Example usage for org.springframework.validation DataBinder getTarget

List of usage examples for org.springframework.validation DataBinder getTarget

Introduction

In this page you can find the example usage for org.springframework.validation DataBinder getTarget.

Prototype

@Nullable
public Object getTarget() 

Source Link

Document

Return the wrapped target object.

Usage

From source file:org.gvnix.web.json.DataBinderDeserializer.java

/**
 * Deserializes JSON content into Map<String, String> format and then uses a
 * Spring {@link DataBinder} to bind the data from JSON message to JavaBean
 * objects./*w ww.  j a v a 2s . c o m*/
 * <p/>
 * It is a workaround for issue
 * https://jira.springsource.org/browse/SPR-6731 that should be removed from
 * next gvNIX releases when that issue will be resolved.
 * 
 * @param parser Parsed used for reading JSON content
 * @param ctxt Context that can be used to access information about this
 *        deserialization activity.
 * 
 * @return Deserializer value
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object deserialize(JsonParser parser, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    JsonToken t = parser.getCurrentToken();
    MutablePropertyValues propertyValues = new MutablePropertyValues();

    // Get target from DataBinder from local thread. If its a bean
    // collection
    // prepares array index for property names. Otherwise continue.
    DataBinder binder = (DataBinder) ThreadLocalUtil
            .getThreadVariable(BindingResult.MODEL_KEY_PREFIX.concat("JSON_DataBinder"));
    Object target = binder.getTarget();

    // For DstaBinderList instances, contentTarget contains the final bean
    // for binding. DataBinderList is just a simple wrapper to deserialize
    // bean wrapper using DataBinder
    Object contentTarget = null;

    if (t == JsonToken.START_OBJECT) {
        String prefix = null;
        if (target instanceof DataBinderList) {
            prefix = binder.getObjectName().concat("[").concat(Integer.toString(((Collection) target).size()))
                    .concat("].");

            // BeanWrapperImpl cannot create new instances if generics
            // don't specify content class, so do it by hand
            contentTarget = BeanUtils.instantiateClass(((DataBinderList) target).getContentClass());
            ((Collection) target).add(contentTarget);
        } else if (target instanceof Map) {
            // TODO
            LOGGER.warn("Map deserialization not implemented yet!");
        }
        Map<String, String> obj = readObject(parser, ctxt, prefix);
        propertyValues.addPropertyValues(obj);
    } else {
        LOGGER.warn("Deserialization for non-object not implemented yet!");
        return null; // TODO?
    }

    // bind to the target object
    binder.bind(propertyValues);

    // Note there is no need to validate the target object because
    // RequestResponseBodyMethodProcessor.resolveArgument() does it on top
    // of including BindingResult as Model attribute

    // For DAtaBinderList the contentTarget contains the final bean to
    // make the binding, so we must return it
    if (contentTarget != null) {
        return contentTarget;
    }
    return binder.getTarget();
}

From source file:org.agatom.springatom.cmp.wizards.core.AbstractWizardProcessor.java

/**
 * If {@link org.springframework.validation.DataBinder#getBindingResult()}} contains any errors then this method
 * will update {@code localResult} with :
 * <ol>//from   w  w w .java 2s  .c  om
 * <li>{@link org.springframework.validation.ObjectError} to {@link org.agatom.springatom.cmp.wizards.data.result.WizardResult#addBindingError(org.springframework.validation.ObjectError)}</li>
 * <li>{@link org.agatom.springatom.cmp.wizards.data.result.FeedbackMessage} to {@link org.agatom.springatom.cmp.wizards.data.result.WizardResult#addFeedbackMessage(FeedbackMessage)}</li>
 * </ol>
 *
 * @param binder      current binder
 * @param locale      current locale
 * @param localResult current result
 *
 * @see org.agatom.springatom.cmp.wizards.data.result.FeedbackMessage#newError()
 * @see org.agatom.springatom.cmp.wizards.data.result.FeedbackType
 * @see org.springframework.validation.Errors
 * @see #getBindErrorFM(org.springframework.validation.ObjectError, java.util.Locale)
 */
