예제 #1
0
  public static List<Validator> getValidators(Class<?> clazz, String property, String name) {
    try {
      List<Validator> validators = new ArrayList<Validator>();
      while (!clazz.equals(Object.class)) {
        try {
          Field field = clazz.getDeclaredField(property);
          for (Annotation annotation : field.getDeclaredAnnotations()) {

            if (annotation.annotationType().getName().startsWith("annotations.validation")) {
              // play.Logger.info("Annotation " + annotation.toString(), annotation);

              Validator validator = new Validator(annotation);
              validators.add(validator);
              if (annotation.annotationType().equals(Equals.class)) {
                validator.params.put("equalsTo", name + "." + ((Equals) annotation).value());
              }
              if (annotation.annotationType().equals(InFuture.class)) {
                validator.params.put("reference", ((InFuture) annotation).value());
              }
              if (annotation.annotationType().equals(InPast.class)) {
                validator.params.put("reference", ((InPast) annotation).value());
              }
            }
          }
          break;
        } catch (NoSuchFieldException e) {
          clazz = clazz.getSuperclass();
        }
      }
      return validators;
    } catch (Exception e) {
      play.Logger.error(e.fillInStackTrace().getMessage(), e);
      return new ArrayList<Validator>();
    }
  }
예제 #2
0
  public static void main(String[] args) throws ClassNotFoundException {
    if (args.length < 1) {
      System.out.println("arguments: annotated classes");
      System.exit(0);
    }
    for (String className : args) {
      Class<?> cl = Class.forName(className);
      DBTable dbTable = cl.getAnnotation(DBTable.class);
      if (dbTable == null) {
        System.out.println("No DBTable annotations in class" + className);
        continue;
      }
      String tableName = dbTable.name();
      // if the tablename is empty, use the Class name
      if (tableName.length() < 1) {
        tableName = cl.getName().toUpperCase();
      }
      List<String> columnDefs = new ArrayList<>();
      for (Field field : cl.getDeclaredFields()) {
        String columnName = null;
        Annotation[] annotations = field.getDeclaredAnnotations();
        if (annotations.length < 1) {
          continue;
        }
        if (annotations[0] instanceof SQLInteger) {
          SQLInteger sInt = (SQLInteger) annotations[0];
          if (sInt.name().length() < 1) {
            columnName = field.getName().toLowerCase();
          } else {
            columnName = sInt.name();
          }
          columnDefs.add(columnName + " INT" + getConstraints(sInt.constraints()));
        }

        if (annotations[0] instanceof SQLString) {
          SQLString sString = (SQLString) annotations[0];
          if (sString.name().length() < 1) {
            columnName = field.getName().toLowerCase();
          } else {
            columnName = sString.name();
          }
          columnDefs.add(
              columnName
                  + " VARCHAR("
                  + sString.value()
                  + ")"
                  + getConstraints(sString.constraints()));
        }

        StringBuilder createCommand = new StringBuilder("CREATE TABLE " + tableName + "(");
        for (String colunmDef : columnDefs) {
          createCommand.append("\n\t" + colunmDef + ",");
        }
        // remove trailing comma
        String tableCreate = createCommand.substring(0, createCommand.length() - 1) + ")";
        System.out.println("table creating for " + className + " is:\n" + tableCreate);
      }
    }
  }
예제 #3
0
 /**
  * Returns an array of {@link Annotation} objects reflecting all annotations declared by this
  * field, or an empty array if there are none. Does not include inherited annotations.
  */
 public Annotation[] getDeclaredAnnotations() {
   java.lang.annotation.Annotation[] annotations = field.getDeclaredAnnotations();
   Annotation[] result = new Annotation[annotations.length];
   for (int i = 0; i < annotations.length; i++) {
     result[i] = new Annotation(annotations[i]);
   }
   return result;
 }
 @Override
 public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
   for (Annotation annotation : field.getDeclaredAnnotations()) {
     if (annotation.annotationType().getName().startsWith("org.mockito")) {
       this.annotations.add(annotation);
     }
   }
 }
  private void bindAutoBindFields() {
    for (Field field : classpathScanner.getFields()) {
      if (ignoreClasses.contains(field.getDeclaringClass())) {
        continue;
      }

      bindAnnotations(field.getDeclaredAnnotations());
    }
  }
 @Test
 public void testAnnotations() throws Exception {
   assertThat(
       describe(first).getDeclaredAnnotations(), is((AnnotationList) new AnnotationList.Empty()));
   assertThat(
       describe(second).getDeclaredAnnotations(),
       is(
           (AnnotationList)
               new AnnotationList.ForLoadedAnnotation(second.getDeclaredAnnotations())));
 }
