예제 #1
0
 @SuppressWarnings({"rawtypes", "unchecked"})
 public static <X> X buildMockObject(Class<X> clazz) {
   X x = null;
   try {
     x = clazz.newInstance();
     for (Method method : clazz.getDeclaredMethods()) {
       String mn = method.getName();
       if (mn.startsWith("set")) {
         Class[] parameters = method.getParameterTypes();
         if (parameters.length == 1) {
           Method getMethod =
               MethodUtils.getAccessibleMethod(clazz, "get" + mn.substring(3), null);
           if (getMethod != null) {
             if (getMethod.getName().equals("getId")) {
               continue;
             }
             Object value = null;
             Class parameter = parameters[0];
             if (parameter.isAssignableFrom(String.class)) {
               Column column = getMethod.getAnnotation(Column.class);
               int columnLength = 32;
               if (column != null && column.length() < columnLength) {
                 columnLength = column.length();
               }
               Size size = getMethod.getAnnotation(Size.class);
               if (size != null && size.min() < columnLength) {
                 columnLength = size.min();
               }
               value = RandomStringUtils.randomAlphabetic(columnLength);
             } else if (parameter.isAssignableFrom(Date.class)) {
               value = new Date();
             } else if (parameter.isAssignableFrom(BigDecimal.class)) {
               value = new BigDecimal(new Random().nextDouble());
             } else if (parameter.isAssignableFrom(Integer.class)) {
               value = new Random().nextInt();
             } else if (parameter.isAssignableFrom(Boolean.class)) {
               value = new Random().nextBoolean();
             } else if (parameter.isEnum()) {
               Method m = parameter.getDeclaredMethod("values", null);
               Object[] result = (Object[]) m.invoke(parameter.getEnumConstants()[0], null);
               value = result[new Random().nextInt(result.length)];
             }
             if (value != null) {
               MethodUtils.invokeMethod(x, mn, value);
               logger.debug("{}={}", method.getName(), value);
             }
           }
         }
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return x;
 }
 @Test
 @SpecAssertions({
   @SpecAssertion(section = "6.11", id = "a"),
   @SpecAssertion(section = "6.11", id = "b"),
   @SpecAssertion(section = "6.11", id = "d")
 })
 public void testAnnotationAndMapParametersReflectParameterOverriding() {
   ConstraintDescriptor<?> descriptor = getConstraintDescriptor(Person.class, "firstName");
   Set<ConstraintDescriptor<?>> composingDescriptors = descriptor.getComposingConstraints();
   assertEquals(composingDescriptors.size(), 2, "Wrong number of composing constraints");
   boolean hasSize = false;
   for (ConstraintDescriptor<?> desc : composingDescriptors) {
     if (desc.getAnnotation().annotationType().equals(Size.class)) {
       hasSize = true;
       Size sizeAnn = (Size) desc.getAnnotation();
       assertEquals(sizeAnn.min(), 5, "The min parameter should reflect the overridden parameter");
       assertEquals(
           desc.getAttributes().get("min"),
           5,
           "The min parameter should reflect the overridden parameter");
     } else if (desc.getAnnotation().annotationType().equals(NotNull.class)) {
     } else {
       fail("Unexpected annotation.");
     }
   }
   assertTrue(hasSize, "Size composed annotation not found");
 }
예제 #3
0
 public void initialize(Size parameters) {
   min = parameters.min();
   max = parameters.max();
   validateParameters();
 }
  public static void buildValidatorAttribute(
      String validatorAttrValue,
      AbstractUITag tag,
      ValueStack stack,
      HttpServletRequest req,
      UIBean uiBean) {
    Map<String, Object> dynamicAttributes = new HashMap<String, Object>();
    if (validatorAttrValue == null) {
      Map<String, Object> validator = new HashMap<String, Object>();
      Map<String, String> messages = new HashMap<String, String>();
      CompoundRoot rootList = stack.getRoot();
      Object entity = null;
      Object controller = null;
      for (Object obj : rootList) {
        if (obj instanceof Persistable) {
          entity = obj;
        } else if (obj instanceof ActionSupport) {
          controller = obj;
        }
      }

      if (entity != null) {
        try {
          String tagName = tag.name;
          Method method =
              OgnlRuntime.getGetMethod(
                  (OgnlContext) stack.getContext(), entity.getClass(), tagName);
          if (method == null) {
            String[] tagNameSplits = StringUtils.split(tagName, ".");
            if (tagNameSplits.length >= 2) {
              Class<?> retClass = entity.getClass();
              for (String tagNameSplit : tagNameSplits) {
                method =
                    OgnlRuntime.getGetMethod(
                        (OgnlContext) stack.getContext(), retClass, tagNameSplit);
                if (method != null) {
                  retClass = method.getReturnType();
                }
              }
              if (method == null) {
                retClass = controller.getClass();
                for (String tagNameSplit : tagNameSplits) {
                  method =
                      OgnlRuntime.getGetMethod(
                          (OgnlContext) stack.getContext(), retClass, tagNameSplit);
                  if (method != null) {
                    retClass = method.getReturnType();
                  }
                }
              }
            }
          }

          if (method != null) {
            Column column = method.getAnnotation(Column.class);
            if (column != null) {
              if (column.nullable() == false) {
                if (tag.requiredLabel == null) {
                  uiBean.setRequiredLabel("true");
                }
              }
              if (column.unique() == true) {
                validator.put("unique", "true");
              }
            }

            Class<?> retType = method.getReturnType();
            if (retType == LocalDate.class) {
              validator.put("date", true);
              validator.put("dateISO", true);
            } else if (retType == LocalDateTime.class) {
              validator.put("timestamp", true);
            } else if (retType == DateTime.class || retType == Date.class) {
              JsonSerialize jsonSerialize = method.getAnnotation(JsonSerialize.class);
              if (jsonSerialize != null) {
                if (JodaDateJsonSerializer.class == jsonSerialize.using()
                    || DateJsonSerializer.class == jsonSerialize.using()) {
                  validator.put("date", true);
                  validator.put("dateISO", true);
                } else if (JodaDateTimeJsonSerializer.class == jsonSerialize.using()
                    || DateTimeJsonSerializer.class == jsonSerialize.using()) {
                  validator.put("timestamp", true);
                }
              }
            } else if (retType == BigDecimal.class) {
              validator.put("number", true);
            } else if (retType == Integer.class) {
              validator.put("number", true);
              validator.put("digits", true);
            } else if (retType == Long.class) {
              validator.put("number", true);
              validator.put("digits", true);
            }

            Size size = method.getAnnotation(Size.class);
            if (size != null) {
              if (size.min() > 0) {
                validator.put("minlength", size.min());
              }
              if (size.max() < Integer.MAX_VALUE) {
                validator.put("maxlength", size.max());
              }
            }

            Email email = method.getAnnotation(Email.class);
            if (email != null) {
              validator.put("email", true);
            }

            Pattern pattern = method.getAnnotation(Pattern.class);
            if (pattern != null) {
              validator.put("regex", pattern.regexp());
              String message = pattern.message();
              if (!"{javax.validation.constraints.Pattern.message}".equals(message)) {
                messages.put("regex", message);
              }
            }
          }
        } catch (IntrospectionException e) {
          e.printStackTrace();
        } catch (OgnlException e) {
          e.printStackTrace();
        }
      }

      if (validator.size() > 0) {
        try {
          if (messages.size() > 0) {
            validator.put("messages", messages);
          }
          String json = mapper.writeValueAsString(validator);
          json = json.replaceAll("\\\"", "'");
          dynamicAttributes.put("validator", json);
          uiBean.setDynamicAttributes(dynamicAttributes);
        } catch (JsonProcessingException e) {
          e.printStackTrace();
        }
      }
    } else {
      dynamicAttributes.put("validator", validatorAttrValue);
      uiBean.setDynamicAttributes(dynamicAttributes);
    }
  }