GenCodeService.java 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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").toAbsolutePath() :
  32. Paths.get(model.getJavaPath(), "web", model.getClassName() + "Controller.java").toAbsolutePath();
  33. Map<String, Object> extra = new HashMap<>();
  34. if (StringUtil.isNotEmpty(model.getGenPackage())) {
  35. List<String> imports = new ArrayList<>();
  36. imports.add("import " + model.getBasePackage() + ".web.BaseController;");
  37. extra.put("imports", imports);
  38. }
  39. extra.put("subPackage", StringUtil.isNotEmpty(model.getGenPackage()));
  40. genFile("ControllerTemplate.ftl", model, extra, targetFile);
  41. log.info("成功生成Controller:{}", targetFile.toString());
  42. }
  43. public void genService(GenCode model) throws IOException, TemplateException {
  44. Path targetFile = StringUtils.isNotBlank(model.getGenPackage()) ?
  45. Paths.get(model.getJavaPath(), "service", model.getGenPackage(), model.getClassName() + "Service.java").toAbsolutePath() :
  46. Paths.get(model.getJavaPath(), "service", model.getClassName() + "Service.java").toAbsolutePath();
  47. genFile("ServiceTemplate.ftl", model, null, targetFile);
  48. log.info("成功生成Service:{}", targetFile.toString());
  49. }
  50. public void genRepo(GenCode model) throws IOException, TemplateException, ClassNotFoundException {
  51. Path targetFile = StringUtils.isNotBlank(model.getGenPackage()) ?
  52. Paths.get(model.getJavaPath(), "repo", model.getGenPackage(), model.getClassName() + "Repo.java").toAbsolutePath() :
  53. Paths.get(model.getJavaPath(), "repo", model.getClassName() + "Repo.java").toAbsolutePath();
  54. Map<String, Object> extra = new HashMap<>();
  55. extra.put("softDelete", false);
  56. try {
  57. Field field = Class.forName(model.getTablePackage()).getDeclaredField("enabled");
  58. if (field != null && field.getType().equals(Boolean.class)) {
  59. extra.put("softDelete", true);
  60. }
  61. } catch (NoSuchFieldException ignored) {
  62. }
  63. genFile("RepoTemplate.ftl", model, extra, targetFile);
  64. log.info("成功生成Repo:{}", targetFile.toString());
  65. }
  66. public void genListView(GenCode model) throws IOException, TemplateException {
  67. Path targetFile = Paths.get(model.getViewPath(), model.getClassName() + "List.vue").toAbsolutePath();
  68. genFile("ListViewTemplate.ftl", model, null, targetFile);
  69. log.info("成功生成ListView:{}", targetFile.toString());
  70. }
  71. public void genEditView(GenCode model) throws IOException, TemplateException, FontFormatException {
  72. Path targetFile = Paths.get(model.getViewPath(), model.getClassName() + "Edit.vue").toAbsolutePath();
  73. Map<String, Object> map = new HashMap<>();
  74. int maxLabelWidth = 0;
  75. for (TableField field : model.getFields()) {
  76. String label = StringUtils.isEmpty(field.getRemark()) ? field.getModelName() : field.getRemark();
  77. int labelWidth = measureText(label, 14);
  78. if (labelWidth > maxLabelWidth) {
  79. maxLabelWidth = labelWidth;
  80. }
  81. }
  82. map.put("labelWidth", maxLabelWidth + 25 + "px");
  83. genFile("EditViewTemplate.ftl", model, map, targetFile);
  84. log.info("成功生成EditView:{}", targetFile.toString());
  85. }
  86. private void genFile(String template, GenCode model, Map<String, Object> extraData, Path path) throws IOException, TemplateException {
  87. Map<String, Object> data = new HashMap<>();
  88. data.put("model", model);
  89. if (extraData != null) {
  90. data.putAll(extraData);
  91. }
  92. Files.createDirectories(path.getParent());
  93. Template temp = cfg.getTemplate(template);
  94. Writer out = new FileWriter(path.toString());
  95. temp.process(data, out);
  96. out.flush();
  97. out.close();
  98. }
  99. private int measureText(String text, float fontSize) throws IOException, FontFormatException {
  100. AffineTransform affinetransform = new AffineTransform();
  101. FontRenderContext frc = new FontRenderContext(affinetransform, true, true);
  102. Font font = Font.createFont(Font.TRUETYPE_FONT, this.getClass().getResourceAsStream("/font/PingFangRegular.ttf"));
  103. return (int) (font.deriveFont(fontSize).getStringBounds(text, frc).getWidth());
  104. }
  105. public void genRouter(GenCode model) {
  106. try {
  107. File file = new File(model.getRouterPath(), "router.js");
  108. BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
  109. StringBuilder routerJs = new StringBuilder();
  110. String line = null;
  111. while ((line = reader.readLine()) != null) {
  112. routerJs.append(line).append("\n");
  113. }
  114. reader.close();
  115. int insertLocation = routerJs.indexOf("/**INSERT_LOCATION**/");
  116. if (insertLocation > -1) {
  117. String routeName = StringUtils.capitalize(model.getClassName());
  118. String routePath = StringUtils.uncapitalize(model.getClassName());
  119. String route = "{\n path: '/"
  120. + routePath
  121. + "Edit',\n name: '"
  122. + routeName
  123. + "Edit',\n component: () => import(/* webpackChunkName: \"" + routePath + "List\" */ '@/views/"
  124. + routeName
  125. + "Edit.vue')\n },\n {\n path: '/"
  126. + routePath
  127. + "List',\n name: '"
  128. + routeName
  129. + "List',\n component: () => import(/* webpackChunkName: \"" + routePath + "Edit\" */ '@/views/"
  130. + routeName
  131. + "List.vue')\n }\n ";
  132. boolean needComma = !routerJs.toString().substring(0, insertLocation).trim().endsWith(",");
  133. if (needComma) {
  134. routerJs.insert(routerJs.toString().substring(0, insertLocation).lastIndexOf("}") + 1, ",");
  135. insertLocation++;
  136. }
  137. routerJs.insert(insertLocation, route);
  138. }
  139. BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
  140. bufferedOutputStream.write(routerJs.toString().trim().getBytes());
  141. bufferedOutputStream.close();
  142. System.out.println("成功生成路由:" + file.getAbsolutePath());
  143. } catch (Exception e) {
  144. e.printStackTrace();
  145. }
  146. }
  147. }