예제 #7
0
 /**
  * Returns an {@link Annotation} object reflecting the annotation provided, or null of this field
  * doesn't have such an annotation. This is a convenience function if the caller knows already
  * which annotation type he's looking for.
  */
 public Annotation getDeclaredAnnotation(
     Class<? extends java.lang.annotation.Annotation> annotationType) {
   java.lang.annotation.Annotation[] annotations = field.getDeclaredAnnotations();
   if (annotations == null) {
     return null;
   }
   for (java.lang.annotation.Annotation annotation : annotations) {
     if (annotation.annotationType().equals(annotationType)) {
       return new Annotation(annotation);
     }
   }
   return null;
 }
예제 #8
0
 /**
  * TODO Refactor, instanceof code smell. TODO Add new annotation in here for the moment
  *
  * @param ai
  * @param instance
  */
 private void initClassFields(final Class<? extends AI> ai, final AI instance)
     throws IllegalAccessException {
   for (Field field : ai.getDeclaredFields()) {
     for (Annotation annotation : field.getDeclaredAnnotations()) {
       if (annotation instanceof AIDigitParameters) {
         initClassFieldDigitParameter(ai, instance, field, (AIDigitParameters) annotation);
       } else if (annotation instanceof AIBooleanParameter) {
         initClassFieldBooleanParameter(ai, instance, field, (AIBooleanParameter) annotation);
       }
       // else if ( annotation instanceof WhatEverFieldAnnotation ) { } -> put it here!
     }
   }
 }
  /**
   * Extract enumeration constraints
   *
   * @param method is the method to have a look at
   * @return a constraints string
   */
  protected String getConstraints(Method method) {
    Class<?> returnType = method.getReturnType();

    if (returnType.isEnum()) {
      return getEnumerationConstants(returnType);
    }

    Field field = this.getFieldForMethod(method);
    if (field != null && field.getDeclaredAnnotations().length > 0) {
      return getFieldAnnotationConstraints(field);
    }

    return null;
  }
예제 #10
0
 static RequestFieldInfo getFieldAnnotations(Field field, Scope scope) {
   RequestFieldInfo result = new RequestFieldInfo();
   result.name = field.getName();
   result.type = field.getType();
   for (Annotation annotation : field.getDeclaredAnnotations()) {
     if (annotation instanceof Modifiable) {
       result.modifiable = (Modifiable) annotation;
     } else if (annotation instanceof Required) {
       result.required = (Required) annotation;
     }
   }
   result.scope = scope;
   return result;
 }
  public DataConverter(Class<T> clazz)
      throws TooManyPrimaryKeys, NotAnnotatedAsTableClassException, PrimaryKeyIsNotColumnException,
          NoPrimaryKeyException {
    if (clazz.getAnnotation(Table.class) == null) {
      throw new NotAnnotatedAsTableClassException();
    } else {
      if (!clazz.getDeclaredAnnotation(Table.class).name().equals("")) {
        tableName = clazz.getDeclaredAnnotation(Table.class).name();
      } else {
        tableName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, clazz.getSimpleName());
      }
    }
    fields = new ArrayList<FieldConverter>();
    for (Field field : clazz.getDeclaredFields()) {
      Class<?> type = field.getType();
      Annotation primaryKeyAnnotation = field.getDeclaredAnnotation(PrimaryKey.class),
          columnAnnotation = field.getDeclaredAnnotation(Column.class);

      if (primaryKeyAnnotation != null) {
        if (columnAnnotation == null) {
          throw new PrimaryKeyIsNotColumnException();
        }
        if (primaryKeyField != null) {
          throw new TooManyPrimaryKeys();
        }
        primaryKeyField = field;
      }
      if (columnAnnotation != null) {
        String name = null;
        if (!field.getDeclaredAnnotation(Column.class).name().equals("")) {
          name = field.getDeclaredAnnotation(Column.class).name();
        } else {
          name = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, field.getName());
        }
        FieldConverter currentFieldConverter = new FieldConverter(name, field);
        fields.add(currentFieldConverter);
        if (field.equals(primaryKeyField)) {
          primaryKeyFieldConverter = currentFieldConverter;
        }
      }
      Annotation[] annotations = field.getDeclaredAnnotations();
      for (Annotation annotation : annotations) {
        annotation.getClass();
      }
    }
    if (primaryKeyField == null) {
      throw new NoPrimaryKeyException();
    }
  }
  private void addAsTestedFieldIfApplicable(@NotNull Field fieldFromTestClass) {
    for (Annotation fieldAnnotation : fieldFromTestClass.getDeclaredAnnotations()) {
      Tested testedMetadata;

      if (fieldAnnotation instanceof Tested) {
        testedMetadata = (Tested) fieldAnnotation;
      } else {
        testedMetadata = fieldAnnotation.annotationType().getAnnotation(Tested.class);
      }

      if (testedMetadata != null) {
        TestedField testedField =
            new TestedField(injectionState, fieldFromTestClass, testedMetadata);
        testedFields.add(testedField);
        break;
      }
    }
  }
