Example #1
0
 /** Return the indexes available for this field (for repeated fields ad List) */
 public List<Integer> indexes() {
   List<Integer> result = new ArrayList<Integer>();
   if (form.value().isDefined()) {
     BeanWrapper beanWrapper = new BeanWrapperImpl(form.value().get());
     beanWrapper.setAutoGrowNestedPaths(true);
     String objectKey = name;
     if (form.name() != null && name.startsWith(form.name() + ".")) {
       objectKey = name.substring(form.name().length() + 1);
     }
     if (beanWrapper.isReadableProperty(objectKey)) {
       Object value = beanWrapper.getPropertyValue(objectKey);
       if (value instanceof Collection) {
         for (int i = 0; i < ((Collection) value).size(); i++) {
           result.add(i);
         }
       }
     }
   } else {
     java.util.regex.Pattern pattern =
         java.util.regex.Pattern.compile(
             "^" + java.util.regex.Pattern.quote(name) + "\\[(\\d+)\\].*$");
     for (String key : form.data().keySet()) {
       java.util.regex.Matcher matcher = pattern.matcher(key);
       if (matcher.matches()) {
         result.add(Integer.parseInt(matcher.group(1)));
       }
     }
   }
   return result;
 }
Example #2
0
 /** Returns the form errors serialized as Json using the given Lang. */
 public org.codehaus.jackson.JsonNode errorsAsJson(play.i18n.Lang lang) {
   Map<String, List<String>> allMessages = new HashMap<String, List<String>>();
   for (String key : errors.keySet()) {
     List<ValidationError> errs = errors.get(key);
     if (errs != null && !errs.isEmpty()) {
       List<String> messages = new ArrayList<String>();
       for (ValidationError error : errs) {
         messages.add(play.i18n.Messages.get(lang, error.message(), error.arguments()));
       }
       allMessages.put(key, messages);
     }
   }
   return play.libs.Json.toJson(allMessages);
 }
Example #3
0
 protected Object[] getArgumentsForConstraint(
     String objectName, String field, ConstraintDescriptor<?> descriptor) {
   List<Object> arguments = new LinkedList<Object>();
   String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field};
   arguments.add(new DefaultMessageSourceResolvable(codes, field));
   // Using a TreeMap for alphabetical ordering of attribute names
   Map<String, Object> attributesToExpose = new TreeMap<String, Object>();
   for (Map.Entry<String, Object> entry : descriptor.getAttributes().entrySet()) {
     String attributeName = entry.getKey();
     Object attributeValue = entry.getValue();
     if (!internalAnnotationAttributes.contains(attributeName)) {
       attributesToExpose.put(attributeName, attributeValue);
     }
   }
   arguments.addAll(attributesToExpose.values());
   return arguments.toArray(new Object[arguments.size()]);
 }
Example #4
0
  /**
   * Retrieve a field.
   *
   * @param key field name
   * @return the field (even if the field does not exist you get a field)
   */
  public Field field(String key) {

    // Value
    String fieldValue = null;
    if (data.containsKey(key)) {
      fieldValue = data.get(key);
    } else {
      if (value.isDefined()) {
        BeanWrapper beanWrapper = new BeanWrapperImpl(value.get());
        beanWrapper.setAutoGrowNestedPaths(true);
        String objectKey = key;
        if (rootName != null && key.startsWith(rootName + ".")) {
          objectKey = key.substring(rootName.length() + 1);
        }
        if (beanWrapper.isReadableProperty(objectKey)) {
          Object oValue = beanWrapper.getPropertyValue(objectKey);
          if (oValue != null) {
            fieldValue =
                play.data.format.Formatters.print(
                    beanWrapper.getPropertyTypeDescriptor(objectKey), oValue);
          }
        }
      }
    }

    // Error
    List<ValidationError> fieldErrors = errors.get(key);
    if (fieldErrors == null) {
      fieldErrors = new ArrayList<ValidationError>();
    }

    // Format
    Tuple<String, List<Object>> format = null;
    BeanWrapper beanWrapper = new BeanWrapperImpl(blankInstance());
    beanWrapper.setAutoGrowNestedPaths(true);
    try {
      for (Annotation a : beanWrapper.getPropertyTypeDescriptor(key).getAnnotations()) {
        Class<?> annotationType = a.annotationType();
        if (annotationType.isAnnotationPresent(play.data.Form.Display.class)) {
          play.data.Form.Display d = annotationType.getAnnotation(play.data.Form.Display.class);
          if (d.name().startsWith("format.")) {
            List<Object> attributes = new ArrayList<Object>();
            for (String attr : d.attributes()) {
              Object attrValue = null;
              try {
                attrValue = a.getClass().getDeclaredMethod(attr).invoke(a);
              } catch (Exception e) {
              }
              attributes.add(attrValue);
            }
            format = Tuple(d.name(), attributes);
          }
        }
      }
    } catch (NullPointerException e) {
    }

    // Constraints
    PropertyDescriptor property =
        play.data.validation.Validation.getValidator()
            .getConstraintsForClass(backedType)
            .getConstraintsForProperty(key);
    List<Tuple<String, List<Object>>> constraints = new ArrayList<Tuple<String, List<Object>>>();
    if (property != null) {
      constraints = Constraints.displayableConstraint(property.getConstraintDescriptors());
    }

    return new Field(this, key, constraints, format, fieldErrors, fieldValue);
  }
Example #5
0
  /**
   * Binds data to this form - that is, handles form submission.
   *
   * @param data data to submit
   * @return a copy of this form filled with the new data
   */
  public Form<T> bind(Map<String, String> data, 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(play.data.validation.Validation.getValidator());
    dataBinder.setValidator(validator);
    dataBinder.setConversionService(play.data.format.Formatters.conversion);
    dataBinder.setAutoGrowNestedPaths(true);
    dataBinder.bind(new MutablePropertyValues(objectData));
    Set<ConstraintViolation<Object>> validationErrors;
    if (groups != null) {
      validationErrors = validator.validate(dataBinder.getTarget(), groups);
    } else {
      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();
        if (key.startsWith("target.") && rootName == null) {
          key = key.substring(7);
        }
        List<Object> arguments = new ArrayList<Object>();
        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, None(), groups);
    } 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) {
          errors.put("", (List<ValidationError>) globalError);
        } else if (globalError instanceof Map) {
          errors = (Map<String, List<ValidationError>>) globalError;
        }
        return new Form(rootName, backedType, data, errors, None(), groups);
      }
      return new Form(
          rootName,
          backedType,
          new HashMap<String, String>(data),
          new HashMap<String, List<ValidationError>>(errors),
          Some((T) result.getTarget()),
          groups);
    }
  }