inleft
2022-02-15 d734432a8bbbf863dc3de305f56e831c56ac767a
commit | author | age
9bcb19 1 /*
I 2 Copyright [2020] [https://www.xiaonuo.vip]
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8   http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15
16 Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
17
18 1.请不要删除和修改根目录下的LICENSE文件。
19 2.请不要删除和修改Snowy源码头部的版权声明。
20 3.请保留源码和相关描述文件的项目出处,作者声明等。
21 4.分发源码时候,请注明软件出处 https://gitee.com/xiaonuobase/snowy
22 5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/xiaonuobase/snowy
23 6.若您的项目无法满足以上几点,可申请商业授权,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip
24  */
25 package vip.xiaonuo.generate.modular.service.impl;
26
27 import cn.hutool.core.bean.BeanUtil;
28 import cn.hutool.core.util.ObjectUtil;
29 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
30 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
31 import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
32 import org.apache.commons.io.IOUtils;
33 import org.apache.velocity.Template;
34 import org.apache.velocity.VelocityContext;
35 import org.apache.velocity.app.Velocity;
36 import org.apache.velocity.app.VelocityEngine;
37 import org.springframework.stereotype.Service;
38 import vip.xiaonuo.core.exception.ServiceException;
39 import vip.xiaonuo.core.factory.PageFactory;
40 import vip.xiaonuo.core.pojo.page.PageResult;
41 import vip.xiaonuo.generate.core.consts.GenConstant;
42 import vip.xiaonuo.generate.core.context.XnVelocityContext;
43 import vip.xiaonuo.generate.core.param.XnCodeGenParam;
44 import vip.xiaonuo.generate.core.tool.StringDateTool;
45 import vip.xiaonuo.generate.core.util.Util;
46 import vip.xiaonuo.generate.modular.entity.CodeGenerate;
47 import vip.xiaonuo.generate.modular.entity.SysCodeGenerateConfig;
48 import vip.xiaonuo.generate.modular.enums.CodeGenerateExceptionEnum;
49 import vip.xiaonuo.generate.modular.mapper.CodeGenerateMapper;
50 import vip.xiaonuo.generate.modular.param.CodeGenerateParam;
51 import vip.xiaonuo.generate.modular.param.SysCodeGenerateConfigParam;
52 import vip.xiaonuo.generate.modular.result.InforMationColumnsResult;
53 import vip.xiaonuo.generate.modular.result.InformationResult;
54 import vip.xiaonuo.generate.modular.service.CodeGenerateService;
55 import vip.xiaonuo.generate.modular.service.SysCodeGenerateConfigService;
56
57 import javax.annotation.Resource;
58 import javax.servlet.http.HttpServletResponse;
59 import java.io.*;
60 import java.util.List;
61 import java.util.Map;
62 import java.util.Properties;
63 import java.util.zip.ZipEntry;
64 import java.util.zip.ZipOutputStream;
65
66 /**
67  * 代码生成基础配置service接口实现类
68  *
69  * @author yubaoshan
70  * @date 2020年12月16日21:31:57
71  */
72 @Service
73 public class CodeGenerateServiceImpl extends ServiceImpl<CodeGenerateMapper, CodeGenerate> implements CodeGenerateService {
74
75     /**
76      * 模板后缀
77      */
78     private static String TEMP_SUFFIX = ".vm";
79
80     /**
81      * 转换的编码
82      */
83     private static String ENCODED = "UTF-8";
84
85     private static String SELECT_SYS_MENU_SQL = "select * from sys_menu where id = {0}";
86
87     /**
88      * 转换模板名称所需变量
89      */
90     private static String ADD_FORM_PAGE_NAME = "addForm.vue";
91     private static String EDIT_FORM_PAGE_NAME = "editForm.vue";
92     private static String INDEX_PAGE_NAME = "index.vue";
93     private static String MANAGE_JS_NAME = "Manage.js";
94     private static String SQL_NAME = ".sql";
95     private static String JAVA_SUFFIX = ".java";
96     private static String TEMP_ENTITY_NAME = "entity";
97
98     @Resource
99     private SysCodeGenerateConfigService sysCodeGenerateConfigService;
100
101     @Override
102     public PageResult<CodeGenerate> page(CodeGenerateParam codeGenerateParam) {
103         QueryWrapper<CodeGenerate> queryWrapper = new QueryWrapper<>();
104         if (ObjectUtil.isNotNull(codeGenerateParam)) {
105             //根据表名模糊查询
106             if (ObjectUtil.isNotEmpty(codeGenerateParam.getTableName())) {
107                 queryWrapper.lambda().like(CodeGenerate::getTableName, codeGenerateParam.getTableName());
108             }
109         }
110         return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
111     }
112
113     @Override
114     public void add(CodeGenerateParam codeGenerateParam) {
115         CodeGenerate codeGenerate = new CodeGenerate();
116         BeanUtil.copyProperties(codeGenerateParam, codeGenerate);
117         if (!vldTablePri(codeGenerate.getTableName())) {
118             throw new ServiceException(CodeGenerateExceptionEnum.CODE_GEN_TABLE_NOT_PRI);
119         }
120         this.save(codeGenerate);
121
122         // 加入配置表中
123         codeGenerateParam.setId(codeGenerate.getId());
124         this.sysCodeGenerateConfigService.addList(this.getInforMationColumnsResultList(codeGenerateParam), codeGenerate);
125     }
126
127     @Override
128     public void delete(List<CodeGenerateParam> codeGenerateParamList) {
129         codeGenerateParamList.forEach(codeGenerateParam -> {
130             this.removeById(codeGenerateParam.getId());
131             SysCodeGenerateConfigParam sysCodeGenerateConfigParam = new SysCodeGenerateConfigParam();
132             sysCodeGenerateConfigParam.setCodeGenId(codeGenerateParam.getId());
133             this.sysCodeGenerateConfigService.delete(sysCodeGenerateConfigParam);
134         });
135     }
136
137     @Override
138     public void edit(CodeGenerateParam codeGenerateParam) {
139         CodeGenerate codeGenerate = this.queryCodeGenerate(codeGenerateParam);
140         BeanUtil.copyProperties(codeGenerateParam, codeGenerate);
141         if (!vldTablePri(codeGenerate.getTableName())) {
142             throw new ServiceException(CodeGenerateExceptionEnum.CODE_GEN_TABLE_NOT_PRI);
143         }
144         this.updateById(codeGenerate);
145     }
146
147     @Override
148     public CodeGenerate detail(CodeGenerateParam codeGenerateParam) {
149         return this.queryCodeGenerate(codeGenerateParam);
150     }
151
152     /**
153      * 获取代码生成基础配置
154      *
155      * @author yubaoshan
156      * @date 2020年12月16日21:19:10
157      */
158     private CodeGenerate queryCodeGenerate(CodeGenerateParam codeGenerateParam) {
159         CodeGenerate codeGenerate = this.getById(codeGenerateParam.getId());
160         if (ObjectUtil.isNull(codeGenerate)) {
161             throw new ServiceException(CodeGenerateExceptionEnum.CODE_GEN_NOT_EXIST);
162         }
163         return codeGenerate;
164     }
165
166     @Override
167     public List<InformationResult> InformationTableList () {
168         return this.baseMapper.selectInformationTable(Util.getDataBasename());
169     }
170
171     @Override
172     public void runLocal(CodeGenerateParam codeGenerateParam) {
173         XnCodeGenParam xnCodeGenParam = copyParams(codeGenerateParam);
174         codeGenLocal(xnCodeGenParam);
175     }
176
177     @Override
178     public void runDown(CodeGenerateParam codeGenerateParam, HttpServletResponse response) {
179         XnCodeGenParam xnCodeGenParam = copyParams(codeGenerateParam);
180         downloadCode(xnCodeGenParam, response);
181     }
182
183     /**
184      * 校验表中是否包含主键
185      *
186      * @author yubaoshan
187      * @date 2020年12月23日 00点32分
188      */
189     private boolean vldTablePri (String tableName) {
190         List<InforMationColumnsResult> inforMationColumnsResultList =  this.baseMapper.selectInformationColumns(Util.getDataBasename(), tableName);
191         for (int a = 0; a < inforMationColumnsResultList.size(); a++) {
192             if (ObjectUtil.isNotNull(inforMationColumnsResultList.get(a).columnKey)
193                     && inforMationColumnsResultList.get(a).columnKey.equals(GenConstant.DB_TABLE_COM_KRY)) {
194                 return true;
195             }
196         }
197         return false;
198     }
199
200     /**
201      * 下载方式组装代码基础
202      *
203      * @author yubaoshan
204      * @date 2020年12月23日 00点32分
205      */
206     private void downloadCode(XnCodeGenParam xnCodeGenParam, HttpServletResponse response) {
207         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
208         ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
209         codeGenDown(xnCodeGenParam, zipOutputStream);
210         IOUtils.closeQuietly(zipOutputStream);
211         outputStream.toByteArray();
212         try {
213             Util.DownloadGen(response, outputStream.toByteArray());
214         } catch (Exception e) {
215             throw new ServiceException(CodeGenerateExceptionEnum.CODE_GEN_NOT_PATH);
216         }
217     }
218
219     /**
220      * 获取表中所有字段集合
221      *
222      * @author yubaoshan
223      * @date 2021-02-06 22:36
224      */
225     private List<InforMationColumnsResult> getInforMationColumnsResultList (CodeGenerateParam codeGenerateParam) {
226         CodeGenerate codeGenerate = this.queryCodeGenerate(codeGenerateParam);
227         return this.baseMapper.selectInformationColumns(Util.getDataBasename(), codeGenerate.getTableName());
228     }
229
230     private XnCodeGenParam copyParams (CodeGenerateParam codeGenerateParam) {
231         CodeGenerate codeGenerate = this.queryCodeGenerate(codeGenerateParam);
232         SysCodeGenerateConfigParam sysCodeGenerateConfigParam = new SysCodeGenerateConfigParam();
233         sysCodeGenerateConfigParam.setCodeGenId(codeGenerateParam.getId());
234         List<SysCodeGenerateConfig> configList = this.sysCodeGenerateConfigService.list(sysCodeGenerateConfigParam);
235         XnCodeGenParam param = new XnCodeGenParam();
236         BeanUtil.copyProperties(codeGenerate, param);
237         // 功能名
238         param.setFunctionName(codeGenerate.getTableComment());
239         param.setConfigList(configList);
240         param.setCreateTimeString(StringDateTool.getStringDate());
241         if (!codeGenerate.getMenuPid().equals("0")) {
242             Map<String, Object> map = SqlRunner.db().selectOne(SELECT_SYS_MENU_SQL, codeGenerate.getMenuPid());
243             param.setMenuPids(map.get("pids").toString());
244         }
245         return param;
246     }
247
248     /**
249      * 本地项目生成
250      */
251     private void codeGenLocal (XnCodeGenParam xnCodeGenParam) {
252         XnVelocityContext context = new XnVelocityContext();
253         //初始化参数
254         Properties properties=new Properties();
255         //设置velocity资源加载方式为class
256         properties.setProperty("resource.loader", "class");
257         //设置velocity资源加载方式为file时的处理类
258         properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
259         //实例化一个VelocityEngine对象
260         VelocityEngine velocityEngine=new VelocityEngine(properties);
261
262         String[] filePath = GenConstant.xnCodeGenFilePath(xnCodeGenParam.getBusName(), xnCodeGenParam.getPackageName());
263         for (int i = 0; i < filePath.length; i++) {
264             String templateName = GenConstant.xnCodeGenTempFile[i];
265
266             String fileBaseName = ResetFileBaseName(xnCodeGenParam.getClassName(),
267                     templateName.substring(templateName.indexOf(GenConstant.FILE_SEP) + 1, templateName.lastIndexOf(TEMP_SUFFIX)));
268             String path = GenConstant.getLocalPath ();
269             // 前端VUE位置有所变化, sql同样根目录
270             if (fileBaseName.contains(INDEX_PAGE_NAME) || fileBaseName.contains(ADD_FORM_PAGE_NAME) ||
271                     fileBaseName.contains(EDIT_FORM_PAGE_NAME) ||fileBaseName.contains(MANAGE_JS_NAME) ||
272             fileBaseName.contains(SQL_NAME)) {
273                 path = GenConstant.getLocalFrontPath();
274             }
275
276             File file = new File(path + filePath[i] + fileBaseName);
277
278             //判断是否覆盖存在的文件
279             if(file.exists() && !GenConstant.FLAG){
280                 continue;
281             }
282
283             //获取父目录
284             File parentFile = file.getParentFile();
285             if(!parentFile.exists()){
286                 parentFile.mkdirs();
287             }
288             try {
289                 Writer writer = new FileWriter(file);
290                 velocityEngine.mergeTemplate(GenConstant.templatePath + templateName,ENCODED,context.createVelContext(xnCodeGenParam),writer);
291                 writer.close();
292             } catch (Exception e) {
293                 throw new ServiceException(CodeGenerateExceptionEnum.CODE_GEN_NOT_PATH);
294             }
295         }
296     }
297
298     /**
299      * 下载ZIP方式
300      */
301     private void codeGenDown (XnCodeGenParam xnCodeGenParam,ZipOutputStream zipOutputStream) {
302         Util.initVelocity();
303         XnVelocityContext context = new XnVelocityContext();
304
305         String[] filePath = GenConstant.xnCodeGenFilePath(xnCodeGenParam.getBusName(), xnCodeGenParam.getPackageName());
306         for (int a = 0; a < filePath.length; a++) {
307             String templateName = GenConstant.xnCodeGenTempFile[a];
308
309             String fileBaseName = ResetFileBaseName(xnCodeGenParam.getClassName(),
310                     templateName.substring(templateName.indexOf(GenConstant.FILE_SEP) + 1, templateName.lastIndexOf(TEMP_SUFFIX)));
311             XnZipOutputStream(context.createVelContext(xnCodeGenParam),
312                     GenConstant.templatePath + templateName,
313                     filePath[a] + fileBaseName,
314                     zipOutputStream);
315         }
316     }
317
318     /**
319      * 重置文件名称
320      */
321     private static String ResetFileBaseName (String className,String fileName) {
322         String fileBaseName = className + fileName;
323         // 实体类名称单独处理
324         if (fileBaseName.contains(TEMP_ENTITY_NAME)) {
325             return className + JAVA_SUFFIX;
326         }
327         // 首页index.vue界面
328         if (fileBaseName.contains(INDEX_PAGE_NAME)) {
329             return INDEX_PAGE_NAME;
330         }
331         // 表单界面名称
332         if (fileBaseName.contains(ADD_FORM_PAGE_NAME)) {
333             return ADD_FORM_PAGE_NAME;
334         }
335         if (fileBaseName.contains(EDIT_FORM_PAGE_NAME)) {
336             return EDIT_FORM_PAGE_NAME;
337         }
338         // js名称
339         if (fileBaseName.contains(MANAGE_JS_NAME)) {
340             return className.substring(0,1).toLowerCase() + className.substring(1) + MANAGE_JS_NAME;
341         }
342         return fileBaseName;
343     }
344
345     /**
346      * 生成ZIP
347      */
348     private void XnZipOutputStream (VelocityContext velContext,String tempName, String fileBaseName, ZipOutputStream zipOutputStream) {
349         StringWriter sw = new StringWriter();
350         Template tpl = Velocity.getTemplate(tempName, ENCODED);
351         tpl.merge(velContext, sw);
352         try {
353             // 添加到zip
354             zipOutputStream.putNextEntry(new ZipEntry(fileBaseName));
355             IOUtils.write(sw.toString(), zipOutputStream, ENCODED);
356             IOUtils.closeQuietly(sw);
357             zipOutputStream.flush();
358             zipOutputStream.closeEntry();
359         } catch (IOException e) {
360             throw new ServiceException(CodeGenerateExceptionEnum.CODE_GEN_NOT_PATH);
361         }
362     }
363
364 }