Browse Source

Use annotation @CollectionProperty to specify collection's simple name

sunyj 8 years ago
parent
commit
71b373d10c

+ 2 - 5
kanban-auth/src/main/java/com/uas/kanban/model/User.java

@@ -1,5 +1,6 @@
 package com.uas.kanban.model;
 
+import com.uas.kanban.annotation.CollectionProperty;
 import com.uas.kanban.annotation.FieldProperty;
 import com.uas.kanban.base.BaseEntity;
 import org.mongodb.morphia.annotations.Entity;
@@ -16,6 +17,7 @@ import java.util.Objects;
  * @since 2017年9月1日 下午5:19:15
  */
 @Entity
+@CollectionProperty(simpleName = "用户")
 public class User extends BaseEntity {
 
     private static final long serialVersionUID = 1L;
@@ -44,11 +46,6 @@ public class User extends BaseEntity {
      */
     private List<String> panelCodes;
 
-    @Override
-    public String collectionSimpleName() {
-        return "用户";
-    }
-
     public String getName() {
         return name;
     }

+ 22 - 0
kanban-common/src/main/java/com/uas/kanban/annotation/CollectionProperty.java

@@ -0,0 +1,22 @@
+package com.uas.kanban.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * 集合属性
+ *
+ * @author sunyj
+ * @since 2017/10/26 10:39
+ */
+@Target(ElementType.TYPE)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface CollectionProperty {
+
+    /**
+     * 集合简称
+     */
+    String simpleName();
+}

+ 50 - 27
kanban-common/src/main/java/com/uas/kanban/base/BaseDao.java

@@ -4,6 +4,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.mongodb.DBCollection;
 import com.mongodb.DuplicateKeyException;
 import com.mongodb.WriteResult;
+import com.uas.kanban.annotation.CollectionProperty;
 import com.uas.kanban.annotation.FieldProperty;
 import com.uas.kanban.annotation.NotEmpty;
 import com.uas.kanban.exception.OperationException;
@@ -66,12 +67,6 @@ public class BaseDao<T extends BaseEntity> {
     public static <K> void checkFields(@NotEmpty("k") K k) throws IllegalArgumentException, IllegalStateException {
         Class<?> clazz = k.getClass();
         Field[] declaredFields = clazz.getDeclaredFields();
-        String collectionName;
-        if (k instanceof BaseEntity) {
-            collectionName = ((BaseEntity) k).collectionSimpleName();
-        } else {
-            collectionName = clazz.getSimpleName();
-        }
         for (Field field : declaredFields) {
             int modifiers = field.getModifiers();
             // 不处理static修饰的变量
@@ -90,7 +85,7 @@ public class BaseDao<T extends BaseEntity> {
 
             // 如果使用 {@link FieldProperty} 指定不可为空,但是值为空,则抛出异常
             if (fieldProperty != null && !fieldProperty.nullable() && ObjectUtils.isEmpty(value)) {
-                throw new IllegalArgumentException(collectionName + "字段为空:" + field.getName());
+                throw new IllegalArgumentException(getCollectionSimpleName(clazz) + "字段为空:" + field.getName());
             }
             // 如果是嵌入或引用对象,并且不为空,则递归检测
             if ((embedded != null || reference != null) && !ObjectUtils.isEmpty(value)) {
@@ -115,6 +110,20 @@ public class BaseDao<T extends BaseEntity> {
         }
     }
 
+    /**
+     * 获取指定类的集合简称(默认为类名)
+     *
+     * @param clazz 指定类
+     * @return 集合简称
+     */
+    protected static String getCollectionSimpleName(@NotEmpty("clazz") Class<?> clazz) {
+        CollectionProperty annotation = clazz.getAnnotation(CollectionProperty.class);
+        if (annotation != null && !StringUtils.isEmpty(annotation.simpleName())) {
+            return annotation.simpleName();
+        }
+        return clazz.getSimpleName();
+    }
+
     /**
      * Returns a new query bound to the collection (a specific {@link DBCollection})
      *
@@ -397,12 +406,7 @@ public class BaseDao<T extends BaseEntity> {
         UpdateOperations<T> operations = createUpdateOperations();
         Set<String> keySet = jsonObject.keySet();
         for (String key : keySet) {
-            Field field;
-            try {
-                field = entityClass.getDeclaredField(key);
-            } catch (NoSuchFieldException | SecurityException e1) {
-                throw new IllegalArgumentException("表中不存在该字段:" + key);
-            }
+            Field field = ObjectUtils.getField(key, entityClass);
             int modifiers = field.getModifiers();
             // 不处理static、final、transient修饰的变量(只处理普通成员变量)
             if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers) || Modifier.isTransient(modifiers)) {
@@ -483,7 +487,7 @@ public class BaseDao<T extends BaseEntity> {
     public T checkExist(@NotEmpty("code") String code) throws IllegalStateException {
         T t = findOne(code);
         if (t == null) {
-            throw new IllegalStateException(t.collectionSimpleName() + "不存在:" + code);
+            throw new IllegalStateException(getCollectionSimpleName(entityClass) + "不存在:" + code);
         }
         return t;
     }
@@ -558,26 +562,22 @@ public class BaseDao<T extends BaseEntity> {
      * @param clazz type of the retrieved field
      * @param <K>   type of the retrieved field
      * @return The results
-     * @throws NoSuchFieldException
+     * @throws IllegalStateException
      */
-    public <K> List<K> findField(@NotEmpty("query") Query<T> query, @NotEmpty("field") String field, Class<K> clazz) throws NoSuchFieldException {
+    public <K> List<K> findField(@NotEmpty("query") Query<T> query, @NotEmpty("field") String field, Class<K> clazz) throws IllegalStateException {
         query.project(field, true);
         List<T> list = query.asList();
         List<K> result = new ArrayList<>();
         if (!CollectionUtils.isEmpty(list)) {
             for (T t : list) {
-                try {
-                    Object value = ObjectUtils.recursivelyGetValue(field, t);
-                    if (value != null) {
-                        Class<?> valueClass = value.getClass();
-                        if (clazz.isAssignableFrom(valueClass)) {
-                            result.add((K) value);
-                        } else {
-                            throw new ClassCastException("字段 " + field + " 的类型为 " + valueClass + " , 无法转为 " + clazz);
-                        }
+                Object value = ObjectUtils.recursivelyGetValue(field, t);
+                if (value != null) {
+                    Class<?> valueClass = value.getClass();
+                    if (clazz.isAssignableFrom(valueClass)) {
+                        result.add((K) value);
+                    } else {
+                        throw new ClassCastException("字段 " + field + " 的类型为 " + valueClass + " , 无法转为 " + clazz);
                     }
-                } catch (NoSuchFieldException e) {
-                    throw new NoSuchFieldException(entityClass + " 中不存在字段:" + field);
                 }
 
             }
@@ -585,6 +585,29 @@ public class BaseDao<T extends BaseEntity> {
         return result;
     }
 
+    /**
+     * Execute the query and get the result (Limits the field retrieved and only one row)
+     *
+     * @param code  the code to query
+     * @param field retrieved field
+     * @param clazz type of the retrieved field
+     * @param <K>   type of the retrieved field
+     * @return The result, may be null
+     * @throws IllegalStateException
+     */
+    public <K> K findField(@NotEmpty("code") String code, @NotEmpty("field") String field, Class<K> clazz) throws IllegalStateException {
+        Query<T> query = createQuery(code);
+        List<K> fields = findField(query, field, clazz);
+        int size = fields.size();
+        if (size < 1) {
+            return null;
+        } else if (size > 1) {
+            throw new IllegalStateException("存在多个值:" + fields);
+        }
+        return fields.get(0);
+    }
+
+
     /**
      * 分页获取数据
      *

+ 0 - 7
kanban-common/src/main/java/com/uas/kanban/base/BaseEntity.java

@@ -57,13 +57,6 @@ public abstract class BaseEntity extends Coded {
         super.init();
     }
 
-    /**
-     * @return 集合简称
-     */
-    public String collectionSimpleName() {
-        return getClass().getSimpleName();
-    }
-
     public Date getCreateTime() {
         return createTime;
     }

+ 20 - 4
kanban-common/src/main/java/com/uas/kanban/util/ObjectUtils.java

@@ -212,7 +212,7 @@ public class ObjectUtils {
      * @param k     指定对象
      * @return 指定字段的值
      */
-    public static <K> Object recursivelyGetValue(@NotEmpty("field") String field, @NotEmpty("k") K k) throws IllegalStateException, NoSuchFieldException {
+    public static <K> Object recursivelyGetValue(@NotEmpty("field") String field, @NotEmpty("k") K k) {
         return getValue(recursivelyGetField(field, k.getClass()), k);
     }
 
@@ -222,9 +222,9 @@ public class ObjectUtils {
      * @param field 指定字段
      * @param clazz 指定类
      * @return 指定字段
-     * @throws NoSuchFieldException
+     * @throws IllegalArgumentException
      */
-    private static Field recursivelyGetField(@NotEmpty("field") String field, @NotEmpty("clazz") Class<?> clazz) throws NoSuchFieldException {
+    private static Field recursivelyGetField(@NotEmpty("field") String field, @NotEmpty("clazz") Class<?> clazz) throws IllegalArgumentException {
         try {
             return clazz.getDeclaredField(field);
         } catch (NoSuchFieldException e) {
@@ -232,7 +232,23 @@ public class ObjectUtils {
             if (superclass != null) {
                 return recursivelyGetField(field, superclass);
             }
-            throw e;
+            throw new IllegalArgumentException(clazz + "中不存在字段:" + field);
+        }
+    }
+
+    /**
+     * 获取指定类的指定字段
+     *
+     * @param field 指定字段
+     * @param clazz 指定类
+     * @return 指定字段
+     * @throws IllegalArgumentException
+     */
+    public static Field getField(@NotEmpty("field") String field, @NotEmpty("clazz") Class<?> clazz) throws IllegalArgumentException {
+        try {
+            return clazz.getDeclaredField(field);
+        } catch (NoSuchFieldException e) {
+            throw new IllegalArgumentException(clazz + "中不存在字段:" + field);
         }
     }
 

+ 2 - 13
kanban-console/src/main/java/com/uas/kanban/dao/KanbanDao.java

@@ -38,11 +38,7 @@ public class KanbanDao extends BaseDao<Kanban> {
     public List<String> findPanelCodes(@NotEmpty("codes") List<String> codes) {
         Query<Kanban> query = createQuery();
         query.field("code").in(codes);
-        try {
-            return findField(query, "panelCode", String.class);
-        } catch (NoSuchFieldException e) {
-            throw new IllegalStateException(e.getMessage(), e);
-        }
+        return findField(query, "panelCode", String.class);
     }
 
     /**
@@ -52,14 +48,7 @@ public class KanbanDao extends BaseDao<Kanban> {
      * @return 面板 code
      */
     public String findPanelCode(String code) {
-        List<String> panelCodes = findPanelCodes(Collections.singletonList(code));
-        int size = panelCodes.size();
-        if (size < 1) {
-            return null;
-        } else if (size > 1) {
-            throw new IllegalStateException("存在多个值:" + panelCodes);
-        }
-        return panelCodes.get(0);
+        return findField(code, "panelCode", String.class);
     }
 
 }

+ 1 - 1
kanban-console/src/main/java/com/uas/kanban/dao/PanelDao.java

@@ -42,7 +42,7 @@ public class PanelDao extends BaseDao<Panel> {
     public Panel checkExist(@NotEmpty("code") String code) throws IllegalStateException {
         Panel panel = findOne(code);
         if (panel == null) {
-            throw new IllegalStateException(panel.collectionSimpleName() + "不存在或未分配:" + code);
+            throw new IllegalStateException(getCollectionSimpleName(Panel.class) + "不存在或未分配:" + code);
         }
         return panel;
     }

+ 1 - 5
kanban-console/src/main/java/com/uas/kanban/dao/ParameterDao.java

@@ -37,11 +37,7 @@ public class ParameterDao extends BaseDao<Parameter> {
     public List<String> findPanelCodes(@NotEmpty("codes") List<String> codes) {
         Query<Parameter> query = createQuery();
         query.field("code").in(codes);
-        try {
-            return findField(query, "panelCode", String.class);
-        } catch (NoSuchFieldException e) {
-            throw new IllegalStateException(e.getMessage(), e);
-        }
+        return findField(query, "panelCode", String.class);
     }
 
 }

+ 2 - 5
kanban-console/src/main/java/com/uas/kanban/model/DataSource.java

@@ -1,5 +1,6 @@
 package com.uas.kanban.model;
 
+import com.uas.kanban.annotation.CollectionProperty;
 import com.uas.kanban.annotation.FieldProperty;
 import com.uas.kanban.base.BaseEntity;
 import org.mongodb.morphia.annotations.Entity;
@@ -15,6 +16,7 @@ import java.util.Objects;
  * @since 2017年8月29日 上午10:06:55
  */
 @Entity
+@CollectionProperty(simpleName = "数据源")
 public class DataSource extends BaseEntity {
 
     private static final long serialVersionUID = 1L;
@@ -50,11 +52,6 @@ public class DataSource extends BaseEntity {
     @FieldProperty(nullable = false)
     private String password;
 
-    @Override
-    public String collectionSimpleName() {
-        return "数据源";
-    }
-
     public String getName() {
         return name;
     }

+ 2 - 5
kanban-console/src/main/java/com/uas/kanban/model/Kanban.java

@@ -1,5 +1,6 @@
 package com.uas.kanban.model;
 
+import com.uas.kanban.annotation.CollectionProperty;
 import com.uas.kanban.annotation.FieldProperty;
 import com.uas.kanban.base.BaseEntity;
 import org.mongodb.morphia.annotations.*;
@@ -12,6 +13,7 @@ import org.mongodb.morphia.annotations.*;
  */
 @Entity
 @Indexes(@Index(fields = {@Field("name"), @Field("panelCode")}, options = @IndexOptions(unique = true)))
+@CollectionProperty(simpleName = "看板")
 public class Kanban extends BaseEntity {
 
     private static final long serialVersionUID = 1L;
@@ -50,11 +52,6 @@ public class Kanban extends BaseEntity {
     @FieldProperty(nullable = false)
     private String panelCode;
 
-    @Override
-    public String collectionSimpleName() {
-        return "看板";
-    }
-
     public String getName() {
         return name;
     }

+ 2 - 5
kanban-console/src/main/java/com/uas/kanban/model/Panel.java

@@ -1,5 +1,6 @@
 package com.uas.kanban.model;
 
+import com.uas.kanban.annotation.CollectionProperty;
 import com.uas.kanban.annotation.FieldProperty;
 import com.uas.kanban.base.BaseEntity;
 import org.mongodb.morphia.annotations.Entity;
@@ -13,6 +14,7 @@ import org.mongodb.morphia.annotations.Indexed;
  * @since 2017/10/18 15:35
  */
 @Entity
+@CollectionProperty(simpleName = "面板")
 public class Panel extends BaseEntity {
 
     private static final long serialVersionUID = 1L;
@@ -50,11 +52,6 @@ public class Panel extends BaseEntity {
         super.init();
     }
 
-    @Override
-    public String collectionSimpleName() {
-        return "面板";
-    }
-
     public String getName() {
         return name;
     }

+ 2 - 5
kanban-console/src/main/java/com/uas/kanban/model/PanelInstance.java

@@ -2,6 +2,7 @@ package com.uas.kanban.model;
 
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
+import com.uas.kanban.annotation.CollectionProperty;
 import com.uas.kanban.annotation.FieldProperty;
 import com.uas.kanban.annotation.NotEmpty;
 import com.uas.kanban.base.BaseDao;
@@ -21,6 +22,7 @@ import java.util.List;
  */
 @Entity
 @Indexes(@Index(fields = {@Field("userCode"), @Field("panelCode")}, options = @IndexOptions(unique = true)))
+@CollectionProperty(simpleName = "面板实例")
 public class PanelInstance extends BaseEntity {
 
     /**
@@ -86,11 +88,6 @@ public class PanelInstance extends BaseEntity {
         super.init();
     }
 
-    @Override
-    public String collectionSimpleName() {
-        return "面板实例";
-    }
-
     public Double getSwitchFrequency() {
         return switchFrequency;
     }

+ 2 - 5
kanban-console/src/main/java/com/uas/kanban/model/Parameter.java

@@ -1,5 +1,6 @@
 package com.uas.kanban.model;
 
+import com.uas.kanban.annotation.CollectionProperty;
 import com.uas.kanban.annotation.FieldProperty;
 import com.uas.kanban.base.BaseEntity;
 import com.uas.kanban.util.CollectionUtils;
@@ -19,6 +20,7 @@ import java.util.Objects;
  */
 @Entity
 @Indexes(@Index(fields = {@Field("name"), @Field("panelCode")}, options = @IndexOptions(unique = true)))
+@CollectionProperty(simpleName = "参数")
 public class Parameter extends BaseEntity {
 
     private static final long serialVersionUID = 1L;
@@ -83,11 +85,6 @@ public class Parameter extends BaseEntity {
         super.init();
     }
 
-    @Override
-    public String collectionSimpleName() {
-        return "参数";
-    }
-
     public String getName() {
         return name;
     }

+ 1 - 1
kanban-console/src/main/java/com/uas/kanban/service/impl/KanbanServiceImpl.java

@@ -76,7 +76,7 @@ public class KanbanServiceImpl extends BaseService<Kanban> implements KanbanServ
         String panelCode = jsonObject.getString("panelCode");
         String oldPanelCode = kanbanDao.findPanelCode(code);
         if (!StringUtils.isEmpty(panelCode) && !Objects.equals(panelCode, oldPanelCode)) {
-            throw new OperationException("不允许修改看板的 panelCode");
+            throw new OperationException("不可修改 panelCode");
         }
         panelDao.checkExist(oldPanelCode);
         panelDao.incVersion(Collections.singletonList(oldPanelCode));