예제 #1
0
  /**
   * 解析字段定义<br>
   * <功能详细描述>
   *
   * @param type
   * @param pd
   * @return [参数说明]
   * @return JPAEntityColumnDef [返回类型说明]
   * @exception throws [异常类型] [异常说明]
   * @see [类、类#方法、类#成员]
   */
  private static JPAEntityColumnDef doAnalyzeCoumnDef(
      String tableName, Class<?> type, PropertyDescriptor pd) {
    JPAEntityColumnDef colDef = null;

    String columnComment = "";
    String propertyName = pd.getName();
    String columnName = propertyName;
    Class<?> javaType = pd.getPropertyType();
    int size = 0;
    int scale = 0;
    boolean required = false;

    // 获取字段
    Field field = FieldUtils.getField(type, propertyName, true);
    if (field != null) {
      if (field.isAnnotationPresent(Transient.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (field.isAnnotationPresent(OneToMany.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (field.isAnnotationPresent(Column.class)) {
        Column columnAnno = field.getAnnotation(Column.class);
        columnName = columnAnno.name();
        required = !columnAnno.nullable();
        size = Math.max(columnAnno.length(), columnAnno.precision());
        scale = columnAnno.scale();
      }
    }

    // 获取读方法
    Method readMethod = pd.getReadMethod();
    if (readMethod != null) {
      if (readMethod.isAnnotationPresent(Transient.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (readMethod.isAnnotationPresent(OneToMany.class)) {
        // 如果含有忽略的字段则跳过该字段
        return null;
      }
      if (readMethod.isAnnotationPresent(Column.class)) {
        Column columnAnno = readMethod.getAnnotation(Column.class);
        columnName = columnAnno.name();
        required = !columnAnno.nullable();
        size = Math.max(columnAnno.length(), columnAnno.precision());
        scale = columnAnno.scale();
      }
    }

    JdbcTypeEnum jdbcType = JPAEntityTypeRegistry.getJdbcType(javaType); // 获取对应的jdbcType
    colDef = new JPAEntityColumnDef(columnName, javaType, jdbcType, size, scale, required);
    colDef.setComment(columnComment);
    return colDef;
  }
  private void readColumn(Column columnAnn, DeployBeanProperty prop) {

    if (!isEmpty(columnAnn.name())) {
      String dbColumn = databasePlatform.convertQuotedIdentifiers(columnAnn.name());
      prop.setDbColumn(dbColumn);
    }

    prop.setDbInsertable(columnAnn.insertable());
    prop.setDbUpdateable(columnAnn.updatable());
    prop.setNullable(columnAnn.nullable());
    prop.setUnique(columnAnn.unique());
    if (columnAnn.precision() > 0) {
      prop.setDbLength(columnAnn.precision());
    } else if (columnAnn.length() != 255) {
      // set default 255 on DbTypeMap
      prop.setDbLength(columnAnn.length());
    }
    prop.setDbScale(columnAnn.scale());
    prop.setDbColumnDefn(columnAnn.columnDefinition());

    String baseTable = descriptor.getBaseTable();
    String tableName = columnAnn.table();
    if (tableName.equals("") || tableName.equalsIgnoreCase(baseTable)) {
      // its a base table property...
    } else {
      // its on a secondary table...
      prop.setSecondaryTable(tableName);
      // DeployTableJoin tableJoin = info.getTableJoin(tableName);
      // tableJoin.addProperty(prop);
    }
  }
예제 #3
0
파일: TUtils.java 프로젝트: imace/coffee
 /** 判断列是否可为空 return : false-不可为空 ; true-可为空 */
 public static <T> boolean isNull(Class<T> clazz, String fieldName) {
   Column column = getColumn(clazz, fieldName);
   if (column != null) {
     return column.nullable();
   } else {
     return true;
   }
 }
예제 #4
0
  public static Map<String, UiConfigImpl> getUiConfigs(Class<?> entityClass) {
    Map<String, UiConfigImpl> map = cache.get(entityClass);
    if (map == null || AppInfo.getStage() == Stage.DEVELOPMENT) {
      GenericGenerator genericGenerator =
          AnnotationUtils.getAnnotatedPropertyNameAndAnnotations(
                  entityClass, GenericGenerator.class)
              .get("id");
      boolean idAssigned =
          genericGenerator != null && "assigned".equals(genericGenerator.strategy());
      Map<String, NaturalId> naturalIds =
          AnnotationUtils.getAnnotatedPropertyNameAndAnnotations(entityClass, NaturalId.class);
      Set<String> hides = new HashSet<String>();
      map = new HashMap<String, UiConfigImpl>();
      PropertyDescriptor[] pds =
          org.springframework.beans.BeanUtils.getPropertyDescriptors(entityClass);
      for (PropertyDescriptor pd : pds) {
        String propertyName = pd.getName();
        if (pd.getReadMethod() == null
            || pd.getWriteMethod() == null
                && pd.getReadMethod().getAnnotation(UiConfig.class) == null) continue;
        Class<?> declaredClass = pd.getReadMethod().getDeclaringClass();
        Version version = pd.getReadMethod().getAnnotation(Version.class);
        if (version == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) version = f.getAnnotation(Version.class);
          } catch (Exception e) {
          }
        if (version != null) continue;
        Transient trans = pd.getReadMethod().getAnnotation(Transient.class);
        if (trans == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) trans = f.getAnnotation(Transient.class);
          } catch (Exception e) {
          }
        SearchableProperty searchableProperty =
            pd.getReadMethod().getAnnotation(SearchableProperty.class);
        if (searchableProperty == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) searchableProperty = f.getAnnotation(SearchableProperty.class);
          } catch (Exception e) {
          }
        SearchableId searchableId = pd.getReadMethod().getAnnotation(SearchableId.class);
        if (searchableId == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) searchableId = f.getAnnotation(SearchableId.class);
          } catch (Exception e) {
          }
        UiConfig uiConfig = pd.getReadMethod().getAnnotation(UiConfig.class);
        if (uiConfig == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) uiConfig = f.getAnnotation(UiConfig.class);
          } catch (Exception e) {
          }

        if (uiConfig != null && uiConfig.hidden()) continue;
        if ("new".equals(propertyName)
            || !idAssigned && "id".equals(propertyName)
            || "class".equals(propertyName)
            || "fieldHandler".equals(propertyName)
            || pd.getReadMethod() == null
            || hides.contains(propertyName)) continue;
        Column columnannotation = pd.getReadMethod().getAnnotation(Column.class);
        if (columnannotation == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) columnannotation = f.getAnnotation(Column.class);
          } catch (Exception e) {
          }
        Basic basic = pd.getReadMethod().getAnnotation(Basic.class);
        if (basic == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) basic = f.getAnnotation(Basic.class);
          } catch (Exception e) {
          }
        Lob lob = pd.getReadMethod().getAnnotation(Lob.class);
        if (lob == null)
          try {
            Field f = declaredClass.getDeclaredField(propertyName);
            if (f != null) lob = f.getAnnotation(Lob.class);
          } catch (Exception e) {
          }
        UiConfigImpl uci = new UiConfigImpl(pd.getPropertyType(), uiConfig);
        if (idAssigned && propertyName.equals("id")) uci.addCssClass("required checkavailable");
        if (Attributable.class.isAssignableFrom(entityClass) && pd.getName().equals("attributes")) {
          uci.setType("attributes");
        }
        if (trans != null) {
          uci.setExcludedFromCriteria(true);
          uci.setExcludedFromLike(true);
          uci.setExcludedFromOrdering(true);
        }
        if (lob != null) {
          uci.setExcludedFromCriteria(true);
          if (uci.getMaxlength() == 0) uci.setMaxlength(2 * 1024 * 1024);
        }
        if (columnannotation != null && !columnannotation.nullable()
            || basic != null && !basic.optional()) uci.setRequired(true);
        if (columnannotation != null && columnannotation.length() != 255 && uci.getMaxlength() == 0)
          uci.setMaxlength(columnannotation.length());
        if (lob != null || uci.getMaxlength() > 255) uci.setExcludedFromOrdering(true);
        Class<?> returnType = pd.getPropertyType();
        if (returnType.isEnum()) {
          uci.setType("enum");
          try {
            returnType.getMethod("getName");
            uci.setListKey("name");
          } catch (NoSuchMethodException e) {
            uci.setListKey("top");
          }
          try {
            returnType.getMethod("getDisplayName");
            uci.setListValue("displayName");
          } catch (NoSuchMethodException e) {
            uci.setListValue(uci.getListKey());
          }
          map.put(propertyName, uci);
          continue;
        } else if (Persistable.class.isAssignableFrom(returnType)) {
          JoinColumn joincolumnannotation = pd.getReadMethod().getAnnotation(JoinColumn.class);
          if (joincolumnannotation == null)
            try {
              Field f = declaredClass.getDeclaredField(propertyName);
              if (f != null) joincolumnannotation = f.getAnnotation(JoinColumn.class);
            } catch (Exception e) {
            }
          if (joincolumnannotation != null && !joincolumnannotation.nullable())
            uci.setRequired(true);
          ManyToOne manyToOne = pd.getReadMethod().getAnnotation(ManyToOne.class);
          if (manyToOne == null)
            try {
              Field f = declaredClass.getDeclaredField(propertyName);
              if (f != null) manyToOne = f.getAnnotation(ManyToOne.class);
            } catch (Exception e) {
            }
          if (manyToOne != null && !manyToOne.optional()) uci.setRequired(true);
          uci.setType("listpick");
          uci.setExcludeIfNotEdited(true);
          if (StringUtils.isBlank(uci.getPickUrl())) {
            String url = AutoConfigPackageProvider.getEntityUrl(returnType);
            StringBuilder sb =
                url != null
                    ? new StringBuilder(url)
                    : new StringBuilder("/")
                        .append(StringUtils.uncapitalize(returnType.getSimpleName()));
            sb.append("/pick");
            Set<String> columns = new LinkedHashSet<String>();
            columns.addAll(
                AnnotationUtils.getAnnotatedPropertyNameAndAnnotations(returnType, NaturalId.class)
                    .keySet());
            Map<String, UiConfigImpl> configs = getUiConfigs(returnType);
            for (String column : "fullname,name,code".split(","))
              if (configs.containsKey(column)
                  && (!columns.contains("fullname") && column.equals("name")
                      || !column.equals("name"))) columns.add(column);
            for (Map.Entry<String, UiConfigImpl> entry : configs.entrySet())
              if (entry.getValue().isShownInPick()) columns.add(entry.getKey());
            if (!columns.isEmpty()) {
              sb.append("?columns=" + StringUtils.join(columns, ','));
            }
            uci.setPickUrl(sb.toString());
          }
          map.put(propertyName, uci);
          continue;
        }
        if (returnType == Integer.TYPE
            || returnType == Short.TYPE
            || returnType == Long.TYPE
            || returnType == Double.TYPE
            || returnType == Float.TYPE
            || Number.class.isAssignableFrom(returnType)) {
          if (returnType == Integer.TYPE
              || returnType == Integer.class
              || returnType == Short.TYPE
              || returnType == Short.class) {
            uci.setInputType("number");
            uci.addCssClass("integer");

          } else if (returnType == Long.TYPE || returnType == Long.class) {
            uci.setInputType("number");
            uci.addCssClass("long");
          } else if (returnType == Double.TYPE
              || returnType == Double.class
              || returnType == Float.TYPE
              || returnType == Float.class
              || returnType == BigDecimal.class) {
            uci.setInputType("number");
            uci.addCssClass("double");
          }
          Set<String> cssClasses = uci.getCssClasses();
          if (cssClasses.contains("double") && !uci.getDynamicAttributes().containsKey("step"))
            uci.getDynamicAttributes().put("step", "0.01");
          if (cssClasses.contains("positive") && !uci.getDynamicAttributes().containsKey("min")) {
            uci.getDynamicAttributes().put("min", "1");
            if (cssClasses.contains("double")) uci.getDynamicAttributes().put("min", "0.01");
            if (cssClasses.contains("zero")) uci.getDynamicAttributes().put("min", "0");
          }
        } else if (Date.class.isAssignableFrom(returnType)) {
          Temporal temporal = pd.getReadMethod().getAnnotation(Temporal.class);
          if (temporal == null)
            try {
              Field f = declaredClass.getDeclaredField(propertyName);
              if (f != null) temporal = f.getAnnotation(Temporal.class);
            } catch (Exception e) {
            }
          String temporalType = "date";
          if (temporal != null)
            if (temporal.value() == TemporalType.TIMESTAMP) temporalType = "datetime";
            else if (temporal.value() == TemporalType.TIME) temporalType = "time";
          uci.addCssClass(temporalType);
          // uci.setInputType(temporalType);
          if (StringUtils.isBlank(uci.getCellEdit())) uci.setCellEdit("click," + temporalType);
        } else if (String.class == returnType
            && pd.getName().toLowerCase().contains("email")
            && !pd.getName().contains("Password")) {
          uci.setInputType("email");
          uci.addCssClass("email");
        } else if (returnType == Boolean.TYPE || returnType == Boolean.class) {
          uci.setType("checkbox");
        }
        if (columnannotation != null && columnannotation.unique()) uci.setUnique(true);
        if (searchableProperty != null || searchableId != null) uci.setSearchable(true);

        if (naturalIds.containsKey(pd.getName())) {
          uci.setRequired(true);
          if (naturalIds.size() == 1) uci.addCssClass("checkavailable");
        }
        map.put(propertyName, uci);
      }
      List<Map.Entry<String, UiConfigImpl>> list =
          new ArrayList<Map.Entry<String, UiConfigImpl>>(map.entrySet());
      Collections.sort(list, comparator);
      Map<String, UiConfigImpl> sortedMap = new LinkedHashMap<String, UiConfigImpl>();
      for (Map.Entry<String, UiConfigImpl> entry : list)
        sortedMap.put(entry.getKey(), entry.getValue());
      map = sortedMap;
      cache.put(entityClass, Collections.unmodifiableMap(map));
    }
    return map;
  }
  /** Test version accessor methods: modifiers, arguments, annotations, and return types. */
  private void testVersionAccessors() {
    // skip classes that have a getVersion from a superclass
    if (!_entityClass.getSuperclass().equals(AbstractEntity.class)) {
      return;
    }

    org.hibernate.annotations.Entity entityAnnotation =
        _entityClass.getAnnotation(org.hibernate.annotations.Entity.class);
    if (entityAnnotation != null && !entityAnnotation.mutable()) {
      return;
    }
    if (_entityClass.getAnnotation(Immutable.class) != null) {
      return;
    }

    // getVersion
    try {
      Method getVersionMethod = _entityClass.getDeclaredMethod("getVersion");
      assertTrue(
          "private getVersion for " + _entityClass,
          Modifier.isPrivate(getVersionMethod.getModifiers()));
      assertFalse(
          "instance getVersion for " + _entityClass,
          Modifier.isStatic(getVersionMethod.getModifiers()));
      assertEquals(
          "getVersion return type for " + _entityClass,
          getVersionMethod.getReturnType(),
          Integer.class);

      Column column = getVersionMethod.getAnnotation(Column.class);
      assertNotNull("getVersion has @javax.persistence.Column", column);
      assertFalse("getVersion has @javax.persistence.Column(nullable=false)", column.nullable());

      Version version = getVersionMethod.getAnnotation(Version.class);
      assertNotNull("getVersion has @javax.persistence.Version", version);
    } catch (SecurityException e) {
      e.printStackTrace();
      fail("getting declared method getVersion for " + _entityClass + ": " + e);
    } catch (NoSuchMethodException e) {
      fail("getting declared method getVersion for " + _entityClass + ": " + e);
    }

    // setVersion
    try {
      Method setVersionMethod = _entityClass.getDeclaredMethod("setVersion", Integer.class);
      assertTrue(
          "private setVersion for " + _entityClass,
          Modifier.isPrivate(setVersionMethod.getModifiers()));
      assertFalse(
          "instance setVersion for " + _entityClass,
          Modifier.isStatic(setVersionMethod.getModifiers()));
      assertEquals(
          "setVersion return type for " + _entityClass,
          setVersionMethod.getReturnType(),
          void.class);
    } catch (SecurityException e) {
      e.printStackTrace();
      fail("getting declared method getVersion for " + _entityClass + ": " + e);
    } catch (NoSuchMethodException e) {
      fail("getting declared method getVersion for " + _entityClass + ": " + e);
    }
  }
  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);
    }
  }