예제 #13
0
  /** Traverse all fields and set up parameters according o @ZkParameters annotation. */
  public static void setupZkParameters(Object instance) {
    for (Field field : ReflectionHelper.getAllFields(instance.getClass())) {
      for (Annotation annotation : field.getDeclaredAnnotations()) {
        if (annotation instanceof ZkParameter)
          setupZkParameter(
              (ZkParameter) annotation,
              getName((ZkParameter) annotation, field),
              field.getType(),
              field,
              null,
              instance);
      }
    }

    for (Method method : ReflectionHelper.getAllMethods(instance.getClass())) {
      for (Annotation annotation : method.getDeclaredAnnotations()) {
        if (annotation instanceof ZkParameter) {
          String paramName = ((ZkParameter) annotation).name();
          if (StringHelper.isNull(paramName)) {
            if (!method.getName().startsWith("set"))
              throw new InstantiationError(
                  "@ZkParameter must be on method in form of setXXX(ParamType p)  (e.g. setParamName). "
                      + "Found: "
                      + method.getName());
            paramName = getMethodLowerCase(method.getName().substring(3));
          }

          if (method.getParameterTypes().length != 1)
            throw new InstantiationError(
                "@ZkParameter must be on method in form of setXXX(ParamType p), wrong number of parameters. "
                    + "Actual number of parameters: "
                    + method.getParameterTypes().length);

          setupZkParameter(
              (ZkParameter) annotation,
              paramName,
              method.getParameterTypes()[0],
              null,
              method,
              instance);
        }
      }
    }
  }
예제 #14
0
 private void checkResourceClassFields(final boolean encodedFlag, boolean isInSingleton) {
   for (Field field :
       AccessController.doPrivileged(ReflectionHelper.getDeclaredFieldsPA(handlerClass))) {
     if (field.getDeclaredAnnotations().length > 0) {
       Parameter p =
           Parameter.create(
               handlerClass,
               field.getDeclaringClass(),
               encodedFlag || field.isAnnotationPresent(Encoded.class),
               field.getType(),
               field.getGenericType(),
               field.getAnnotations());
       if (null != p) {
         ResourceMethodValidator.validateParameter(
             p, field, field.toGenericString(), field.getName(), isInSingleton);
       }
     }
   }
 }
예제 #15
0
 /**
  * Method called to add field mix-ins from given mix-in class (and its fields) into already
  * collected actual fields (from introspected classes and their super-classes)
  */
 protected void _addFieldMixIns(Class<?> mixin, Map<String, AnnotatedField> fields) {
   for (Field mixinField : mixin.getDeclaredFields()) {
     /* there are some dummy things (static, synthetic); better
      * ignore
      */
     if (!_isIncludableField(mixinField)) {
       continue;
     }
     String name = mixinField.getName();
     // anything to mask? (if not, quietly ignore)
     AnnotatedField maskedField = fields.get(name);
     if (maskedField != null) {
       for (Annotation a : mixinField.getDeclaredAnnotations()) {
         if (_annotationIntrospector.isHandled(a)) {
           maskedField.addOrOverride(a);
         }
       }
     }
   }
 }
