Transform.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. package com.nuliji.tools;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.nuliji.tools.annotation.Dto;
  5. import com.nuliji.tools.exception.SystemException;
  6. import org.modelmapper.AbstractConverter;
  7. import org.modelmapper.Converter;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.modelmapper.ModelMapper;
  11. import org.modelmapper.config.Configuration;
  12. import java.lang.reflect.Field;
  13. import java.lang.reflect.Type;
  14. import java.util.*;
  15. import static org.modelmapper.convention.MatchingStrategies.STRICT;
  16. /**
  17. * 使用ModelMapper转换Dto和Entity
  18. */
  19. public class Transform {
  20. private static final ModelMapper modelMapper = new ModelMapper();
  21. private static final Logger logger = LoggerFactory.getLogger(Transform.class);
  22. static {
  23. // modelMapper.getConfiguration().setFieldMatchingEnabled(true);
  24. modelMapper.getConfiguration().setMatchingStrategy(STRICT);
  25. modelMapper.getConfiguration().setFieldAccessLevel(Configuration.AccessLevel.PRIVATE);
  26. Converter<Collection<Long>, String> longToString = new AbstractConverter<Collection<Long>, String>() {
  27. protected String convert(Collection<Long> source) {
  28. return Tools.joinIds(source);
  29. }
  30. };
  31. modelMapper.addConverter(longToString);
  32. Converter<String, Collection<Long>> stringToLong = new AbstractConverter<String, Collection<Long>>() {
  33. protected Collection<Long> convert(String source) {
  34. return Tools.splitIds(source);
  35. }
  36. };
  37. modelMapper.addConverter(stringToLong);
  38. Converter<Date, Long> dateToLong = new AbstractConverter<Date, Long>() {
  39. protected Long convert(Date source) {
  40. return source.getTime() / 1000;
  41. }
  42. };
  43. modelMapper.addConverter(dateToLong);
  44. Converter<Long, Date> longToDate = new AbstractConverter<Long, Date>() {
  45. protected Date convert(Long source) {
  46. return new Date(source * 1000);
  47. }
  48. };
  49. modelMapper.addConverter(longToDate);
  50. Converter<JSONObject, JSONObject> jsonObjectConverter = new AbstractConverter<JSONObject, JSONObject>() {
  51. protected JSONObject convert(JSONObject source) {
  52. if (source == null) return null;
  53. logger.info(source.toJSONString());
  54. return JSONObject.parseObject(source.toJSONString());
  55. }
  56. };
  57. modelMapper.addConverter(jsonObjectConverter);
  58. Converter<String, JSONObject> stringJSONObjectConverter = new AbstractConverter<String, JSONObject>() {
  59. protected JSONObject convert(String source) {
  60. return JSONObject.parseObject(source);
  61. }
  62. };
  63. modelMapper.addConverter(stringJSONObjectConverter);
  64. Converter<Object, JSONObject> objectJSONObjectConverter = new AbstractConverter<Object, JSONObject>() {
  65. protected JSONObject convert(Object source) {
  66. return JSONObject.parseObject(JSONObject.toJSONString(source));
  67. }
  68. };
  69. modelMapper.addConverter(objectJSONObjectConverter);
  70. Converter<JSONArray, JSONArray> jsonArrayConverter = new AbstractConverter<JSONArray, JSONArray>() {
  71. protected JSONArray convert(JSONArray source) {
  72. if (source == null) return null;
  73. logger.info(source.toJSONString());
  74. return JSONObject.parseArray(source.toJSONString());
  75. }
  76. };
  77. modelMapper.addConverter(jsonArrayConverter);
  78. Converter<Object, JSONArray> objectJSONArrayConverter = new AbstractConverter<Object, JSONArray>() {
  79. protected JSONArray convert(Object source) {
  80. return JSONObject.parseArray(JSONObject.toJSONString(source));
  81. }
  82. };
  83. modelMapper.addConverter(objectJSONArrayConverter);
  84. Converter<String, JSONArray> stringJSONArrayConverter = new AbstractConverter<String, JSONArray>() {
  85. protected JSONArray convert(String source) {
  86. return JSONObject.parseArray(source);
  87. }
  88. };
  89. modelMapper.addConverter(stringJSONArrayConverter);
  90. }
  91. public static <S, T> T dtoToEntity(S source) {
  92. Class sourceClass = source.getClass();
  93. if(!sourceClass.isAnnotationPresent(Dto.class)){
  94. throw new SystemException("Class " + sourceClass.getName() + " need dto annotation");
  95. }
  96. Dto dto = (Dto) sourceClass.getAnnotation(Dto.class);
  97. return (T) transfer(source, dto.entity());
  98. }
  99. public static <S, T> T convert(S source, Class<?> clazz) {
  100. return (T) transfer(source, clazz);
  101. }
  102. public static <S, T> List<T> convert(Collection<S> source, Class<T> clazz) {
  103. List<T> al = new ArrayList<>();
  104. for(S s:source){
  105. al.add(Transform.convert(s, clazz));
  106. }
  107. return al;
  108. }
  109. public static <T> void replace(List<T> targetList, Collection<T> objectList, Class<?> objectClass, String indexProp) throws RuntimeException {
  110. if(objectList.size() == 0 || targetList.size() == 0) return ;
  111. Map<Object, T> objectMap = new HashMap<>(objectList.size());
  112. Field objectField = getField(objectClass, indexProp);
  113. try {
  114. for(T o: objectList){
  115. objectMap.put(objectField.get(o), o);
  116. }
  117. targetList.replaceAll(e-> {
  118. try {
  119. return objectMap.get(objectField.get(e));
  120. } catch (IllegalAccessException e1) {
  121. e1.printStackTrace();
  122. return e;
  123. }
  124. });
  125. } catch (IllegalAccessException e) {
  126. e.printStackTrace();
  127. throw new RuntimeException("ObjectClass:"+objectClass.getName()+" access "+indexProp+" exception");
  128. }
  129. }
  130. public static <T, S> void combine(List<T> targetList, Collection<S> objectList, Class<?> targetClass, String keyProp, String targetProp, Class<?> objectClass, String indexProp) throws RuntimeException {
  131. if(objectList.size() == 0 || targetList.size() == 0) return ;
  132. Map<Object, S> objectMap = new HashMap<>(objectList.size());
  133. Field objectField = getField(objectClass, indexProp);
  134. try {
  135. for(S o: objectList){
  136. objectMap.put(objectField.get(o), o);
  137. }
  138. } catch (IllegalAccessException e) {
  139. e.printStackTrace();
  140. throw new RuntimeException("ObjectClass:"+objectClass.getName()+" access "+indexProp+" exception");
  141. }
  142. combine(targetList, objectMap, targetClass, keyProp, targetProp);
  143. }
  144. public static <T, S, R> void combine(List<T> targetList, Collection<S> objectList, Class<?> targetClass, String keyProp, String targetProp, Class<?> objectClass, String indexProp, Class<?> transform) throws RuntimeException {
  145. if(objectList.size() == 0 || targetList.size() == 0) return ;
  146. Map<Object, R> objectMap = new HashMap<>(objectList.size());
  147. Field objectField = getField(objectClass, indexProp);
  148. try {
  149. for(S o: objectList){
  150. objectMap.put(objectField.get(o), convert(o, transform));
  151. }
  152. } catch (IllegalAccessException e) {
  153. e.printStackTrace();
  154. throw new RuntimeException("ObjectClass:"+objectClass.getName()+" access "+indexProp+" exception");
  155. }
  156. combine(targetList, objectMap, targetClass, keyProp, targetProp);
  157. }
  158. public static <T, S> void combine(List<T> targetList, Map<Object, S> objectMap, Class<?> targetClass, String keyProp, String targetProp) throws RuntimeException {
  159. if(objectMap.size() == 0 || targetList.size() == 0) return ;
  160. Field targetField = getField(targetClass, targetProp);
  161. Field targetKeyField = getField(targetClass, keyProp);
  162. try {
  163. for(T t: targetList){
  164. S o = objectMap.get(targetKeyField.get(t));
  165. targetField.set(t, o);
  166. }
  167. } catch (IllegalAccessException e) {
  168. e.printStackTrace();
  169. throw new RuntimeException("TargetClass:"+targetClass.getName()+" access "+keyProp+" exception");
  170. }
  171. }
  172. public static <T, S> void combine(List<T> targetList, Map<Object, Collection<S>> objectMap, Class<?> targetClass, String keyProp, String targetProp, Class<?> transform) throws RuntimeException {
  173. if(objectMap.size() == 0 || targetList.size() == 0) return ;
  174. Field targetField = getField(targetClass, targetProp);
  175. Field targetKeyField = getField(targetClass, keyProp);
  176. try {
  177. for(T t: targetList){
  178. Collection<S> o = objectMap.get(targetKeyField.get(t));
  179. if (transform == null){
  180. targetField.set(t, o);
  181. }else{
  182. targetField.set(t, convert(o, transform));
  183. }
  184. }
  185. } catch (IllegalAccessException e) {
  186. e.printStackTrace();
  187. throw new RuntimeException("TargetClass:"+targetClass.getName()+" access "+keyProp+" exception");
  188. }
  189. }
  190. private static Object transfer(Object source, Class<?> clazz) {
  191. if (source == null) {
  192. return null;
  193. }
  194. return modelMapper.map(source, clazz);
  195. }
  196. private static Object transfer(Object source, Type type){
  197. if (source == null) {
  198. return null;
  199. }
  200. logger.info("{}", type);
  201. return modelMapper.map(source, type);
  202. }
  203. public static Field getField(Class<?> clazz, String prop){
  204. Field field;
  205. try {
  206. field = clazz.getDeclaredField(prop);
  207. field.setAccessible(true);
  208. } catch (NoSuchFieldException e) {
  209. // 关系继承类
  210. try {
  211. field = clazz.getSuperclass().getDeclaredField(prop);
  212. field.setAccessible(true);
  213. } catch (NoSuchFieldException e1) {
  214. throw new RuntimeException("TargetClass:"+clazz.getName()+" no "+prop);
  215. }
  216. }
  217. return field;
  218. }
  219. public static <T> Collection getIds(Collection<T> list, Class<?> clazz, String idProp) throws RuntimeException {
  220. Set ids = new HashSet<>();
  221. if(list == null || list.size() == 0) return ids;
  222. Field field = Transform.getField(clazz, idProp);
  223. try {
  224. for(T item: list){
  225. ids.add(field.get(item));
  226. }
  227. return ids;
  228. } catch (IllegalAccessException e) {
  229. e.printStackTrace();
  230. throw new RuntimeException("Class:"+clazz.getName()+" access "+idProp+" exception");
  231. }
  232. }
  233. public static <T> Map getMap(Collection<T> list, Class<?> clazz, String keyProp) throws RuntimeException{
  234. Map map = new HashMap<>();
  235. if(list == null || list.size() == 0) return map;
  236. Field keyField = Transform.getField(clazz, keyProp);
  237. try{
  238. for(T item: list){
  239. map.put(keyField.get(item), item);
  240. }
  241. return map;
  242. } catch (IllegalAccessException e) {
  243. e.printStackTrace();
  244. throw new RuntimeException("Class:"+clazz.getName()+" access "+keyProp+" exception");
  245. }
  246. }
  247. public static <T> Map getMap(Collection<T> list, Class<?> clazz, String keyProp, String valueProp) throws RuntimeException{
  248. Map map = new HashMap<>();
  249. if(list == null || list.size() == 0) return map;
  250. Field keyField = Transform.getField(clazz, keyProp);
  251. Field valueField = Transform.getField(clazz, valueProp);
  252. try{
  253. for(T item: list){
  254. map.put(keyField.get(item), valueField.get(item));
  255. }
  256. return map;
  257. } catch (IllegalAccessException e) {
  258. e.printStackTrace();
  259. throw new RuntimeException("Class:"+clazz.getName()+" access "+keyProp+","+valueProp+" exception");
  260. }
  261. }
  262. public static <T,S> Map<Object, List<T>> getMapList(List<S> list, List<T> targetList, Class<?> clazz, String keyProp, String targetProp, Class<?> targetClazz, String indexProp){
  263. return new HashMap<Object, List<T>>();
  264. }
  265. }