This commit is contained in:
20932067@zju.edu.cn 2021-01-28 23:17:27 +08:00
parent 59dd327214
commit 3967854cd2
8 changed files with 324 additions and 176 deletions

View File

@ -52,67 +52,68 @@
</el-form> </el-form>
</template> </template>
<script> <script>
import {queryListModule} from "@/api/tool/module" import {queryListModule} from "@/api/tool/module"
export default {
name: "ApiclassInfoForm", export default {
props: { name: "ApiclassInfoForm",
info: { props: {
type: Object, info: {
default: null type: Object,
} default: null
},
data() {
return {
moduleList:[],
rules: {
packageName: [
{required: true, message: "包名不能为空", trigger: "blur"},
],
mId: [
{required: true, message: "模块不能为空", trigger: "blur"},
],
cName: [
{required: true, message: "类名不能为空", trigger: "blur"},
],
cDescribe: [
{required: true, message: "类描述不能为空", trigger: "blur"},
],
author: [
{required: true, message: "作者不能为空", trigger: "blur"},
],
email: [
{required: true, message: "电子邮件不能为空", trigger: "blur"},
{
pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
message: '电子邮件格式有误',
trigger: "blur"
},
],
}
};
},
created() {
queryListModule().then(respone => {
this.moduleList = respone.data
})
},
methods:{
transform() {
var mid = this.info.mId
var str = ''
var start = true
for (let i = 0; i < this.moduleList.length; i++) {
if (mid == this.moduleList[i].id) {
str = this.moduleList[i].mName
start = false
}
}
if (start) {
str = ''
}
this.info.packageName = 'com.hchyun.' + str +"."
this.info.prefix = str+":"+this.info.cName + ":"
},
} }
}; },
data() {
return {
moduleList: [],
rules: {
packageName: [
{required: true, message: "包名不能为空", trigger: "blur"},
],
mId: [
{required: true, message: "模块不能为空", trigger: "blur"},
],
cName: [
{required: true, message: "类名不能为空", trigger: "blur"},
],
cDescribe: [
{required: true, message: "类描述不能为空", trigger: "blur"},
],
author: [
{required: true, message: "作者不能为空", trigger: "blur"},
],
email: [
{required: true, message: "电子邮件不能为空", trigger: "blur"},
{
pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
message: '电子邮件格式有误',
trigger: "blur"
},
],
}
};
},
created() {
queryListModule().then(respone => {
this.moduleList = respone.data
})
},
methods: {
transform() {
var mid = this.info.mId
var str = ''
var start = true
for (let i = 0; i < this.moduleList.length; i++) {
if (mid == this.moduleList[i].id) {
str = this.moduleList[i].mName
start = false
}
}
if (start) {
str = ''
}
this.info.packageName = 'com.hchyun.' + str
this.info.prefix = str + ":" + this.info.cName.toLowerCase()
},
}
};
</script> </script>

View File