private void addErrorsToResultIfAny(final DataBinder binder, final Locale locale,
        final WizardResult localResult) {
    final Errors errors = binder.getBindingResult();
    if (errors.hasErrors()) {
        final Object contextObject = binder.getTarget();
        LOGGER.warn(String.format("Found %d binding bindingResult for context object=%s",
                errors.getErrorCount(), contextObject));
        for (final ObjectError objectError : errors.getAllErrors()) {
            localResult.addFeedbackMessage(this.getBindErrorFM(objectError, locale));
            localResult.addBindingError(objectError);
        }
    }
}

From source file:org.agatom.springatom.cmp.wizards.core.AbstractWizardProcessor.java

@SuppressWarnings("UnusedAssignment")
private void doValidate(final WizardResult result, final DataBinder binder, String step,
        final Map<String, Object> formData, final Locale locale) throws Exception {

    final Object target = binder.getTarget();

    if (!StringUtils.hasText(step)) {
        // Wizard submission, because step is null
        step = this.stepHelperDelegate.getLastStep();
        if (!this.stepHelperDelegate.isValidationEnabled(step)) {
            // reset the step again
            step = null;//from w  w w .  jav  a  2s  .  com
        }
    }

    try {
        final BindingResult bindingResult = binder.getBindingResult();
        boolean alreadyValidate = false;

        if (this.localValidator != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(String.format("Validating via Validator instance=%s", this.localValidator));
            }
            this.validationService.validate(this.localValidator, bindingResult, result);
            alreadyValidate = true;
        }

        if (!alreadyValidate) {
            final ValidationBean bean = new ValidationBean();

            bean.setPartialResult(result);
            bean.setStepId(step);
            bean.setCommandBean(bindingResult.getTarget());
            bean.setCommandBeanName(this.getContextObjectName());
            bean.setFormData(formData);
            bean.setBindingModel(formData);

            if (this.validationService.canValidate(bean)) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(
                            String.format("Validating via validation service for validationBean=%s", bean));
                }
                this.validationService.validate(bean);
                alreadyValidate = true;
            }
        }

        /* Will validate only if not yet validated it is not step submission and wizard is allowed to validate
         * This a last opportunity to validate however unlike validation via
         * - localValidator
         * - validationService
         * this validation will be run only if
         * - not yet validated
         * - current (or last) step has validation flag set
         * - entire wizard has validation flag set
         */
        if (!alreadyValidate && this.isValidationEnabledForStep(step) && this.isValidationEnabled()) {
            LOGGER.debug(String.format(
                    "Not yet validated (tried localValidator and via validationService), assuming that is wizard submission due to step===null, validating through binder"));
            final Validator validator = binder.getValidator();
            if (validator != null) {

                final long startTime = System.nanoTime();
                validator.validate(target, bindingResult);
                final long endTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);

                result.addDebugData(WizardDebugDataKeys.VALIDATION_TIME, endTime);
                result.addDebugData(WizardDebugDataKeys.VALIDATOR,
                        ClassUtils.getShortName(validator.getClass()));

            }
        }

        if (LOGGER.isDebugEnabled()) {
            final Set<Message> messages = result.getValidationMessages();
            final short count = (short) (messages == null ? 0 : messages.size());
            LOGGER.debug(String.format("Validation completed, found %d validation errors", count));
        }
    } catch (Exception exp) {
        // Catch any validation exception and add it as an error
        LOGGER.error("Validation failed either via [localValidator,validationService,binder#validator", exp);
        result.addError(exp);
        result.addFeedbackMessage(FeedbackMessage.newError()
                .setTitle(this.messageSource.getMessage("sa.wiz.validationError.title", locale))
                .setMessage(this.messageSource.getMessage("sa.wiz.validationError.msg",
                        new Object[] { target.toString() }, locale)));
    }

}

From source file:org.agatom.springatom.cmp.wizards.core.AbstractWizardProcessor.java

private void doBind(final DataBinder binder, Map<String, Object> params) throws Exception {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format(
                "Binding allowed request parameters in %s to form object with name '%s', pre-bind formObject toString = %s",
                params, binder.getObjectName(), binder.getTarget()));
        if (binder.getAllowedFields() != null && binder.getAllowedFields().length > 0) {
            LOGGER.debug(//  www .  ja  v a 2s .  com
                    String.format("(Allowed fields are %s)", StylerUtils.style(binder.getAllowedFields())));
        } else {
            LOGGER.debug("(Any field is allowed)");
        }
    }
    binder.bind(new MutablePropertyValues(params));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(String.format(
                "Binding completed for form object with name '%s', post-bind formObject toString = %s",
                binder.getObjectName(), binder.getTarget()));
        LOGGER.debug(String.format("There are [%d] errors, details: %s",
                binder.getBindingResult().getErrorCount(), binder.getBindingResult().getAllErrors()));
    }
}