예제 #16
0
  private void handleField(Field field) {
    Annotation[] annotations = field.getDeclaredAnnotations();

    for (Annotation annotation : annotations) {
      if (annotation.annotationType().isAssignableFrom(Preference.class)) {
        Preference preferenceAnnotation = (Preference) annotation;

        if (!preferenceAnnotation.enabled()) {
          return;
        }

        if (!preferenceAnnotation.name().isEmpty()) {
          mFieldsPreferencesMap.put(preferenceAnnotation.name(), field);
          return;
        }
      }
    }

    mFieldsPreferencesMap.put(field.getName(), field);
  }
  private static List<String> getColumnDefinitions(Class<?> clazz) {
    List<String> columnDefinitions = new ArrayList<>();
    for (Field field : clazz.getDeclaredFields()) {
      String columnName;
      Annotation[] annotations = field.getDeclaredAnnotations();
      if (annotations.length < 1) {
        logger.info("{} field is not a DB table column.", field.getName());
        continue;
      }

      if (annotations[0] instanceof SqlInteger) {
        SqlInteger sqlInteger = (SqlInteger) annotations[0];
        if (sqlInteger.name().length() < 1) {
          columnName = field.getName().toUpperCase();
        } else {
          columnName = sqlInteger.name();
        }
        columnDefinitions.add(columnName + " INT " + getConstraints(sqlInteger.constraints()));
      }

      if (annotations[0] instanceof SqlString) {
        SqlString sqlString = (SqlString) annotations[0];
        if (sqlString.name().length() < 1) {
          columnName = field.getName().toUpperCase();
        } else {
          columnName = sqlString.name();
        }
        columnDefinitions.add(
            columnName
                + " VARCHAR("
                + sqlString.value()
                + ")"
                + getConstraints(sqlString.constraints()));
      }
    }
    return columnDefinitions;
  }
예제 #18
0
 protected AnnotatedField _constructField(Field f) {
   return new AnnotatedField(f, _collectRelevantAnnotations(f.getDeclaredAnnotations()));
 }
예제 #19
0
  /**
   * 读取并解析业务实体中的注解信息
   *
   * @param entityClass 业务实体
   * @return
   * @throws UtilException
   */
  @SuppressWarnings("unchecked")
  public static EntityBinder readEntity(Class<?> entityClass) throws UtilException {
    if (entityBinders.contains(entityClass)) {
      return entityBinders.get(entityClass);
    }
    EntityBinder entityBinder = new EntityBinder();
    // 得到key为属性名,value为属性对应的PropertyDescriptor的HashMap
    try {
      for (PropertyDescriptor pd : Introspector.getBeanInfo(entityClass).getPropertyDescriptors()) {
        if (pd.getName().equals("class")) {
          continue;
        }
        Field field = getField(entityClass, pd.getName());

        for (Annotation annotation : field.getDeclaredAnnotations()) {
          // 解析主键
          if (pd.getReadMethod().isAnnotationPresent(Id.class)
              || pd.getReadMethod().isAnnotationPresent(EmbeddedId.class)) {
            entityBinder
                .getIdBinderList()
                .add(
                    new IdBinder(
                        pd.getName(),
                        pd,
                        pd.getReadMethod().getAnnotation(EmbeddedId.class) == null
                            ? Id.class
                            : EmbeddedId.class));
            continue;
          }
          if (!entityBinder.getAnnotationBinders().contains(annotation.annotationType())) {
            try {
              entityBinder
                  .getAnnotationBinders()
                  .add(
                      new AnnotationBinder(
                          ((BaseResolver)
                              SpringContextUtils.getBean(
                                  StringUtils.join(
                                      annotation.annotationType().getSimpleName(), "Resolver"))),
                          (Class<Annotation>) annotation.annotationType()));
            } catch (NoSuchBeanDefinitionException e) {

              logger.warn("没有找到注解对应的解析器{}", annotation.annotationType().getName());
              continue;
            }
          }
          entityBinder
              .getAnnotationBinders()
              .get(
                  entityBinder
                      .getAnnotationBinders()
                      .indexOf(
                          new AnnotationBinder((Class<Annotation>) annotation.annotationType())))
              .getFields()
              .add(field);
        }
      }
    } catch (Exception e) {
      throw new UtilException(e);
    }
    entityBinders.put(entityClass, entityBinder);
    return entityBinder;
  }