@ -222,7 +222,11 @@
import {queryListModule} from "@/api/tool/module" import {queryListModule} from "@/api/tool/module"
import {getClassPreview} from "@/api/tool/interTable" import {getClassPreview} from "@/api/tool/interTable"
import hljs from "highlight.js/lib/highlight"; import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
import {genCode} from "@/api/tool/gen";
import {downLoadZip} from "@/utils/zipdownload";
hljs.registerLanguage("java", require("highlight.js/lib/languages/java")); hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));
export default { export default {
name: "Apiclass", name: "Apiclass",
components: {}, components: {},
@ -307,17 +311,23 @@
methods: { methods: {
/** 预览代码 */ /** 预览代码 */
handlePreview(id){ handlePreview(id){
getClassPreview(3).then(res =>{ console.log(id)
getClassPreview(id).then(res =>{
this.preview.data = res.data; this.preview.data = res.data;
this.preview.open = true; this.preview.open = true;
var keys = Object.keys(res.data) var keys = Object.keys(res.data)
this.preview.activeName = keys[0] this.preview.activeName = keys[0]
}) })
}, },
/** 生成代码操作 */
handleGenTable(row) {
downLoadZip("/generator/intertable/classgen/" + row.id, "hchyun");
},
/** 高亮显示 */ /** 高亮显示 */
highlightedCode(code, key) { highlightedCode(code, key) {
const vmName = key; const vmName = key;
var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length); var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
console.log(language)
const result = hljs.highlight(language, code || "", true); const result = hljs.highlight(language, code || "", true);
return result.value || '&nbsp;'; return result.value || '&nbsp;';
}, },
@ -352,8 +362,8 @@
if (start) { if (start) {
str = '' str = ''
} }
this.form.packageName = 'com.hchyun.' + str +"." this.form.packageName = 'com.hchyun.' + str
this.form.prefix = str+":"+this.form.cName + ":" this.form.prefix = str+":"+this.form.cName.toLowerCase()
}, },
// //
reset() { reset() {

View File

@ -306,6 +306,7 @@ export default {
highlightedCode(code, key) { highlightedCode(code, key) {
const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm")); const vmName = key.substring(key.lastIndexOf("/") + 1, key.indexOf(".vm"));
var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length); var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
console.log(language)
const result = hljs.highlight(language, code || "", true); const result = hljs.highlight(language, code || "", true);
return result.value || '&nbsp;'; return result.value || '&nbsp;';
}, },

View File

@ -104,7 +104,7 @@
type="text" type="text"
size="small" size="small"
icon="el-icon-view" icon="el-icon-view"
@click="handlePreview(scope.row)" @click="handlePreview(scope.row.id)"
v-hasPermi="['tool:apiclass:preview']" v-hasPermi="['tool:apiclass:preview']"
>预览</el-button> >预览</el-button>
<el-button <el-button
@ -185,7 +185,9 @@
import { listModule, getModule, delModule, addModule, updateModule, exportModule } from "@/api/tool/module"; import { listModule, getModule, delModule, addModule, updateModule, exportModule } from "@/api/tool/module";
import { getModulePreview } from '@/api/tool/interTable' import { getModulePreview } from '@/api/tool/interTable'
import hljs from "highlight.js/lib/highlight"; import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
hljs.registerLanguage("java", require("highlight.js/lib/languages/java")); hljs.registerLanguage("java", require("highlight.js/lib/languages/java"));
hljs.registerLanguage("sql", require("highlight.js/lib/languages/sql"));
export default { export default {
name: "Module", name: "Module",
components: { components: {
@ -245,7 +247,8 @@ export default {
methods: { methods: {
/** 预览代码 */ /** 预览代码 */
handlePreview(id){ handlePreview(id){
getModulePreview(3).then(res=>{ console.log(id)
getModulePreview(id).then(res=>{
this.preview.data = res.data; this.preview.data = res.data;
this.preview.open = true; this.preview.open = true;
var keys = Object.keys(res.data) var keys = Object.keys(res.data)
@ -256,6 +259,7 @@ export default {
highlightedCode(code, key) { highlightedCode(code, key) {
const vmName = key; const vmName = key;
var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length); var language = vmName.substring(vmName.indexOf(".") + 1, vmName.length);
console.log(language)
const result = hljs.highlight(language, code || "", true); const result = hljs.highlight(language, code || "", true);
return result.value || '&nbsp;'; return result.value || '&nbsp;';
}, },

View File

@ -18,4 +18,8 @@ public class ReturnConstants {
* 操作失败 * 操作失败
*/ */
public static final String SYS_FAILL = "数据库异常!"; public static final String SYS_FAILL = "数据库异常!";
/**
* 接口为空
*/
public static final String INTER_NULL = "该类下接口数据为空,请先添加接口!";
} }

View File

@ -1,5 +1,6 @@
package com.hchyun.generator.controller; package com.hchyun.generator.controller;
import java.io.IOException;
import java.io.Serializable; import java.io.Serializable;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -14,6 +15,7 @@ import com.hchyun.generator.entity.Apiclass;
import com.hchyun.generator.service.ApiclassService; import com.hchyun.generator.service.ApiclassService;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -34,6 +36,8 @@ import com.hchyun.generator.entity.InterTable;
import com.hchyun.generator.service.InterTableService; import com.hchyun.generator.service.InterTableService;
import com.hchyun.common.utils.poi.ExcelUtil; import com.hchyun.common.utils.poi.ExcelUtil;
import javax.servlet.http.HttpServletResponse;
/** /**
* 接口信息Controller * 接口信息Controller
* *
@ -76,16 +80,18 @@ public class InterTableController extends HcyBaseController {
*/ */
@ApiOperation("预览代码(工作流)") @ApiOperation("预览代码(工作流)")
@PreAuthorize("@ss.hasPermi('generator:intertable:classpreview')")
@Log(title = "预览代码(工作流)", businessType = BusinessType.GENCODE)
@GetMapping("/classpreview/{id}") @GetMapping("/classpreview/{id}")
public AjaxResult classPreview(@PathVariable("id") Long id){ public AjaxResult classPreview(@PathVariable("id") Long id) {
try { try {
ServerResult<Map<String,String>> serverResult = interTableService.previewCodeCalss(id); ServerResult<Map<String, String>> serverResult = interTableService.previewCodeCalss(id);
if (serverResult.isStart()){ if (serverResult.isStart()) {
return AjaxResult.success(serverResult.getData()); return AjaxResult.success(serverResult.getData());
}else { } else {
return AjaxResult.error(serverResult.getMsg()); return AjaxResult.error(serverResult.getMsg());
} }
}catch (RuntimeException e){ } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR); return AjaxResult.error(ReturnConstants.SYS_ERROR);
} }
@ -95,54 +101,16 @@ public class InterTableController extends HcyBaseController {
* 预览代码(工作台) * 预览代码(工作台)
*/ */
@ApiOperation("预览代码(工作台)") @ApiOperation("预览代码(工作台)")
@PreAuthorize("@ss.hasPermi('generator:intertable:modulepreview')")
@Log(title = "预览代码(工作台)", businessType = BusinessType.GENCODE)
@GetMapping("/modulepreview/{id}") @GetMapping("/modulepreview/{id}")
public AjaxResult modulePreview(@PathVariable("id") Long id){ public AjaxResult modulePreview(@PathVariable("id") Long id) {
try { try {
ServerResult<Map<String,Object>> serverResult = interTableService.previewCodeMoudle(id); ServerResult<Map<String, Object>> serverResult = interTableService.previewCodeMoudle(id);
if (serverResult.isStart()){
return AjaxResult.success(serverResult.getData());
}else {
return AjaxResult.error(serverResult.getMsg());
}
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
}
// /**
// * 导出接口信息列表
// */
// @PreAuthorize("@ss.hasPermi('generator:intertable:export')")
// @Log(title = "接口信息", businessType = BusinessType.EXPORT)
// @GetMapping("/export")
// public AjaxResult export(InterTable interTable) {
// try {
// ServerResult<List<InterTable>> serverResult = interTableService.selectInterTableList(interTable);
// ExcelUtil<InterTable> util = new ExcelUtil<InterTable>(InterTable. class);
// if (serverResult.isStart()) {
// return util.exportExcel(serverResult.getData(), "intertable");
// } else {
// return AjaxResult.error(serverResult.getMsg());
// }
// } catch (RuntimeException e) {
// logger.error(e.getMessage());
// return AjaxResult.error(ReturnConstants.SYS_ERROR);
// }
// }
/**
* 获取接口信息详细信息
*/
@PreAuthorize("@ss.hasPermi('generator:intertable:query')")
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) {
try {
ServerResult<InterTable> serverResult = interTableService.selectInterTableById(id);
if (serverResult.isStart()) { if (serverResult.isStart()) {
return AjaxResult.success(serverResult.getData()); return AjaxResult.success(serverResult.getData());
} else { } else {
return AjaxResult.info(serverResult.getMsg()); return AjaxResult.error(serverResult.getMsg());
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
@ -150,21 +118,27 @@ public class InterTableController extends HcyBaseController {
} }
} }
/** /**
* 新增接口信息 * 生成代码(工作流)
*
* @param id
* @return
*/ */
@PreAuthorize("@ss.hasPermi('generator:intertable:add')") @ApiOperation("生成代码(工作流)")
@Log(title = "接口信息", businessType = BusinessType.INSERT) @PreAuthorize("@ss.hasPermi('generator:intertable:classgen')")
@PostMapping @Log(title = "生成代码(工作流)", businessType = BusinessType.GENCODE)
public AjaxResult add(@RequestBody InterTable interTable) { @GetMapping("/classgen/{id}")
public AjaxResult classGenerator(@PathVariable("id") Long id, HttpServletResponse response) {
try { try {
ServerResult<Integer> serverResult = interTableService.insertInterTable(interTable); ServerResult<byte[]> serverResult = interTableService.generatorCodeClass(id);
if (serverResult.isStart()) { if (serverResult.isStart()) {
genCode(response, serverResult.getData());
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(serverResult.getMsg()); return AjaxResult.error(serverResult.getMsg());
} }
} catch (RuntimeException e) { } catch (RuntimeException | IOException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR); return AjaxResult.error(ReturnConstants.SYS_ERROR);
} }
@ -191,25 +165,99 @@ public class InterTableController extends HcyBaseController {
} }
/** /**
* 删除接口信息 * 生成zip文件
*/ */
@PreAuthorize("@ss.hasPermi('generator:intertable:remove')") private void genCode(HttpServletResponse response, byte[] data) throws IOException {
@Log(title = "接口信息", businessType = BusinessType.DELETE) response.reset();
@DeleteMapping("/{ids}") response.addHeader("Access-Control-Allow-Origin", "*");
public AjaxResult remove(@PathVariable Long[] ids) { response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
try { response.setHeader("Content-Disposition", "attachment; filename=\"hchyun.zip\"");
if (ids.length<0){ response.addHeader("Content-Length", "" + data.length);
return AjaxResult.error("id不能为空!"); response.setContentType("application/octet-stream; charset=UTF-8");
} IOUtils.write(data, response.getOutputStream());
ServerResult<Integer> serverResult = interTableService.deleteInterTableByIds(ids);
if (serverResult.isStart()) {
return AjaxResult.success();
} else {
return AjaxResult.error(serverResult.getMsg());
}
}catch (RuntimeException e){
logger.error(e.getMessage());
return AjaxResult.error(ReturnConstants.SYS_ERROR);
}
} }
// /**
// * 导出接口信息列表
// */
// @PreAuthorize("@ss.hasPermi('generator:intertable:export')")
// @Log(title = "接口信息", businessType = BusinessType.EXPORT)
// @GetMapping("/export")
// public AjaxResult export(InterTable interTable) {
// try {
// ServerResult<List<InterTable>> serverResult = interTableService.selectInterTableList(interTable);
// ExcelUtil<InterTable> util = new ExcelUtil<InterTable>(InterTable. class);
// if (serverResult.isStart()) {
// return util.exportExcel(serverResult.getData(), "intertable");
// } else {
// return AjaxResult.error(serverResult.getMsg());
// }
// } catch (RuntimeException e) {
// logger.error(e.getMessage());
// return AjaxResult.error(ReturnConstants.SYS_ERROR);
// }
// }
// /**
// * 获取接口信息详细信息
// */
// @PreAuthorize("@ss.hasPermi('generator:intertable:query')")
// @GetMapping(value = "/{id}")
// public AjaxResult getInfo(@PathVariable("id") Long id) {
// try {
// ServerResult<InterTable> serverResult = interTableService.selectInterTableById(id);
// if (serverResult.isStart()) {
// return AjaxResult.success(serverResult.getData());
// } else {
// return AjaxResult.info(serverResult.getMsg());
// }
// } catch (RuntimeException e) {
// logger.error(e.getMessage());
// return AjaxResult.error(ReturnConstants.SYS_ERROR);
// }
// }
//
// /**
// * 新增接口信息
// */
// @PreAuthorize("@ss.hasPermi('generator:intertable:add')")
// @Log(title = "接口信息", businessType = BusinessType.INSERT)
// @PostMapping
// public AjaxResult add(@RequestBody InterTable interTable) {
// try {
// ServerResult<Integer> serverResult = interTableService.insertInterTable(interTable);
// if (serverResult.isStart()) {
// return AjaxResult.success();
// } else {
// return AjaxResult.error(serverResult.getMsg());
// }
// } catch (RuntimeException e) {
// logger.error(e.getMessage());
// return AjaxResult.error(ReturnConstants.SYS_ERROR);
// }
// }
//
// /**
// * 删除接口信息
// */
// @PreAuthorize("@ss.hasPermi('generator:intertable:remove')")
// @Log(title = "接口信息", businessType = BusinessType.DELETE)
// @DeleteMapping("/{ids}")
// public AjaxResult remove(@PathVariable Long[] ids) {
// try {
// if (ids.length<0){
// return AjaxResult.error("id不能为空!");
// }
// ServerResult<Integer> serverResult = interTableService.deleteInterTableByIds(ids);
// if (serverResult.isStart()) {
// return AjaxResult.success();
// } else {
// return AjaxResult.error(serverResult.getMsg());
// }
// }catch (RuntimeException e){
// logger.error(e.getMessage());
// return AjaxResult.error(ReturnConstants.SYS_ERROR);
// }
// }
} }

View File

@ -1,6 +1,7 @@
package com.hchyun.generator.service; package com.hchyun.generator.service;
import java.util.Map; import java.util.Map;
import java.util.zip.ZipOutputStream;
import com.hchyun.common.utils.ServerResult; import com.hchyun.common.utils.ServerResult;
import com.hchyun.generator.dto.InterTableDto; import com.hchyun.generator.dto.InterTableDto;
@ -70,7 +71,20 @@ public interface InterTableService
*/ */
ServerResult<Map<String,String>> previewCodeCalss(Long cid); ServerResult<Map<String,String>> previewCodeCalss(Long cid);
/**
* 预览代码()工作台
* @param mid
* @return
*/
ServerResult<Map<String,Object>> previewCodeMoudle(Long mid); ServerResult<Map<String,Object>> previewCodeMoudle(Long mid);
/**
* 生成代码(工作流)
* @param cid
* @return
*/
ServerResult<byte[]> generatorCodeClass(Long cid);
} }

View File

@ -1,10 +1,14 @@
package com.hchyun.generator.service.impl; package com.hchyun.generator.service.impl;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter; import java.io.StringWriter;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.hchyun.common.constant.Constants; import com.hchyun.common.constant.Constants;
import com.hchyun.common.constant.ReturnConstants; import com.hchyun.common.constant.ReturnConstants;
@ -17,6 +21,7 @@ import com.hchyun.generator.entity.Apiclass;
import com.hchyun.generator.entity.Module; import com.hchyun.generator.entity.Module;
import com.hchyun.generator.util.InterTableUtils; import com.hchyun.generator.util.InterTableUtils;
import com.hchyun.generator.util.VelocityInitializer; import com.hchyun.generator.util.VelocityInitializer;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template; import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity; import org.apache.velocity.app.Velocity;
@ -76,16 +81,16 @@ public class InterTableServiceImpl implements InterTableService {
@Override @Override
public ServerResult<Map<String, Object>> selectInterTableList(InterTable interTable) { public ServerResult<Map<String, Object>> selectInterTableList(InterTable interTable) {
try { try {
Map<String,Object> modeMap = new HashMap<String, Object>(); Map<String, Object> modeMap = new HashMap<String, Object>();
if (interTable.getType()==1){ if (interTable.getType() == 1) {
Module module = moduleDao.selectModuleById(interTable.getmId()); Module module = moduleDao.selectModuleById(interTable.getmId());
modeMap.put("info",module); modeMap.put("info", module);
}else if (interTable.getType() == 2){ } else if (interTable.getType() == 2) {
Apiclass apiclass = apiclassDao.selectApiclassById(interTable.getcId()); Apiclass apiclass = apiclassDao.selectApiclassById(interTable.getcId());
modeMap.put("info",apiclass); modeMap.put("info", apiclass);
} }
List<InterTable> interTableList = interTableDao.selectInterTableList(interTable); List<InterTable> interTableList = interTableDao.selectInterTableList(interTable);
modeMap.put("rows",interTableList); modeMap.put("rows", interTableList);
return new ServerResult<Map<String, Object>>(true, modeMap); return new ServerResult<Map<String, Object>>(true, modeMap);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
@ -127,20 +132,23 @@ public class InterTableServiceImpl implements InterTableService {
try { try {
List<InterTable> interTables = interTableDto.getInterTables(); List<InterTable> interTables = interTableDto.getInterTables();
Integer renewal = 0; Integer renewal = 0;
if (interTableDto.getModule() == null){ if (interTableDto.getModule() == null) {
Apiclass apiclass = interTableDto.getApiclass(); Apiclass apiclass = interTableDto.getApiclass();
renewal = apiclassDao.updateApiclass(apiclass); renewal = apiclassDao.updateApiclass(apiclass);
interTableDao.deleteInterTableByClassId(apiclass.getId()); interTableDao.deleteInterTableByClassId(apiclass.getId());
}else if (interTableDto.getApiclass() == null){ } else if (interTableDto.getApiclass() == null) {
Module module = interTableDto.getModule(); Module module = interTableDto.getModule();
renewal = moduleDao.updateModule(module); renewal = moduleDao.updateModule(module);
interTableDao.deleteInterTableByModuleId(module.getId()); interTableDao.deleteInterTableByModuleId(module.getId());
} }
for (int i=0;i<interTables.size();i++){ Integer renewalTables = 0;
interTables.get(i).setCreateBy(SecurityUtils.getUserId()); if (interTables.size() > 0) {
for (int i = 0; i < interTables.size(); i++) {
interTables.get(i).setCreateBy(SecurityUtils.getUserId());
}
renewalTables = interTableDao.insertInterTables(interTables);
} }
Integer renewalTables = interTableDao.insertInterTables(interTables); if (renewalTables > 0 || renewal > 0) {
if (renewalTables > 0&& renewal>0) {
return new ServerResult<Integer>(true, renewalTables); return new ServerResult<Integer>(true, renewalTables);
} else { } else {
return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
@ -196,56 +204,114 @@ public class InterTableServiceImpl implements InterTableService {
@Override @Override
public ServerResult<Map<String, String>> previewCodeCalss(Long cid) { public ServerResult<Map<String, String>> previewCodeCalss(Long cid) {
try { try {
Map<String,String> dataMap = new LinkedHashMap<String, String>(); Map<String, String> dataMap = new LinkedHashMap<String, String>();
Apiclass apiclass = interTableDao.selectInterTableClass(cid); Apiclass apiclass = interTableDao.selectInterTableClass(cid);
if (apiclass == null) {
return new ServerResult<Map<String, String>>(false, ReturnConstants.INTER_NULL);
}
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
VelocityContext context = InterTableUtils.prepareClassContext(apiclass); VelocityContext context = InterTableUtils.prepareClassContext(apiclass);
Map<String,String> templates = InterTableUtils.getTemplateList(2); Map<String, String> templates = InterTableUtils.getTemplateList(2);
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8); Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8);
template.merge(context,sw); template.merge(context, sw);
dataMap.put(getJavaClassName(apiclass.getcName()),sw.toString()); dataMap.put(getJavaClassName(apiclass.getcName()), sw.toString());
sw = new StringWriter(); sw = new StringWriter();
template = Velocity.getTemplate(templates.get("sql"),Constants.UTF8); template = Velocity.getTemplate(templates.get("sql"), Constants.UTF8);
template.merge(context,sw); template.merge(context, sw);
dataMap.put(getSqlName(apiclass.getcName()),sw.toString()); dataMap.put(getSqlName(apiclass.getcName()), sw.toString());
return new ServerResult<Map<String, String>>(true,dataMap); return new ServerResult<Map<String, String>>(true, dataMap);
}catch (RuntimeException e){ } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
return new ServerResult<Map<String,String>>(false,ReturnConstants.DB_EX); return new ServerResult<Map<String, String>>(false, ReturnConstants.DB_EX);
} }
} }
@Override @Override
public ServerResult<Map<String, Object>> previewCodeMoudle(Long mid) { public ServerResult<Map<String, Object>> previewCodeMoudle(Long mid) {
try { try {
Map<String,Object> dataMap = new LinkedHashMap<String,Object>(); Map<String, Object> dataMap = new LinkedHashMap<String, Object>();
List<InterTable> interTableList = interTableDao.selectInterTableModule(mid); List<InterTable> interTableList = interTableDao.selectInterTableModule(mid);
if (interTableList.size() == 0) {
return new ServerResult<Map<String, Object>>(false, "该模块下接口为空,请先创建接口!");
}
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
List<VelocityContext> contextList = InterTableUtils.prepareMoudleContext(interTableList); List<VelocityContext> contextList = InterTableUtils.prepareMoudleContext(interTableList);
Map<String,String> templates = InterTableUtils.getTemplateList(2); Map<String, String> templates = InterTableUtils.getTemplateList(2);
StringWriter sqlsw = new StringWriter(); StringWriter sqlsw = new StringWriter();
Template sqltemplate = Velocity.getTemplate(templates.get("sql"),Constants.UTF8); Template sqltemplate = Velocity.getTemplate(templates.get("sql"), Constants.UTF8);
for (VelocityContext context : contextList){ for (VelocityContext context : contextList) {
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8); Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8);
template.merge(context,sw); template.merge(context, sw);
sqltemplate.merge(context,sqlsw); sqltemplate.merge(context, sqlsw);
dataMap.put(getJavaClassName((String) context.get("ClassName")),sw.toString()); dataMap.put(getJavaClassName((String) context.get("ClassName")), sw.toString());
} }
dataMap.put(getSqlName("module"),sqlsw.toString()); dataMap.put(getSqlName("module"), sqlsw.toString());
return new ServerResult<Map<String,Object>>(true,dataMap); return new ServerResult<Map<String, Object>>(true, dataMap);
}catch (RuntimeException e){ } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
return new ServerResult<Map<String,Object>>(false,ReturnConstants.DB_EX); return new ServerResult<Map<String, Object>>(false, ReturnConstants.DB_EX);
} }
} }
public String getJavaClassName(String cName){ @Override
public ServerResult<byte[]> generatorCodeClass(Long cid) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
Apiclass apiclass = interTableDao.selectInterTableClass(cid);
VelocityInitializer.initVelocity();
VelocityContext context = InterTableUtils.prepareClassContext(apiclass);
Map<String, String> templates = InterTableUtils.getTemplateList(2);
StringWriter sw = new StringWriter();
Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8);
template.merge(context, sw);
zip = genCode(getJavaClassName(apiclass.getcName()),zip,sw);
if (zip == null){
return new ServerResult<byte[]>(false,"代码生成失败!");
}
sw = new StringWriter();
template = Velocity.getTemplate(templates.get("sql"), Constants.UTF8);
template.merge(context, sw);
zip = genCode(getSqlName(apiclass.getcName()),zip,sw);
if (zip == null){
return new ServerResult<byte[]>(false,"代码生成失败!");
}
IOUtils.closeQuietly(zip);
return new ServerResult<byte[]>(true,outputStream.toByteArray());
}catch (RuntimeException e){
logger.error(e.getMessage());
return new ServerResult<byte[]>(false,"代码生成失败!");
}
}
public ZipOutputStream genCode(String className, ZipOutputStream zip,StringWriter sw){
try {
zip.putNextEntry(new ZipEntry(className));
IOUtils.write(sw.toString(),zip,Constants.UTF8);
IOUtils.closeQuietly(sw);
zip.flush();
zip.closeEntry();
return zip;
}catch (IOException e){
logger.error(e.getMessage());
return null;
}
}
public String getJavaClassName(String cName) {
return InterTableUtils.getUpperCase(cName) + "Controller.java"; return InterTableUtils.getUpperCase(cName) + "Controller.java";
} }
public String getSqlName(String cName){
public String getSqlName(String cName) {
return InterTableUtils.getUpperCase(cName) + ".sql"; return InterTableUtils.getUpperCase(cName) + ".sql";
} }
} }