From source file:utils.play.BugWorkaroundForm.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from  ww w . ja v  a 2 s.  c  om*/
public Form<T> bind(final Map<String, String> data, final String... allowedFields) {
    DataBinder dataBinder = null;
    Map<String, String> objectData = data;
    if (rootName == null) {
        dataBinder = new DataBinder(blankInstance());
    } else {
        dataBinder = new DataBinder(blankInstance(), rootName);
        objectData = new HashMap<String, String>();
        for (String key : data.keySet()) {
            if (key.startsWith(rootName + ".")) {
                objectData.put(key.substring(rootName.length() + 1), data.get(key));
            }
        }
    }
    if (allowedFields.length > 0) {
        dataBinder.setAllowedFields(allowedFields);
    }
    SpringValidatorAdapter validator = new SpringValidatorAdapter(Validation.getValidator());
    dataBinder.setValidator(validator);
    dataBinder.setConversionService(play.data.format.Formatters.conversion);
    dataBinder.setAutoGrowNestedPaths(true);
    dataBinder.bind(new MutablePropertyValues(objectData));

    Set<ConstraintViolation<Object>> validationErrors = validator.validate(dataBinder.getTarget());
    BindingResult result = dataBinder.getBindingResult();

    for (ConstraintViolation<Object> violation : validationErrors) {
        String field = violation.getPropertyPath().toString();
        FieldError fieldError = result.getFieldError(field);
        if (fieldError == null || !fieldError.isBindingFailure()) {
            try {
                result.rejectValue(field,
                        violation.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName(),
                        getArgumentsForConstraint(result.getObjectName(), field,
                                violation.getConstraintDescriptor()),
                        violation.getMessage());
            } catch (NotReadablePropertyException ex) {
                throw new IllegalStateException("JSR-303 validated property '" + field
                        + "' does not have a corresponding accessor for data binding - "
                        + "check your DataBinder's configuration (bean property versus direct field access)",
                        ex);
            }
        }
    }

    if (result.hasErrors()) {
        Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
        for (FieldError error : result.getFieldErrors()) {
            String key = error.getObjectName() + "." + error.getField();
            System.out.println("Error field:" + key);
            if (key.startsWith("target.") && rootName == null) {
                key = key.substring(7);
            }
            List<Object> arguments = new ArrayList<>();
            for (Object arg : error.getArguments()) {
                if (!(arg instanceof org.springframework.context.support.DefaultMessageSourceResolvable)) {
                    arguments.add(arg);
                }
            }
            if (!errors.containsKey(key)) {
                errors.put(key, new ArrayList<ValidationError>());
            }
            errors.get(key).add(new ValidationError(key,
                    error.isBindingFailure() ? "error.invalid" : error.getDefaultMessage(), arguments));
        }
        return new Form(rootName, backedType, data, errors, F.Option.None());
    } else {
        Object globalError = null;
        if (result.getTarget() != null) {
            try {
                java.lang.reflect.Method v = result.getTarget().getClass().getMethod("validate");
                globalError = v.invoke(result.getTarget());
            } catch (NoSuchMethodException e) {
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
        if (globalError != null) {
            Map<String, List<ValidationError>> errors = new HashMap<String, List<ValidationError>>();
            if (globalError instanceof String) {
                errors.put("", new ArrayList<ValidationError>());
                errors.get("").add(new ValidationError("", (String) globalError, new ArrayList()));
            } else if (globalError instanceof List) {
                for (ValidationError error : (List<ValidationError>) globalError) {
                    List<ValidationError> errorsForKey = errors.get(error.key());
                    if (errorsForKey == null) {
                        errors.put(error.key(), errorsForKey = new ArrayList<ValidationError>());
                    }
                    errorsForKey.add(error);
                }
            } else if (globalError instanceof Map) {
                errors = (Map<String, List<ValidationError>>) globalError;
            }

            if (result.getTarget() != null) {
                return new Form(rootName, backedType, data, errors, F.Option.Some((T) result.getTarget()));
            } else {
                return new Form(rootName, backedType, data, errors, F.Option.None());
            }
        }
        return new Form(rootName, backedType, new HashMap<String, String>(data),
                new HashMap<String, List<ValidationError>>(errors), F.Option.Some((T) result.getTarget()));
    }
}

From source file:com.jaspersoft.jasperserver.war.action.FileResourceAction.java

protected void doBind(RequestContext context, DataBinder binder) throws Exception {
    super.doBind(context, binder);
    FileResourceWrapper res = (FileResourceWrapper) binder.getTarget();
    res.afterBind();//  www  .  j a v a2  s. c o m
}

From source file:de.siegmar.securetransfer.controller.SendController.java

/**
 * Process the send form./*from ww  w  . j ava  2  s . c  o m*/
 */
@PostMapping
public ModelAndView create(final HttpServletRequest req, final RedirectAttributes redirectAttributes)
        throws IOException, FileUploadException {

    if (!ServletFileUpload.isMultipartContent(req)) {
        throw new IllegalStateException("No multipart request!");
    }

    // Create encryptionKey and initialization vector (IV) to encrypt data
    final KeyIv encryptionKey = messageService.newEncryptionKey();

    // secret shared with receiver using the link - not stored in database
    final String linkSecret = messageService.newRandomId();

    final DataBinder binder = initBinder();

    final List<SecretFile> tmpFiles = handleStream(req, encryptionKey, binder);

    final EncryptMessageCommand command = (EncryptMessageCommand) binder.getTarget();
    final BindingResult errors = binder.getBindingResult();

    if (!errors.hasErrors() && command.getMessage() == null && (tmpFiles == null || tmpFiles.isEmpty())) {
        errors.reject(null, "Neither message nor files submitted");
    }

    if (errors.hasErrors()) {
        return new ModelAndView(FORM_SEND_MSG, binder.getBindingResult().getModel());
    }

    final String senderId = messageService.storeMessage(command.getMessage(), tmpFiles, encryptionKey,
            HashCode.fromString(linkSecret).asBytes(), command.getPassword(),
            Instant.now().plus(command.getExpirationDays(), ChronoUnit.DAYS));

    redirectAttributes.addFlashAttribute("messageSent", true).addFlashAttribute("message",
            command.getMessage());

    return new ModelAndView("redirect:/send/" + senderId).addObject("linkSecret", linkSecret);
}

From source file:no.abmu.questionnaire.webflow.MuseumStatisticFormAction.java

/**
 * Bind allowed parameters in the external context request parameter map to the form object using given binder.
 * @param context the action execution context, for accessing and setting data in "flow scope" or "request scope"
 * @param binder the data binder to use/*ww  w  .j  a v a  2  s  . com*/
 * @throws Exception when an unrecoverable exception occurs
 */
protected void doBind(RequestContext context, DataBinder binder) throws Exception {
    logger.debug("Execute local doBind");
    if (logger.isDebugEnabled()) {
        logger.debug("Binding allowed request parameters in "
                + StylerUtils.style(context.getExternalContext().getRequestParameterMap())
                + " to form object with name '" + binder.getObjectName() + "', pre-bind formObject toString = "
                + binder.getTarget());
        if (binder.getAllowedFields() != null && binder.getAllowedFields().length > 0) {
            logger.debug("(Allowed fields are " + StylerUtils.style(binder.getAllowedFields()) + ")");
        } else {
            logger.debug("(Any field is allowed)");
        }
    }
    logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBb");
    logger.debug("BBBBBBBBB Value of binder befor binding BBBBBBBBBBBBBBBBBBb");
    logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBb");
    logger.debug(binder);
    binder.bind(new MutablePropertyValues(context.getRequestParameters().asMap()));
    logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBb");
    logger.debug("BBBBBBBBB Value of binder after binding BBBBBBBBBBBBBBBBBBb");
    logger.debug("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBb");
    logger.debug(binder);

    if (logger.isDebugEnabled()) {
        logger.debug("Binding completed for form object with name '" + binder.getObjectName()
                + "', post-bind formObject toString = " + binder.getTarget());
        logger.debug("There are [" + binder.getErrors().getErrorCount() + "] errors, details: "
                + binder.getErrors().getAllErrors());
    }
}