예제 #20
0
  public static void main(String[] args) throws Exception {
    String className = "annotations.Member";
    Class<?> cl = Class.forName(className);

    // 通过类名获取注解
    DBTable dbTable = cl.getAnnotation(DBTable.class);

    if (dbTable == null) {
      System.out.println("no DBTable annotation in class" + className);
    }

    String tableName = dbTable.name();
    if (tableName.length() < 1) {
      tableName = cl.getName().toUpperCase();
    }

    List<String> columnDefs = new ArrayList<String>();

    // 通过类名获取注解的属性
    for (Field field : cl.getDeclaredFields()) {
      String columnName = null;

      // 一个属性上面可能有多个注解
      Annotation[] anns = field.getDeclaredAnnotations();
      if (anns.length < 1) {
        continue;
      }

      if (anns[0] instanceof SqlInteger) {
        SqlInteger sInt = (SqlInteger) anns[0];

        if (sInt.name().length() < 1) {
          columnName = field.getName().toUpperCase();
        } else {
          columnName = sInt.name();
        }

        columnDefs.add(columnName + " INT" + getConstraints(sInt.constraints()));
      }

      if (anns[0] instanceof SqlString) {
        SqlString sString = (SqlString) anns[0];

        if (sString.name().length() < 1) {
          columnName = field.getName().toUpperCase();
        } else {
          columnName = sString.name();
        }

        columnDefs.add(
            columnName
                + " VARCHAR("
                + sString.value()
                + ")"
                + getConstraints(sString.constraints()));
      }
    }

    StringBuilder createCommand = new StringBuilder("create table " + tableName + "(");

    for (String columnDef : columnDefs) {
      createCommand.append("\n\t" + columnDef + ",");
    }

    String tableCreate = createCommand.substring(0, createCommand.length() - 1) + ");";
    System.out.println("sql:" + tableCreate);
  }
  public static void populateObject(
      String operatorName,
      int operatorNum,
      String dataFlowName,
      Map<String, Object> objectProperties,
      Object top,
      EngineImportService engineImportService,
      EPDataFlowOperatorParameterProvider optionalParameterProvider,
      Map<String, Object> optionalParameterURIs)
      throws ExprValidationException {
    Class applicableClass = top.getClass();
    Set<WriteablePropertyDescriptor> writables =
        PropertyHelper.getWritableProperties(applicableClass);
    Set<Field> annotatedFields =
        JavaClassHelper.findAnnotatedFields(top.getClass(), DataFlowOpParameter.class);
    Set<Method> annotatedMethods =
        JavaClassHelper.findAnnotatedMethods(top.getClass(), DataFlowOpParameter.class);

    // find catch-all methods
    Set<Method> catchAllMethods = new LinkedHashSet<Method>();
    if (annotatedMethods != null) {
      for (Method method : annotatedMethods) {
        DataFlowOpParameter anno =
            (DataFlowOpParameter)
                JavaClassHelper.getAnnotations(
                        DataFlowOpParameter.class, method.getDeclaredAnnotations())
                    .get(0);
        if (anno.all()) {
          if (method.getParameterTypes().length == 2
              && method.getParameterTypes()[0] == String.class
              && method.getParameterTypes()[1] == Object.class) {
            catchAllMethods.add(method);
            continue;
          }
          throw new ExprValidationException("Invalid annotation for catch-call");
        }
      }
    }

    // map provided values
    for (Map.Entry<String, Object> property : objectProperties.entrySet()) {
      boolean found = false;
      String propertyName = property.getKey();

      // invoke catch-all setters
      for (Method method : catchAllMethods) {
        try {
          method.invoke(top, new Object[] {propertyName, property.getValue()});
        } catch (IllegalAccessException e) {
          throw new ExprValidationException(
              "Illegal access invoking method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + method.getName(),
              e);
        } catch (InvocationTargetException e) {
          throw new ExprValidationException(
              "Exception invoking method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + method.getName()
                  + ": "
                  + e.getTargetException().getMessage(),
              e);
        }
        found = true;
      }

      if (propertyName.toLowerCase().equals(CLASS_PROPERTY_NAME)) {
        continue;
      }

      // use the writeable property descriptor (appropriate setter method) from writing the property
      WriteablePropertyDescriptor descriptor =
          findDescriptor(applicableClass, propertyName, writables);
      if (descriptor != null) {
        Object coerceProperty =
            coerceProperty(
                propertyName,
                applicableClass,
                property.getValue(),
                descriptor.getType(),
                engineImportService,
                false);

        try {
          descriptor.getWriteMethod().invoke(top, new Object[] {coerceProperty});
        } catch (IllegalArgumentException e) {
          throw new ExprValidationException(
              "Illegal argument invoking setter method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + descriptor.getWriteMethod().getName()
                  + " provided value "
                  + coerceProperty,
              e);
        } catch (IllegalAccessException e) {
          throw new ExprValidationException(
              "Illegal access invoking setter method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + descriptor.getWriteMethod().getName(),
              e);
        } catch (InvocationTargetException e) {
          throw new ExprValidationException(
              "Exception invoking setter method for property '"
                  + propertyName
                  + "' for class "
                  + applicableClass.getName()
                  + " method "
                  + descriptor.getWriteMethod().getName()
                  + ": "
                  + e.getTargetException().getMessage(),
              e);
        }
        continue;
      }

      // find the field annotated with {@link @GraphOpProperty}
      for (Field annotatedField : annotatedFields) {
        DataFlowOpParameter anno =
            (DataFlowOpParameter)
                JavaClassHelper.getAnnotations(
                        DataFlowOpParameter.class, annotatedField.getDeclaredAnnotations())
                    .get(0);
        if (anno.name().equals(propertyName) || annotatedField.getName().equals(propertyName)) {
          Object coerceProperty =
              coerceProperty(
                  propertyName,
                  applicableClass,
                  property.getValue(),
                  annotatedField.getType(),
                  engineImportService,
                  true);
          try {
            annotatedField.setAccessible(true);
            annotatedField.set(top, coerceProperty);
          } catch (Exception e) {
            throw new ExprValidationException(
                "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
          }
          found = true;
          break;
        }
      }
      if (found) {
        continue;
      }

      throw new ExprValidationException(
          "Failed to find writable property '"
              + propertyName
              + "' for class "
              + applicableClass.getName());
    }

    // second pass: if a parameter URI - value pairs were provided, check that
    if (optionalParameterURIs != null) {
      for (Field annotatedField : annotatedFields) {
        try {
          annotatedField.setAccessible(true);
          String uri = operatorName + "/" + annotatedField.getName();
          if (optionalParameterURIs.containsKey(uri)) {
            Object value = optionalParameterURIs.get(uri);
            annotatedField.set(top, value);
            if (log.isDebugEnabled()) {
              log.debug(
                  "Found parameter '"
                      + uri
                      + "' for data flow "
                      + dataFlowName
                      + " setting "
                      + value);
            }
          } else {
            if (log.isDebugEnabled()) {
              log.debug("Not found parameter '" + uri + "' for data flow " + dataFlowName);
            }
          }
        } catch (Exception e) {
          throw new ExprValidationException(
              "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
        }
      }
    }

    // third pass: if a parameter provider is provided, use that
    if (optionalParameterProvider != null) {
      for (Field annotatedField : annotatedFields) {
        try {
          annotatedField.setAccessible(true);
          Object provided = annotatedField.get(top);
          Object value =
              optionalParameterProvider.provide(
                  new EPDataFlowOperatorParameterProviderContext(
                      operatorName,
                      annotatedField.getName(),
                      top,
                      operatorNum,
                      provided,
                      dataFlowName));
          if (value != null) {
            annotatedField.set(top, value);
          }
        } catch (Exception e) {
          throw new ExprValidationException(
              "Failed to set field '" + annotatedField.getName() + "': " + e.getMessage(), e);
        }
      }
    }
  }
예제 #22
0
  protected boolean validateValue(
      Class<?> beanClazz, String name, JSONObject jsonObj, ValidationException validationException)
      throws JSONException {
    boolean rightValue = true;

    try {
      Field field = beanClazz.getDeclaredField(name);
      Annotation[] annotations = field.getDeclaredAnnotations();

      ArrayList<Annotation> validators = new ArrayList<Annotation>();
      boolean inputRequired = false;
      for (Annotation annotation : annotations) {

        if (AnnotationValidator.isValidationAnnotation(annotation)) {
          validators.add(annotation);
        }

        if (!inputRequired) {
          if (annotation instanceof com.maxiaohua.genealogy.fw.core.validator.type.NotNull
              || annotation instanceof com.maxiaohua.genealogy.fw.core.validator.type.NotEmpty) {
            inputRequired = true;
          } else if (annotation instanceof MultiField) {
            MultiField multiField = (MultiField) annotation;
            if (multiField
                .validator()
                .equals(com.maxiaohua.genealogy.fw.core.validator.type.NotAllEmpty.class)) {
              inputRequired = true;
            }
          }
        }
      }

      boolean sitei = jsonObj.containsKey(name);

      if (inputRequired || (sitei && jsonObj.get(name) != null)) {

        Collections.sort(
            validators,
            new Comparator<Annotation>() {
              public int compare(Annotation arg0, Annotation arg1) {
                int result = -1;
                try {
                  Integer junban0 =
                      (Integer) arg0.getClass().getDeclaredMethod(KEY_JUNBAN).invoke(arg0);
                  Integer junban2 =
                      (Integer) arg1.getClass().getDeclaredMethod(KEY_JUNBAN).invoke(arg1);
                  result = junban0.compareTo(junban2);
                } catch (NoSuchMethodException nsme) {
                  errorLogger.writeErrorLog(nsme.getMessage());
                  appLogger.error(nsme.getMessage(), nsme);
                  debugLogger.error(nsme.getMessage(), nsme);
                } catch (InvocationTargetException ite) {
                  errorLogger.writeErrorLog(ite.getMessage());
                  appLogger.error(ite.getMessage(), ite);
                  debugLogger.error(ite.getMessage(), ite);

                } catch (IllegalAccessException iae) {
                  errorLogger.writeErrorLog(iae.getMessage());
                  appLogger.error(iae.getMessage(), iae);
                  debugLogger.error(iae.getMessage(), iae);
                }
                return result;
              }
            });

        for (Annotation annotation : validators) {

          if (annotation instanceof MultiField) {
            MultiField multiField = (MultiField) annotation;
            String[] fieldNames = multiField.others();
            if (fieldNames != null) {

              Object[] values = new Object[fieldNames.length + 1];
              if (sitei) {
                values[0] = jsonObj.get(name);
              }
              for (int i = 0; i < fieldNames.length; i++) {
                if (jsonObj.containsKey(fieldNames[i])) {
                  values[i + 1] = jsonObj.get(fieldNames[i]);
                }
              }

              AnnotationValidator validator = AnnotationValidationUtil.validate(values, annotation);

              if (validator != null) {

                String errorCode = validator.getErrorCode();
                String fieldBungen = beanClazz.getName() + "." + name;
                Alias alias = (Alias) field.getAnnotation(Alias.class);
                if (alias != null) {
                  fieldBungen = alias.value();
                }
                String[] parameters = null;
                String[] ps = validator.getMsgParameters();
                if (ps == null) {
                  parameters = new String[2];
                  parameters[0] = fieldBungen;
                  StringBuffer othersBungen = new StringBuffer();
                  for (int i = 0; i < fieldNames.length; i++) {
                    try {
                      String bungen = beanClazz.getName() + "." + name;
                      Field f = beanClazz.getDeclaredField(fieldNames[i]);
                      Alias a = (Alias) f.getAnnotation(Alias.class);
                      if (a != null) {
                        bungen = a.value();
                      }
                      if (i == 0) {
                        othersBungen.append(bungen);
                      } else {
                        othersBungen.append(",").append(bungen);
                      }
                    } catch (NoSuchFieldException nsfe) {
                      nsfe.printStackTrace();
                    }
                  }
                  parameters[1] = othersBungen.toString();
                } else {
                  parameters = new String[ps.length + 1];
                  parameters[0] = fieldBungen;
                  for (int i = 0; i < ps.length; i++) {
                    parameters[i + 1] = ps[i];
                  }
                }

                validationException.addValidationException(errorCode, parameters, null);
                rightValue = false;
              }
            }
          } else {
            Object value = null;
            if (sitei) {
              value = jsonObj.get(name);
            }

            AnnotationValidator validator = AnnotationValidationUtil.validate(value, annotation);

            if (validator != null) {

              String errorCode = validator.getErrorCode();
              String fieldBungen = beanClazz.getName() + "." + name;
              Alias alias = (Alias) field.getAnnotation(Alias.class);
              if (alias != null) {
                fieldBungen = alias.value();
              }
              String[] parameters = null;
              String[] ps = validator.getMsgParameters();
              if (ps == null) {
                parameters = new String[] {fieldBungen};
              } else {
                parameters = new String[ps.length + 1];
                parameters[0] = fieldBungen;
                for (int i = 0; i < ps.length; i++) {
                  parameters[i + 1] = ps[i];
                }
              }

              validationException.addValidationException(errorCode, parameters, null);
              rightValue = false;
            }
          }

          if (!rightValue) {
            break;
          }
        }
      }
    } catch (NoSuchFieldException nsfe) {

    }

    return rightValue;
  }