✨ Introducing new features. close #4134 【低代码】表单设计以后直接运行无需下载代码

This commit is contained in:
lbw committed 2022-07-14 18:01:22 +08:00
1 parent c631e665a5
commit ec6a17570c
27 files changed
+1206 -243

No files matched your search

@@ -0,0 +1,58 @@
package com.pig4cloud.pigx.codegen.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.util.SecurityUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* magic 设计的接口鉴权处理逻辑
*
* @author lengleng
* @date 2022/7/12
*/
@ConditionalOnProperty("magic-api.prod")
@Configuration(proxyBeanMethods = false)
public class CustomDynamicApiAuthorizationInterceptor extends OncePerRequestFilter {
private final AntPathMatcher pathMatcher = new AntPathMatcher();
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
String requestURI = request.getRequestURI();
if (!pathMatcher.match("/api/dynamic/**", requestURI)) {
chain.doFilter(request, response);
return;
}
if (SecurityUtils.getAuthentication() == null) {
chain.doFilter(request, response);
return;
}
if (SecurityUtils.getAuthentication().getAuthorities().stream().map(GrantedAuthority::getAuthority)
.anyMatch(requestURI::contains)) {
chain.doFilter(request, response);
return;
}
response.setStatus(HttpStatus.FORBIDDEN.value());
response.getWriter().write(objectMapper.writeValueAsString(R.failed("权限不足,不允许访问")));
}
}
@@ -0,0 +1,83 @@
package com.pig4cloud.pigx.codegen.config;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.ssssssss.magicapi.core.context.MagicUser;
import org.ssssssss.magicapi.core.interceptor.Authorization;
import org.ssssssss.magicapi.core.interceptor.AuthorizationInterceptor;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Enumeration;
/**
* magic 设计器鉴权处理
*
* @author lengleng
* @date 2022/7/10
*
* 自定义权限
*/
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
public class CustomMagicDesignerAuthorizationInterceptor implements AuthorizationInterceptor {
private final static String MAGIC_AUTHORITY = "gen_api_designer";
private final ResourceServerTokenServices tokenServices;
/**
* 配置是否需要登录
*/
@Override
public boolean requireLogin() {
return true;
}
/**
* 是否拥有页面按钮的权限
*/
@Override
public boolean allowVisit(MagicUser magicUser, HttpServletRequest request, Authorization authorization) {
String accessToken = extractHeaderToken(request);
if (StrUtil.isBlank(accessToken)) {
return true;
// throw new AccessDeniedException("权限不足");
}
OAuth2Authentication oAuth2Authentication = tokenServices.loadAuthentication(accessToken);
Collection<GrantedAuthority> authorities = oAuth2Authentication.getAuthorities();
// 查询权限
return authorities.stream().anyMatch(authority -> MAGIC_AUTHORITY.equals(authority.getAuthority()));
}
private String extractHeaderToken(HttpServletRequest request) {
Enumeration<String> headers = request.getHeaders(HttpHeaders.AUTHORIZATION);
while (headers.hasMoreElements()) { // typically there is only one (most servers
// enforce that)
String value = headers.nextElement();
if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) {
String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim();
// Add this here for the auth details later. Would be better to change the
// signature of this method.
request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_TYPE,
value.substring(0, OAuth2AccessToken.BEARER_TYPE.length()).trim());
int commaIndex = authHeaderValue.indexOf(',');
if (commaIndex > 0) {
authHeaderValue = authHeaderValue.substring(0, commaIndex);
}
return authHeaderValue;
}
}
return null;
}
}
@@ -0,0 +1,59 @@
package com.pig4cloud.pigx.codegen.config;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.pig4cloud.pigx.common.core.factory.YamlPropertySourceFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;
import org.ssssssss.magicapi.core.resource.DatabaseResource;
import org.ssssssss.magicapi.core.resource.Resource;
import org.ssssssss.magicapi.datasource.model.MagicDynamicDataSource;
import java.util.List;
/**
* 低代码设计相关
*
* @author lengleng
* @date 2022/5/20
*/
@RequiredArgsConstructor
@Configuration(proxyBeanMethods = false)
@PropertySource(value = "classpath:magic/magic.yml", factory = YamlPropertySourceFactory.class)
public class MagicApiConfiguration implements InitializingBean {
private final MagicDynamicDataSource magicDynamicDataSource;
private final List<DynamicDataSourceProvider> providers;
/**
* 定义 magic-api 存储
* @param jdbcTemplate
* @return 文件存储实现
*/
@Bean
public Resource databaseResource(JdbcTemplate jdbcTemplate) {
return new DatabaseResource(jdbcTemplate, "gen_api_file");
}
/**
* 格式化magic 结果输出
* @return
*/
@Bean
public ResultProvider resultProvider() {
return new RResultProvider();
}
@Override
public void afterPropertiesSet() {
for (DynamicDataSourceProvider provider : providers) {
provider.loadDataSources().forEach(magicDynamicDataSource::add);
}
}
}
@@ -0,0 +1,41 @@
package com.pig4cloud.pigx.codegen.config;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pig4cloud.pigx.common.core.util.R;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;
import org.ssssssss.magicapi.modules.db.model.Page;
import java.util.List;
import java.util.Map;
/**
* 返回R
*
* @author lengleng
* @date 2022/7/9
*/
public class RResultProvider implements ResultProvider {
@Override
public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
return R.ok().setData(data).setMsg(message);
}
/**
* 定义分页返回结果,该项会被封装在Json结果内, 此方法可以不覆盖,默认返回PageResult
*/
@Override
public Object buildPageResult(RequestEntity requestEntity, Page page, long total, List<Map<String, Object>> data) {
IPage result = new com.baomidou.mybatisplus.extension.plugins.pagination.Page();
result.setTotal(total);
result.setRecords(data);
return R.ok(result);
}
@Override
public Object buildException(RequestEntity requestEntity, Throwable throwable) {
return R.failed(throwable.getLocalizedMessage());
}
}
@@ -22,6 +22,7 @@ import com.pig4cloud.pigx.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pigx.codegen.service.GenDatasourceConfService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import com.pig4cloud.pigx.common.xss.core.XssCleanIgnore;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
@@ -55,6 +56,7 @@ public class GenDsConfController {
* @return
*/
@GetMapping("/list")
@Inner(value = false)
public R list() {
return R.ok(datasourceConfService.list());
}
@@ -0,0 +1,41 @@
package com.pig4cloud.pigx.codegen.controller;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.GenDynamicService;
import com.pig4cloud.pigx.codegen.util.SqlDto;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.LinkedHashMap;
import java.util.List;
/**
* @author lengleng
* @date 2022/7/9
*
* 动态数据 无代码
*/
@RestController
@Inner(value = false)
@RequiredArgsConstructor
@RequestMapping("/dynamic")
@Api(value = "dynamic", tags = "无代码管理")
public class GenDynamicController {
private final GenDynamicService dynamicService;
@GetMapping("/gen")
public R genCode(GenConfig genConfig) {
return R.ok(dynamicService.run(genConfig));
}
@PostMapping("/dynamic-query")
public R dynamicQuery(@RequestBody SqlDto sqlDto) {
List<LinkedHashMap<String, Object>> linkedHashMaps = dynamicService.dynamicQuery(sqlDto);
return R.ok(linkedHashMaps);
}
}
@@ -17,12 +17,14 @@
package com.pig4cloud.pigx.codegen.controller;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.service.GenFormConfService;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import com.pig4cloud.pigx.common.security.annotation.Inner;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
@@ -73,6 +75,7 @@ public class GenFormConfController {
* @return R
*/
@ApiOperation(value = "通过tableName查询表单信息")
@Inner(value = false)
@GetMapping("/info")
public R form(String dsName, String tableName) {
return R.ok(genRecordService.getForm(dsName, tableName));
@@ -88,6 +91,7 @@ public class GenFormConfController {
@PostMapping
@PreAuthorize("@pms.hasPermission('gen_form_add')")
public R save(@RequestBody GenFormConf formConf) {
formConf.setFormInfo(JSONUtil.toJsonPrettyStr(formConf.getFormInfo()));
return R.ok(genRecordService.save(formConf));
}
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.mapper;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.LinkedHashMap;
import java.util.List;
/**
* 动态查询
*
* @author lengleng
* @date 2022-07-09
*/
@Mapper
public interface GenDynamicMapper {
@InterceptorIgnore(tenantLine = "true")
List<LinkedHashMap<String, Object>> dynamicQuerySql(@Param("value") String sq);
}
@@ -1,21 +1,4 @@
/*
* Copyright (c) 2018-2025, lengleng All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the pig4cloud.com developer nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* Author: lengleng (wangiegie@gmail.com)
*/
package com.pig4cloud.pigx.codegen.util;
package com.pig4cloud.pigx.codegen.service;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
@@ -26,13 +9,10 @@ import com.pig4cloud.pigx.codegen.entity.*;
import com.pig4cloud.pigx.codegen.mapper.GenDatasourceConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import com.pig4cloud.pigx.common.core.constant.enums.StyleTypeEnum;
import com.pig4cloud.pigx.common.core.exception.CheckedException;
import com.pig4cloud.pigx.common.core.util.SpringContextHolder;
import com.pig4cloud.pigx.common.datasource.util.DsJdbcUrlEnum;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
@@ -46,7 +26,6 @@ import org.apache.velocity.tools.generic.MathTool;
import org.springframework.context.ApplicationContext;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
@@ -54,74 +33,77 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* 代码生成器 工具类
* 生成代码抽象
*
* @author lengleng
* @date 2018-07-30
* @date 2022/7/11
*/
@Slf4j
@UtilityClass
public class GenUtils {
public interface GenCodeService {
public final String CRUD_PREFIX = "export const tableOption =";
default Map<String, String> gen(GenConfig genConfig, Map<String, String> table, List<Map<String, String>> columns,
ZipOutputStream zip, GenFormConf formConf) {
private final String ENTITY_JAVA_VM = "Entity.java.vm";
// 构建表实体
TableEntity tableEntity = buildTableEntity(genConfig, table);
private final String MAPPER_JAVA_VM = "Mapper.java.vm";
// 处理列相关
buildColumnEntity(tableEntity, columns);
private final String SERVICE_JAVA_VM = "Service.java.vm";
// 模板入参
Map<String, Object> tempModel = buildTempModel(tableEntity, genConfig);
private final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm";
private final String CONTROLLER_JAVA_VM = "Controller.java.vm";
private final String MAPPER_XML_VM = "Mapper.xml.vm";
private final String MENU_SQL_VM = "menu.sql.vm";
private final String AVUE_INDEX_VUE_VM = "avue/index.vue.vm";
private final String ELE_INDEX_VUE_VM = "element/index.vue.vm";
private final String ELE_ADD_UPDATE_VUE_VM = "element/form.vue.vm";
private final String AVUE_API_JS_VM = "avue/api.js.vm";
private final String AVUE_CRUD_JS_VM = "avue/crud.js.vm";
private final String UVIEW_API_JS_VM = "uview/api.js.vm";
private final String UVIEW_FORM_VUE_VM = "uview/form.vue.vm";
private final String UVIEW_INDEX_VUE_VM = "uview/index.vue.vm";
private final String UVIEW_PAGE_JSON_VM = "uview/page.json.vm";
return renderData(genConfig, zip, tableEntity, tempModel, formConf);
}
/**
* 配置
* @param config
* @return
* 获取文件名
*/
private List<String> getTemplates(GenConfig config) {
default String getFileName(String template, String className, String packageName, String moduleName) {
String packagePath = CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main"
+ File.separator + "java" + File.separator;
if (StringUtils.isNotBlank(packageName)) {
packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
}
if (template.contains("Entity.java.vm")) {
return packagePath + "entity" + File.separator + className + ".java";
}
if (template.contains("Mapper.java.vm")) {
return packagePath + "mapper" + File.separator + className + "Mapper.java";
}
if (template.contains("Service.java.vm")) {
return packagePath + "service" + File.separator + className + "Service.java";
}
if (template.contains("ServiceImpl.java.vm")) {
return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
}
if (template.contains("Controller.java.vm")) {
return packagePath + "controller" + File.separator + className + "Controller.java";
}
if (template.contains("Mapper.xml.vm")) {
return CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator
+ "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml";
}
if (template.contains("menu.sql.vm")) {
return className.toLowerCase() + "_menu.sql";
}
return null;
}
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
default List<String> getTemplates(GenConfig config) {
List<String> templates = new ArrayList<>();
if (StyleTypeEnum.AVUE.getStyle().equals(config.getStyle())) {
templates.add("template/avue/index.vue.vm");
templates.add("template/avue/crud.js.vm");
templates.add("template/avue/api.js.vm");
}
else if (StyleTypeEnum.ELEMENT.getStyle().equals(config.getStyle())) {
templates.add("template/element/index.vue.vm");
templates.add("template/element/form.vue.vm");
templates.add("template/avue/api.js.vm");
}
else {
templates.add("template/uview/index.vue.vm");
templates.add("template/uview/form.vue.vm");
templates.add("template/uview/api.js.vm");
templates.add("template/uview/page.json.vm");
}
templates.add("template/Entity.java.vm");
templates.add("template/Mapper.java.vm");
templates.add("template/Mapper.xml.vm");
@@ -129,20 +111,19 @@ public class GenUtils {
templates.add("template/ServiceImpl.java.vm");
templates.add("template/Controller.java.vm");
templates.add("template/menu.sql.vm");
return templates;
}
/**
* 生成代码
* 构建 TableEntity
* @param genConfig 用户输入相关
* @param table 表元信息
* @param columns 列元信息
* @param zip 输出zip流
* @param formConf 表单设计
* @return
*/
@SneakyThrows
public Map<String, String> generatorCode(GenConfig genConfig, Map<String, String> table,
List<Map<String, String>> columns, ZipOutputStream zip, GenFormConf formConf) {
// 配置信息
Configuration config = getConfig();
boolean hasBigDecimal = false;
default TableEntity buildTableEntity(GenConfig genConfig, Map<String, String> table) {
// 表信息
TableEntity tableEntity = new TableEntity();
tableEntity.setTableName(table.get("tableName"));
@@ -161,15 +142,23 @@ public class GenUtils {
tablePrefix = genConfig.getTablePrefix();
}
else {
tablePrefix = config.getString("tablePrefix");
tablePrefix = getConfig().getString("tablePrefix");
}
// 表名转换成Java类名
String className = tableToJava(tableEntity.getTableName(), tablePrefix);
tableEntity.setCaseClassName(className);
tableEntity.setLowerClassName(StringUtils.uncapitalize(className));
// 获取需要在swagger文档中隐藏的属性字段
List<Object> hiddenColumns = config.getList("hiddenColumn");
return tableEntity;
}
/**
* 构建 ColumnEntity
* @param columns 列元信息
* @return
*/
default void buildColumnEntity(TableEntity tableEntity, List<Map<String, String>> columns) {
List<Object> hiddenColumns = getConfig().getList("hiddenColumn");
// 列信息
List<ColumnEntity> columnList = new ArrayList<>();
for (Map<String, String> column : columns) {
@@ -202,11 +191,8 @@ public class GenUtils {
// 列的数据类型,转换成Java类型
String dataType = StrUtil.subBefore(columnEntity.getDataType(), "(", false);
String attrType = config.getString(dataType, "unknowType");
String attrType = getConfig().getString(dataType, "unknowType");
columnEntity.setAttrType(attrType);
if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
hasBigDecimal = true;
}
// 是否主键
if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) {
tableEntity.setPk(columnEntity);
@@ -214,15 +200,14 @@ public class GenUtils {
columnList.add(columnEntity);
}
tableEntity.setColumns(columnList);
}
// 没主键,则第一个字段为主键
if (tableEntity.getPk() == null) {
tableEntity.setPk(tableEntity.getColumns().get(0));
}
default Map<String, Object> buildTempModel(TableEntity tableEntity, GenConfig genConfig) {
// 封装模板数据
Map<String, Object> map = new HashMap<>(16);
map.put("dsName", genConfig.getDsName());
map.put("dbType", tableEntity.getDbType());
map.put("tableName", tableEntity.getTableName());
map.put("pk", tableEntity.getPk());
@@ -230,7 +215,6 @@ public class GenUtils {
map.put("classname", tableEntity.getLowerClassName());
map.put("pathName", tableEntity.getLowerClassName().toLowerCase());
map.put("columns", tableEntity.getColumns());
map.put("hasBigDecimal", hasBigDecimal);
map.put("datetime", DateUtil.now());
if (StrUtil.isNotBlank(genConfig.getComments())) {
@@ -244,14 +228,14 @@ public class GenUtils {
map.put("author", genConfig.getAuthor());
}
else {
map.put("author", config.getString("author"));
map.put("author", getConfig().getString("author"));
}
if (StrUtil.isNotBlank(genConfig.getModuleName())) {
map.put("moduleName", genConfig.getModuleName());
}
else {
map.put("moduleName", config.getString("moduleName"));
map.put("moduleName", getConfig().getString("moduleName"));
}
if (StrUtil.isNotBlank(genConfig.getPackageName())) {
@@ -259,26 +243,26 @@ public class GenUtils {
map.put("mainPath", genConfig.getPackageName());
}
else {
map.put("package", config.getString("package"));
map.put("mainPath", config.getString("mainPath"));
map.put("package", getConfig().getString("package"));
map.put("mainPath", getConfig().getString("mainPath"));
}
// 渲染数据
return renderData(genConfig, zip, formConf, tableEntity, map);
return map;
}
/**
* 渲染数据
* @param genConfig 配置信息
* @param zip 流 (为空,直接返回Map)
* @param formConf 表单信息
* @param tableEntity 表基本信息
* @param map 模板参数
* @return map key-filename value-contents
* @throws IOException
* @param genConfig 用户输入相关
* @param zip 输出zip流
* @param tableEntity 表格实体
* @param map 参数集合
* @param formConf 表单设计
* @return
*/
private Map<String, String> renderData(GenConfig genConfig, ZipOutputStream zip, GenFormConf formConf,
TableEntity tableEntity, Map<String, Object> map) throws IOException {
@SneakyThrows
default Map<String, String> renderData(GenConfig genConfig, ZipOutputStream zip, TableEntity tableEntity,
Map<String, Object> map, GenFormConf formConf) {
// 设置velocity资源加载器
Properties prop = new Properties();
prop.put("resource.loader.file.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
@@ -293,23 +277,6 @@ public class GenUtils {
Map<String, String> resultMap = new LinkedHashMap<>(8);
for (String template : templates) {
// 如果是crud
if (template.contains(AVUE_CRUD_JS_VM) && formConf != null) {
String fileName = getFileName(template, tableEntity.getCaseClassName(), map.get("package").toString(),
map.get("moduleName").toString());
String contents = CRUD_PREFIX + formConf.getFormInfo();
if (zip != null) {
zip.putNextEntry(new ZipEntry(Objects.requireNonNull(fileName)));
IoUtil.write(zip, StandardCharsets.UTF_8, false, contents);
zip.closeEntry();
}
resultMap.put(template, contents);
continue;
}
// 渲染模板
StringWriter sw = new StringWriter();
Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8);
@@ -320,10 +287,14 @@ public class GenUtils {
map.get("moduleName").toString());
if (zip != null) {
zip.putNextEntry(new ZipEntry(Objects.requireNonNull(fileName)));
IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString());
IoUtil.close(sw);
zip.closeEntry();
try {
zip.putNextEntry(new ZipEntry(Objects.requireNonNull(fileName)));
IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString());
IoUtil.close(sw);
}
catch (Exception e) {
}
}
resultMap.put(template, sw.toString());
}
@@ -334,14 +305,14 @@ public class GenUtils {
/**
* 列名转换成Java属性名
*/
public String columnToJava(String columnName) {
default String columnToJava(String columnName) {
return WordUtils.capitalizeFully(columnName, new char[] { '_' }).replace("_", "");
}
/**
* 表名转换成Java类名
*/
private String tableToJava(String tableName, String tablePrefix) {
default String tableToJava(String tableName, String tablePrefix) {
if (StringUtils.isNotBlank(tablePrefix)) {
tableName = tableName.replaceFirst(tablePrefix, "");
}
@@ -351,7 +322,7 @@ public class GenUtils {
/**
* 获取配置信息
*/
public Configuration getConfig() {
default Configuration getConfig() {
try {
return new PropertiesConfiguration("generator.properties");
}
@@ -360,97 +331,12 @@ public class GenUtils {
}
}
/**
* 获取文件名
*/
private String getFileName(String template, String className, String packageName, String moduleName) {
String packagePath = CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main"
+ File.separator + "java" + File.separator;
if (StringUtils.isNotBlank(packageName)) {
packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
}
if (template.contains(ENTITY_JAVA_VM)) {
return packagePath + "entity" + File.separator + className + ".java";
}
if (template.contains(MAPPER_JAVA_VM)) {
return packagePath + "mapper" + File.separator + className + "Mapper.java";
}
if (template.contains(SERVICE_JAVA_VM)) {
return packagePath + "service" + File.separator + className + "Service.java";
}
if (template.contains(SERVICE_IMPL_JAVA_VM)) {
return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
}
if (template.contains(CONTROLLER_JAVA_VM)) {
return packagePath + "controller" + File.separator + className + "Controller.java";
}
if (template.contains(MAPPER_XML_VM)) {
return CommonConstants.BACK_END_PROJECT + File.separator + "src" + File.separator + "main" + File.separator
+ "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml";
}
if (template.contains(MENU_SQL_VM)) {
return className.toLowerCase() + "_menu.sql";
}
if (template.contains(AVUE_INDEX_VUE_VM) || template.contains(ELE_INDEX_VUE_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ "index.vue";
}
if (template.contains(AVUE_API_JS_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" + File.separator
+ className.toLowerCase() + ".js";
}
if (template.contains(AVUE_CRUD_JS_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "const"
+ File.separator + "crud" + File.separator + className.toLowerCase() + ".js";
}
if (template.contains(ELE_ADD_UPDATE_VUE_VM)) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ className.toLowerCase() + "-form.vue";
}
if (template.contains(UVIEW_INDEX_VUE_VM)) {
return CommonConstants.UNI_END_PROJECT + File.separator + "pages" + File.separator + moduleName
+ File.separator + className.toLowerCase() + File.separator + className.toLowerCase()
+ "-index.vue";
}
if (template.contains(UVIEW_FORM_VUE_VM)) {
return CommonConstants.UNI_END_PROJECT + File.separator + "pages" + File.separator + moduleName
+ File.separator + className.toLowerCase() + File.separator + className.toLowerCase() + "-form.vue";
}
if (template.contains(UVIEW_API_JS_VM)) {
return CommonConstants.UNI_END_PROJECT + File.separator + "common" + File.separator
+ className.toLowerCase() + ".api.js";
}
if (template.contains(UVIEW_PAGE_JSON_VM)) {
return className.toLowerCase() + ".page.json";
}
return null;
}
/**
* 根据目标数据源名称动态匹配Mapper
* @param dsName
* @return
*/
public GeneratorMapper getMapper(String dsName) {
default GeneratorMapper getMapper(String dsName) {
// 获取目标数据源数据库类型
GenDatasourceConfMapper datasourceConfMapper = SpringContextHolder.getBean(GenDatasourceConfMapper.class);
GenDatasourceConf datasourceConf = datasourceConfMapper
@@ -0,0 +1,29 @@
package com.pig4cloud.pigx.codegen.service;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.util.SqlDto;
import java.util.LinkedHashMap;
import java.util.List;
/**
* @author lengleng
* @date 2022/7/9
*/
public interface GenDynamicService {
/**
* 执行代码
* @param genConfig 请求参数
* @return
*/
Object run(GenConfig genConfig);
/**
* 动态查询
* @param sqlDto 请求参数
* @return ListMap
*/
List<LinkedHashMap<String, Object>> dynamicQuery(SqlDto sqlDto);
}
@@ -0,0 +1,140 @@
package com.pig4cloud.pigx.codegen.service.impl;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.mapper.GenDynamicMapper;
import com.pig4cloud.pigx.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.codegen.service.GenDynamicService;
import com.pig4cloud.pigx.codegen.util.SqlDto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.service.MagicResourceService;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 动态无代码实现类
*
* @author lengleng
* @date 2022/7/9
*/
@Service
@RequiredArgsConstructor
public class GenDynamicServiceImpl implements GenDynamicService {
private final MagicResourceService magicResourceService;
private final GenFormConfMapper genFormConfMapper;
private final GenDynamicMapper dynamicMapper;
private final GenCodeService magic;
/**
* 动态查询
* @param sqlDto 请求参数
* @return ListMap
*/
@Override
public List<LinkedHashMap<String, Object>> dynamicQuery(SqlDto sqlDto) {
DynamicDataSourceContextHolder.clear();
// 切换线程, 注意清空避免污染
DynamicDataSourceContextHolder.push(sqlDto.getDsName());
List<LinkedHashMap<String, Object>> linkedHashMaps = dynamicMapper.dynamicQuerySql(sqlDto.getSql());
DynamicDataSourceContextHolder.clear();
return linkedHashMaps;
}
@Override
public Map<String, String> run(GenConfig genConfig) {
// 根据tableName 查询最新的表单配置
List<GenFormConf> formConfList = genFormConfMapper.selectList(Wrappers.<GenFormConf>lambdaQuery()
.eq(GenFormConf::getTableName, genConfig.getTableName()).orderByDesc(GenFormConf::getCreateTime));
String tableNames = genConfig.getTableName();
String dsName = genConfig.getDsName();
GeneratorMapper mapper = magic.getMapper(genConfig.getDsName());
Map<String, String> templates = new HashMap<>();
for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
// 查询表信息
Map<String, String> table = mapper.queryTable(tableName, dsName);
// 查询列信息
List<Map<String, String>> columns = mapper.selectMapTableColumn(tableName, dsName);
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
templates = magic.gen(genConfig, table, columns, null, formConfList.get(0));
}
else {
templates = magic.gen(genConfig, table, columns, null, null);
}
// 分组
Group group = new Group();
String id = dsName + "_" + StrUtil.toSymbolCase(tableName, CharUtil.UNDERLINE);
group.setId(id);
group.setParentId("0");
group.setName(id);
group.setType("api");
group.setPath("/api/dynamic/" + dsName + "/" + StrUtil.toSymbolCase(tableName, CharUtil.UNDERLINE));
magicResourceService.saveGroup(group);
ApiInfo apiInfo = new ApiInfo();
apiInfo.setId(id + "_query");
String script = templates.get("template/magic/query.magic.vm");
apiInfo.setScript(script);
apiInfo.setName("分页");
apiInfo.setPath("/list");
apiInfo.setMethod("post");
apiInfo.setGroupId(id);
magicResourceService.saveFile(apiInfo);
ApiInfo delApiInfo = new ApiInfo();
delApiInfo.setId(id + "_del");
String delScript = templates.get("template/magic/del.magic.vm");
delApiInfo.setScript(delScript);
delApiInfo.setName("删除");
delApiInfo.setPath("/delete");
delApiInfo.setMethod("delete");
delApiInfo.setGroupId(id);
magicResourceService.saveFile(delApiInfo);
ApiInfo addApiInfo = new ApiInfo();
addApiInfo.setId(id + "_add");
String addScript = templates.get("template/magic/add.magic.vm");
addApiInfo.setScript(addScript);
addApiInfo.setName("添加");
addApiInfo.setPath("/save");
addApiInfo.setMethod("post");
addApiInfo.setGroupId(id);
magicResourceService.saveFile(addApiInfo);
ApiInfo updateApiInfo = new ApiInfo();
updateApiInfo.setId(id + "_update");
String updateScript = templates.get("template/magic/update.magic.vm");
updateApiInfo.setScript(updateScript);
updateApiInfo.setName("修改");
updateApiInfo.setPath("/update");
updateApiInfo.setMethod("put");
updateApiInfo.setGroupId(id);
magicResourceService.saveFile(updateApiInfo);
}
return templates;
}
}
@@ -24,8 +24,8 @@ import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.codegen.service.GenFormConfService;
import com.pig4cloud.pigx.codegen.util.GenUtils;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
@@ -50,6 +50,8 @@ import java.util.Properties;
@AllArgsConstructor
public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFormConf> implements GenFormConfService {
private final GenCodeService avue;
/**
* 1. 根据数据源、表名称,查询已配置表单信息 2. 不存在调用模板生成
* @param dsName 数据源ID
@@ -66,7 +68,7 @@ public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFo
return form.getFormInfo();
}
GeneratorMapper mapper = GenUtils.getMapper(dsName);
GeneratorMapper mapper = avue.getMapper(dsName);
List<ColumnEntity> columns = mapper.selectTableColumn(tableName, dsName);
// 设置velocity资源加载器
Properties prop = new Properties();
@@ -78,7 +80,7 @@ public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFo
List<ColumnEntity> columnList = new ArrayList<>();
for (ColumnEntity column : columns) {
ColumnEntity columnEntity = new ColumnEntity();
columnEntity.setLowerAttrName(StringUtils.uncapitalize(GenUtils.columnToJava(column.getColumnName())));
columnEntity.setLowerAttrName(StringUtils.uncapitalize(avue.columnToJava(column.getColumnName())));
// 判断注释是否为空
if (StrUtil.isNotBlank(column.getComments())) {
@@ -92,7 +94,7 @@ public class GenFormConfServiceImpl extends ServiceImpl<GenFormConfMapper, GenFo
context.put("columns", columnList);
StringWriter writer = new StringWriter();
template.merge(context, writer);
return StrUtil.trim(StrUtil.removePrefix(writer.toString(), GenUtils.CRUD_PREFIX));
return StrUtil.trim(StrUtil.removePrefix(writer.toString(), "export const tableOption ="));
}
}
@@ -6,8 +6,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pigx.codegen.entity.ColumnEntity;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.codegen.service.GenTableColumnService;
import com.pig4cloud.pigx.codegen.util.GenUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.lang.StringUtils;
@@ -23,9 +23,11 @@ import org.springframework.stereotype.Service;
@RequiredArgsConstructor
public class GenTableColumnServiceImpl implements GenTableColumnService {
private final GenCodeService element;
@Override
public IPage<ColumnEntity> listTable(Page page, GenConfig genConfig) {
GeneratorMapper mapper = GenUtils.getMapper(genConfig.getDsName());
GeneratorMapper mapper = element.getMapper(genConfig.getDsName());
// 关闭sql 优化
page.setOptimizeCountSql(false);
@@ -33,12 +35,12 @@ public class GenTableColumnServiceImpl implements GenTableColumnService {
genConfig.getDsName());
// 处理 数据库类型和 Java 类型关系
Configuration config = GenUtils.getConfig();
Configuration config = element.getConfig();
columnPage.getRecords().forEach(column -> {
// 只保留 ()之前部分,例如 timestamp(6) -> timestamp
String dataType = StrUtil.subBefore(column.getDataType(), "(", false);
String attrType = config.getString(dataType, "unknowType");
column.setLowerAttrName(StringUtils.uncapitalize(GenUtils.columnToJava(column.getColumnName())));
column.setLowerAttrName(StringUtils.uncapitalize(element.columnToJava(column.getColumnName())));
column.setJavaType(attrType);
});
return columnPage;
@@ -29,8 +29,9 @@ import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.mapper.GenFormConfMapper;
import com.pig4cloud.pigx.codegen.mapper.GeneratorMapper;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.codegen.service.GeneratorService;
import com.pig4cloud.pigx.codegen.util.GenUtils;
import com.pig4cloud.pigx.common.core.constant.enums.StyleTypeEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@@ -51,6 +52,10 @@ public class GeneratorServiceImpl implements GeneratorService {
private final GenFormConfMapper genFormConfMapper;
private final GenCodeService element;
private final Map<String, GenCodeService> genCodeServiceMap;
/**
* 分页查询表
* @param tableName 查询条件
@@ -59,7 +64,7 @@ public class GeneratorServiceImpl implements GeneratorService {
*/
@Override
public IPage<Map<String, Object>> getPage(Page page, String tableName, String dsName) {
GeneratorMapper mapper = GenUtils.getMapper(dsName);
GeneratorMapper mapper = element.getMapper(dsName);
// 手动切换数据源
DynamicDataSourceContextHolder.push(dsName);
@@ -76,7 +81,9 @@ public class GeneratorServiceImpl implements GeneratorService {
String tableNames = genConfig.getTableName();
String dsName = genConfig.getDsName();
GeneratorMapper mapper = GenUtils.getMapper(genConfig.getDsName());
GenCodeService genCodeService = genCodeServiceMap.get(StyleTypeEnum.getDecs(genConfig.getStyle()));
GeneratorMapper mapper = genCodeService.getMapper(genConfig.getDsName());
for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
// 查询表信息
@@ -85,10 +92,10 @@ public class GeneratorServiceImpl implements GeneratorService {
List<Map<String, String>> columns = mapper.selectMapTableColumn(tableName, dsName);
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
return GenUtils.generatorCode(genConfig, table, columns, null, formConfList.get(0));
return genCodeService.gen(genConfig, table, columns, null, formConfList.get(0));
}
else {
return GenUtils.generatorCode(genConfig, table, columns, null, null);
return genCodeService.gen(genConfig, table, columns, null, null);
}
}
return MapUtil.empty();
@@ -110,7 +117,9 @@ public class GeneratorServiceImpl implements GeneratorService {
String tableNames = genConfig.getTableName();
String dsName = genConfig.getDsName();
GeneratorMapper mapper = GenUtils.getMapper(dsName);
GenCodeService genCodeService = genCodeServiceMap.get(StyleTypeEnum.getDecs(genConfig.getStyle()));
GeneratorMapper mapper = genCodeService.getMapper(dsName);
for (String tableName : StrUtil.split(tableNames, StrUtil.DASHED)) {
// 查询表信息
@@ -119,10 +128,10 @@ public class GeneratorServiceImpl implements GeneratorService {
List<Map<String, String>> columns = mapper.selectMapTableColumn(tableName, dsName);
// 生成代码
if (CollUtil.isNotEmpty(formConfList)) {
GenUtils.generatorCode(genConfig, table, columns, zip, formConfList.get(0));
genCodeService.gen(genConfig, table, columns, zip, formConfList.get(0));
}
else {
GenUtils.generatorCode(genConfig, table, columns, zip, null);
genCodeService.gen(genConfig, table, columns, zip, null);
}
}
IoUtil.close(zip);
@@ -0,0 +1,107 @@
package com.pig4cloud.pigx.codegen.service.impl.temp;
import cn.hutool.core.io.IoUtil;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.entity.GenFormConf;
import com.pig4cloud.pigx.codegen.entity.TableEntity;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* avue代码实现
*
* @author lengleng
* @date 2022/7/11
*/
@Service("avue")
public class AvueGenCodeServiceImpl implements GenCodeService {
private final String CRUD_PREFIX = "export const tableOption =";
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
@Override
public List<String> getTemplates(GenConfig config) {
List<String> templates = GenCodeService.super.getTemplates(config);
templates.add("template/avue/index.vue.vm");
templates.add("template/avue/crud.js.vm");
templates.add("template/avue/api.js.vm");
return templates;
}
/**
* 获取文件名
* @param template
* @param className
* @param packageName
* @param moduleName
*/
@Override
public String getFileName(String template, String className, String packageName, String moduleName) {
if (template.contains("avue/index.vue.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ "index.vue";
}
if (template.contains("avue/api.js.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" + File.separator
+ className.toLowerCase() + ".js";
}
if (template.contains("avue/crud.js.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "const"
+ File.separator + "crud" + File.separator + className.toLowerCase() + ".js";
}
return GenCodeService.super.getFileName(template, className, packageName, moduleName);
}
/**
* 渲染数据
* @param genConfig 用户输入相关
* @param zip 输出zip流
* @param tableEntity 表格实体
* @param map 参数集合
* @param formConf 表单设计
* @return
*/
@SneakyThrows
public Map<String, String> renderData(GenConfig genConfig, ZipOutputStream zip, TableEntity tableEntity,
Map<String, Object> map, GenFormConf formConf) {
Map<String, String> resultMap = new HashMap<>();
if (Objects.nonNull(formConf)) {
// 存在 curd 存在设计好的JSON 则使用Json 覆盖
String crudTempName = "template/avue/crud.js.vm";
String fileName = getFileName(crudTempName, tableEntity.getCaseClassName(), map.get("package").toString(),
map.get("moduleName").toString());
String contents = CRUD_PREFIX + formConf.getFormInfo();
if (zip != null) {
zip.putNextEntry(new ZipEntry(Objects.requireNonNull(fileName)));
IoUtil.write(zip, StandardCharsets.UTF_8, false, contents);
}
resultMap.putAll(GenCodeService.super.renderData(genConfig, zip, tableEntity, map, formConf));
resultMap.put(crudTempName, contents);
return resultMap;
}
return GenCodeService.super.renderData(genConfig, zip, tableEntity, map, formConf);
}
}
@@ -0,0 +1,58 @@
package com.pig4cloud.pigx.codegen.service.impl.temp;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
/**
* element代码实现
*
* @author lengleng
* @date 2022/7/11
*/
@Service("element")
public class EleGenCodeServiceImpl implements GenCodeService {
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
@Override
public List<String> getTemplates(GenConfig config) {
List<String> templates = GenCodeService.super.getTemplates(config);
templates.add("template/element/index.vue.vm");
templates.add("template/element/form.vue.vm");
templates.add("template/avue/api.js.vm");
return templates;
}
/**
* 获取文件名
* @param template
* @param className
* @param packageName
* @param moduleName
*/
@Override
public String getFileName(String template, String className, String packageName, String moduleName) {
if (template.contains("element/index.vue.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ "index.vue";
}
if (template.contains("element/form.vue.vm")) {
return CommonConstants.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
+ className.toLowerCase() + "-form.vue";
}
return GenCodeService.super.getFileName(template, className, packageName, moduleName);
}
}
@@ -0,0 +1,36 @@
package com.pig4cloud.pigx.codegen.service.impl.temp;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* magic代码实现
*
* @author lengleng
* @date 2022/7/11
*/
@Service("magic")
public class MagicGenCodeServiceImpl implements GenCodeService {
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
@Override
public List<String> getTemplates(GenConfig config) {
List<String> templates = GenCodeService.super.getTemplates(config);
templates.add("template/avue/index.vue.vm");
templates.add("template/avue/crud.js.vm");
templates.add("template/avue/api.js.vm");
templates.add("template/magic/query.magic.vm");
templates.add("template/magic/del.magic.vm");
templates.add("template/magic/add.magic.vm");
templates.add("template/magic/update.magic.vm");
return templates;
}
}
@@ -0,0 +1,67 @@
package com.pig4cloud.pigx.codegen.service.impl.temp;
import com.pig4cloud.pigx.codegen.entity.GenConfig;
import com.pig4cloud.pigx.codegen.service.GenCodeService;
import com.pig4cloud.pigx.common.core.constant.CommonConstants;
import org.springframework.stereotype.Service;
import java.io.File;
import java.util.List;
/**
* uview代码实现
*
* @author lengleng
* @date 2022/7/11
*/
@Service("uview")
public class UviewGenCodeServiceImpl implements GenCodeService {
/**
* 注入支持的模板列表
* @param config 用户输入
* @return ListString
*/
@Override
public List<String> getTemplates(GenConfig config) {
List<String> templates = GenCodeService.super.getTemplates(config);
templates.add("template/uview/index.vue.vm");
templates.add("template/uview/form.vue.vm");
templates.add("template/uview/api.js.vm");
templates.add("template/uview/page.json.vm");
return templates;
}
/**
* 获取文件名
* @param template
* @param className
* @param packageName
* @param moduleName
*/
@Override
public String getFileName(String template, String className, String packageName, String moduleName) {
if (template.contains("uview/index.vue.vm")) {
return CommonConstants.UNI_END_PROJECT + File.separator + "pages" + File.separator + moduleName
+ File.separator + className.toLowerCase() + File.separator + className.toLowerCase()
+ "-index.vue";
}
if (template.contains("uview/form.vue.vm")) {
return CommonConstants.UNI_END_PROJECT + File.separator + "pages" + File.separator + moduleName
+ File.separator + className.toLowerCase() + File.separator + className.toLowerCase() + "-form.vue";
}
if (template.contains("uview/api.js.vm")) {
return CommonConstants.UNI_END_PROJECT + File.separator + "common" + File.separator
+ className.toLowerCase() + ".api.js";
}
if (template.contains("uview/page.json.vm")) {
return className.toLowerCase() + ".page.json";
}
return GenCodeService.super.getFileName(template, className, packageName, moduleName);
}
}
@@ -0,0 +1,22 @@
package com.pig4cloud.pigx.codegen.util;
import lombok.Data;
/**
* @author lengleng
* @date 2022/5/2
*/
@Data
public class SqlDto {
/**
* 数据源ID
*/
private String dsName;
/**
* sql脚本
*/
private String sql;
}
@@ -0,0 +1,212 @@
var MAGIC_EDITOR_CONFIG = {
title: '接口低代码设计平台',
theme: 'dark',
defaultExpand: true,
checkUpdate: true,
jdbcDrivers: ['com.mysql.cj.jdbc.Driver', 'com.mysql.jdbc.Driver', 'oracle.jdbc.driver.OracleDriver', 'org.postgresql.Driver', 'com.microsoft.sqlserver.jdbc.SQLServerDriver'],
blockClose: true, // 是否阻止离开页面
autoSave: true,
decorationTimeout: 10000,
logMaxRows: Infinity,
editorFontFamily: 'JetBrainsMono, Consolas, "Courier New",monospace, 微软雅黑',
editorFontSize: 14,
fontLigatures: true,
header: {
skin: true, document: true, repo: true, qqGroup: true
},
request: {
beforeSend: function (config) {
let tenant_id = new URL(window.location.href).searchParams.get("tenant_id");
config.headers["TENANT-ID"] = tenant_id === null ? 1 : tenant_id
let access_token = new URL(window.location.href).searchParams.get("access_token");
if (access_token !== null) {
config.headers["Authorization"] = `Bearer ${access_token}`
}
return config;
}, onError: function (err) {
return Promise.reject(err)
}
},
response: {
onSuccess: function (resp) {
if (resp.data.code === -1) {
window.location.href = '/'
}
return resp;
}, onError: function (err) {
console.log('请求失败', err)
return Promise.reject(err)
},
},
themes: {
editor: {
base: 'vs-dark',
rules: [{foreground: 'A9B7C6'}, {
token: 'keywords',
foreground: 'CC7832',
fontStyle: 'bold'
}, {token: 'keyword', foreground: 'CC7832', fontStyle: 'bold'}, {
token: 'number',
foreground: '6897BB'
}, {token: 'string', foreground: '6A8759', fontStyle: 'bold'}, {
token: 'string.sql',
foreground: '6A8759'
}, {token: 'tag.sql', foreground: 'E8BF6A'}, {
token: 'attribute.name.sql',
foreground: 'BABABA'
}, {token: 'attribute.value.sql', foreground: '6A8759'}, {
token: 'predefined.sql',
foreground: 'A9B7C6',
fontStyle: 'italic'
}, {token: 'predefined.magicscript', foreground: 'A9B7C6', fontStyle: 'italic'}, {
token: 'key',
foreground: '9876AA'
}, {token: 'string.key.json', foreground: '9876AA'}, {
token: 'string.value.json',
foreground: '6A8759'
}, {token: 'keyword.json', foreground: '6897BB'}, {
token: 'operator.sql',
foreground: 'CC7832',
fontStyle: 'bold'
}, {token: 'string.invalid', foreground: '008000', background: 'FFCCCC'}, {
token: 'string.escape.invalid',
foreground: '008000',
background: 'FFCCCC'
}, {token: 'string.escape', foreground: '000080', fontStyle: 'bold'}, {
token: 'comment',
foreground: '808080',
fontStyle: 'italic'
}, {token: 'comment.doc', foreground: '629755', fontStyle: 'italic'}, {
token: 'comment.todo',
foreground: 'A8C023',
fontStyle: 'italic'
}, {token: 'string.escape', foreground: 'CC7832'}],
colors: {
'editor.background': '#2B2B2B', 'editorLineNumber.foreground': '#999999', //行号的颜色
'editorGutter.background': '#313335', //行号背景色
'editor.lineHighlightBackground': '#323232', //光标所在行的颜色
'dropdown.background': '#3C3F41', //右键菜单
'dropdown.foreground': '#BBBBBB', //右键菜单文字颜色
'list.activeSelectionBackground': '#4B6EAF', //右键菜单悬浮背景色
'list.activeSelectionForeground': '#FFFFFF', //右键菜单悬浮文字颜色
'editorSuggestWidget.selectedBackground': '#113A5C' //代码提示选中行的背景色
}
}, styles: {
'main-background-color': '#3C3F41', // 主要背景色
'main-border-color': '#323232', // 主要边框色
'main-color': '#bbb', // 主要文字颜色
'main-selected-background-color': '#323232', // 主要选中背景色
'main-hover-background-color': '#353739', // 主要悬浮背景色
'main-hover-icon-background-color': '#4C5052', // 主要悬浮图标背景色
'main-selected-color': '#fff', // 主要选中文字颜色
'main-icon-color': '#AFB1B3', // 主要图标颜色
'header-title-color': '#bbb', // 顶部名字颜色
'header-version-color': '#999', // 顶部版本号颜色
'header-default-color': '#AFB1B3', // 顶部其它文字颜色
'empty-background-color': '#282828', // 中间空的背景颜色
'empty-key-color': '#489DF6', // 中间空的快捷键文字颜色
'empty-color': '#A0A0A0', // 中间空的文字颜色
'button-hover-background-color': '#365880', // 按钮悬浮背景颜色
'button-hover-border-color': '#43688C', // 按钮悬浮边框颜色
'button-background-color': '#4C5052', // 按钮背景颜色
'button-border-color': '#5E6060', // 按钮边框颜色
'button-disabled-color': '#5a5a5a', // 按钮禁用时的颜色
'navbar-body-background-color': '#3C3F41', // 导航条内容背景颜色
'navbar-body-border-color': '#555555', //导航条内边框颜色
'resource-label-color': '#bbb', // 资源树形菜单label颜色
'resource-span-color': '#787878', // 资源树形菜单span颜色
'tree-hover-background-color': '#0d293e', // 树形菜单悬浮背景色
'tree-icon-color': '#aeb9c0', // 树形菜单图标颜色
'table-border-color': '#646464', // 表格边框颜色
'input-border-color': '#646464', // input边框颜色
'input-foucs-color': '#3D6185', // input focus边框颜色
'input-background-color': '#45494A', // input背景颜色
'select-background-color': '#3C3F41', // select背景颜色
'select-hover-background-color': '#3C3F41', // select悬浮背景色
'select-option-background-color': '#3C3F41', // select选项背景色
'select-option-hover-background-color': '#4B6EAF', // select选项悬浮背景色
'select-option-border-color': '#808080', // select选项边框色
// 数据类型颜色
'data-type-default-color': '#a9b7c6',
'data-type-string-color': '#6a8759',
'data-type-integer-color': '#6897bb',
'data-type-byte-color': '#6897bb',
'data-type-long-color': '#6897bb',
'data-type-float-color': '#6897bb',
'data-type-double-color': '#6897bb',
'data-type-short-color': '#6897bb',
'data-type-number-color': '#6897bb',
'data-type-boolean-color': '#cc7832',
'data-type-class-color': '#9876aa',
'data-type-key-color': '#FF8E8E',
'run-log-background-color': '#2b2b2b', // 运行日志背景颜色
// 日志级别颜色
'log-level-info': '#ABC023',
'log-level-error': '#CC666E',
'log-level-debug': '#299999',
'log-level-warn': 'unset',
'log-level-trace': '#5394EC',
'log-color-cyan': '#009191',
'log-color-link': '#287BDE',
'todo-color': '#A8C023',
'debug-line-background-color': '#2D6099', // 调试时,断点行背景颜色
'breakpoints-background-color': '#C75450', // 断点圆圈背景颜色
'breakpoint-line-background-color': '#3a2323', // 断点所在行的背景颜色
'select-inputable-background-color': '#45494a', // select输入框背景颜色
'select-inputable-border': 'transparent',
'tab-selected-background-color': '#4E5254', // tab 选中时的背景颜色
'message-em-color': '#68dd9a', // 消息 em 颜色
'checkbox-background-color': '#43494A',
'checkbox-border-color': '#6B6B6B',
'checkbox-text-color': '#bbb',
'checkbox-selected-background-color': '#43494A',
'checkbox-selected-border-color': '#6B6B6B',
'toolbox-list-label-color': '#bbb',
'toolbox-list-span-color': '#787878',
'toolbox-border-color': '#323232',
'toolbox-list-hover-background': '#0D293E',
'toolbox-border-right-color': '#555555',
'footer-border-color': '#323232',
'tab-bar-border-color': '#323232',
'dialog-border-color': '#282828',
'dialog-shadow-color': '#151515',
'table-col-border-color': '#333638',
'table-row-border-color': '#333638',
'table-hover-background': '#4B6EAF',
'debug-line-background': '#2D6099',
'breakpoints-background': '#C75450',
'breakpoint-line-background': '#3a2323',
'table-even-background': '#414547',
'button-disabled-background': '#5A5A5A',
'toolbox-list-header-icon-color': '#AFB1B3',
'log-error-color': '#CC666E',
'text-string-color': '#6A8759',
'text-number-color': '#6897BB',
'text-boolean-color': '#CC7832',
'text-property-color': '#9876aa',
'text-key-color': '#9876aa',
'suggest-hover-background': '#113A5C',
'suggest-hover-color': '#fff',
'statusbar-em-color': '#68dd9a',
}
}
}
@@ -0,0 +1,7 @@
magic-api:
prod: true #生产模式鉴权
show-url: false
banner: false
web: /api/designer
editor-config: classpath:./magic/magic-editor-config.js
sql-column-case: camel
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.pig4cloud.pigx.codegen.mapper.GenDynamicMapper">
<!-- 动态SQL查询 -->
<select id="dynamicQuerySql" parameterType="String" resultType="java.util.LinkedHashMap">
${value}
</select>
</mapper>
@@ -0,0 +1,6 @@
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import response;
import log;
var dbId = new DefaultIdentifierGenerator().nextId(null)
return db.${dsName}.table("${tableName}").primary("$pk.columnName", dbId).save(body)
@@ -0,0 +1,8 @@
import response;
var data = db.${dsName}.table("${tableName}").primary("$pk.columnName").update({
id: id,
del_flag: 1
})
return response.json(data)
@@ -0,0 +1,17 @@
import request;
import cn.hutool.json.JSONUtil;
import response;
var queryDsl = db.${dsName}.table("${tableName}")
.where()
.eq("del_flag", 0)
if (query != null) {
var jsonObj = JSONUtil.parseObj(query)
for (key in jsonObj.keySet()) {
queryDsl.like(key, "%" + jsonObj.get(key) + "%")
}
}
// 执行DSL 输出结果
return response.json(queryDsl.page())
@@ -0,0 +1,5 @@
import response;
var data = db.${dsName}.table("${tableName}").primary("$pk.columnName").update(body)
return response.json(data)