GenCodeService.java 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. package com.izouma.awesomeAdmin.service;
  2. import com.izouma.awesomeAdmin.dto.gen.GenCode;
  3. import com.izouma.awesomeAdmin.dto.gen.TableField;
  4. import freemarker.template.Configuration;
  5. import freemarker.template.Template;
  6. import freemarker.template.TemplateException;
  7. import jodd.util.StringUtil;
  8. import lombok.extern.slf4j.Slf4j;
  9. import org.apache.commons.lang.StringUtils;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.stereotype.Service;
  12. import java.awt.*;
  13. import java.awt.font.FontRenderContext;
  14. import java.awt.geom.AffineTransform;
  15. import java.io.*;
  16. import java.lang.reflect.Field;
  17. import java.nio.file.Files;
  18. import java.nio.file.Path;
  19. import java.nio.file.Paths;
  20. import java.util.ArrayList;
  21. import java.util.HashMap;
  22. import java.util.List;
  23. import java.util.Map;
  24. @Service
  25. @Slf4j
  26. public class GenCodeService {
  27. @Autowired
  28. private Configuration cfg;
  29. public void genController(GenCode model) throws IOException, TemplateException {
  30. Path targetFile = StringUtils.isNotBlank(model.getGenPackage()) ?
  31. Paths.get(model.getJavaPath(), "web", model.getGenPackage(), model.getClassName() + "Controller.java")
  32. .toAbsolutePath() :
  33. Paths.get(model.getJavaPath(), "web", model.getClassName() + "Controller.java").toAbsolutePath();
  34. Map<String, Object> extra = new HashMap<>();
  35. if (StringUtil.isNotEmpty(model.getGenPackage())) {
  36. List<String> imports = new ArrayList<>();
  37. imports.add("import " + model.getBasePackage() + ".web.BaseController;");
  38. extra.put("imports", imports);
  39. }
  40. extra.put("subPackage", StringUtil.isNotEmpty(model.getGenPackage()));
  41. extra.put("softDelete", canSoftDelete(model));
  42. genFile("ControllerTemplate.ftl", model, extra, targetFile);
  43. log.info("成功生成Controller:{}", targetFile.toString());
  44. }
  45. public void genService(GenCode model) throws IOException, TemplateException {
  46. Path targetFile = StringUtils.isNotBlank(model.getGenPackage()) ?
  47. Paths.get(model.getJavaPath(), "service", model.getGenPackage(), model.getClassName() + "Service.java")
  48. .toAbsolutePath() :
  49. Paths.get(model.getJavaPath(), "service", model.getClassName() + "Service.java").toAbsolutePath();
  50. Map<String, Object> extra = new HashMap<>();
  51. extra.put("softDelete", canSoftDelete(model));
  52. genFile("ServiceTemplate.ftl", model, extra, targetFile);
  53. log.info("成功生成Service:{}", targetFile.toString());
  54. }
  55. public void genRepo(GenCode model) throws IOException, TemplateException, ClassNotFoundException {
  56. Path targetFile = StringUtils.isNotBlank(model.getGenPackage()) ?
  57. Paths.get(model.getJavaPath(), "repo", model.getGenPackage(), model.getClassName() + "Repo.java")
  58. .toAbsolutePath() :
  59. Paths.get(model.getJavaPath(), "repo", model.getClassName() + "Repo.java").toAbsolutePath();
  60. Map<String, Object> extra = new HashMap<>();
  61. extra.put("softDelete", canSoftDelete(model));
  62. genFile("RepoTemplate.ftl", model, extra, targetFile);
  63. log.info("成功生成Repo:{}", targetFile.toString());
  64. }
  65. public void genListView(GenCode model) throws IOException, TemplateException {
  66. Path targetFile = Paths.get(model.getViewPath(), model.getClassName() + "List.vue").toAbsolutePath();
  67. Map<String, Object> extra = new HashMap<>();
  68. extra.put("softDelete", canSoftDelete(model));
  69. genFile("ListViewTemplate.ftl", model, extra, targetFile);
  70. log.info("成功生成ListView:{}", targetFile.toString());
  71. }
  72. public void genEditView(GenCode model) throws IOException, TemplateException, FontFormatException {
  73. Path targetFile = Paths.get(model.getViewPath(), model.getClassName() + "Edit.vue").toAbsolutePath();
  74. Map<String, Object> map = new HashMap<>();
  75. int maxLabelWidth = 0;
  76. for (TableField field : model.getFields()) {
  77. String label = StringUtils.isEmpty(field.getRemark()) ? field.getModelName() : field.getRemark();
  78. int labelWidth = measureText(label, 14);
  79. if (labelWidth > maxLabelWidth) {
  80. maxLabelWidth = labelWidth;
  81. }
  82. }
  83. map.put("labelWidth", maxLabelWidth + 25 + "px");
  84. map.put("softDelete", canSoftDelete(model));
  85. genFile("EditViewTemplate.ftl", model, map, targetFile);
  86. log.info("成功生成EditView:{}", targetFile.toString());
  87. }
  88. private void genFile(String template, GenCode model, Map<String, Object> extraData, Path path) throws IOException, TemplateException {
  89. Map<String, Object> data = new HashMap<>();
  90. data.put("model", model);
  91. if (extraData != null) {
  92. data.putAll(extraData);
  93. }
  94. Files.createDirectories(path.getParent());
  95. Template temp = cfg.getTemplate(template);
  96. Writer out = new FileWriter(path.toString());
  97. temp.process(data, out);
  98. out.flush();
  99. out.close();
  100. }
  101. private int measureText(String text, float fontSize) throws IOException, FontFormatException {
  102. AffineTransform affinetransform = new AffineTransform();
  103. FontRenderContext frc = new FontRenderContext(affinetransform, true, true);
  104. Font font = Font.createFont(Font.TRUETYPE_FONT, this.getClass()
  105. .getResourceAsStream("/font/SourceHanSansCN-Normal.ttf"));
  106. return (int) (font.deriveFont(fontSize).getStringBounds(text, frc).getWidth());
  107. }
  108. public void genRouter(GenCode model) {
  109. try {
  110. File file = new File(model.getRouterPath(), "router.js");
  111. BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
  112. StringBuilder routerJs = new StringBuilder();
  113. String line = null;
  114. while ((line = reader.readLine()) != null) {
  115. routerJs.append(line).append("\n");
  116. }
  117. reader.close();
  118. int insertLocation = routerJs.indexOf("/**INSERT_LOCATION**/");
  119. if (insertLocation > -1) {
  120. String remark = model.getRemark();
  121. String routeName = StringUtils.capitalize(model.getClassName());
  122. String routePath = StringUtils.uncapitalize(model.getClassName());
  123. String route = "{\n path: '/"
  124. + routePath
  125. + "Edit',\n name: '"
  126. + routeName
  127. + "Edit',\n component: () => import(/* webpackChunkName: \"" + routePath + "Edit\" */ '@/views/"
  128. + routeName
  129. + "Edit.vue'),\n meta: {\n title: '" + remark + "编辑',\n"
  130. + " },\n },\n {\n path: '/"
  131. + routePath
  132. + "List',\n name: '"
  133. + routeName
  134. + "List',\n component: () => import(/* webpackChunkName: \"" + routePath + "List\" */ '@/views/"
  135. + routeName
  136. + "List.vue'),\n meta: {\n title: '" + remark + "',\n"
  137. + " },\n }\n ";
  138. boolean needComma = !routerJs.toString().substring(0, insertLocation).trim().endsWith(",");
  139. if (needComma) {
  140. routerJs.insert(routerJs.toString().substring(0, insertLocation).lastIndexOf("}") + 1, ",");
  141. insertLocation++;
  142. }
  143. routerJs.insert(insertLocation, route);
  144. }
  145. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
  146. bufferedOutputStream.write(routerJs.toString().trim().getBytes());
  147. bufferedOutputStream.close();
  148. System.out.println("成功生成路由:" + file.getAbsolutePath());
  149. } catch (Exception e) {
  150. e.printStackTrace();
  151. }
  152. }
  153. private boolean canSoftDelete(GenCode model) {
  154. try {
  155. Field field = Class.forName(model.getTablePackage()).getDeclaredField("enabled");
  156. if (field != null && field.getType().equals(Boolean.class)) {
  157. return true;
  158. }
  159. } catch (NoSuchFieldException | ClassNotFoundException ignored) {
  160. }
  161. return false;
  162. }
  163. }