diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/ColumnInfo.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/ColumnInfo.java deleted file mode 100644 index cc23dd560..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/ColumnInfo.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.domain; - -import io.swagger.annotations.ApiModelProperty; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.nl.modules.generator.utils.GenUtil; - -import javax.persistence.*; -import java.io.Serializable; - -/** - * 列的数据信息 - * @author Zheng Jie - * @date 2019-01-02 - */ -@Getter -@Setter -@Entity -@NoArgsConstructor -@Table(name = "code_column_config") -public class ColumnInfo implements Serializable { - - @Id - @Column(name = "column_id") - @ApiModelProperty(value = "ID", hidden = true) - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @ApiModelProperty(value = "表名") - private String tableName; - - @ApiModelProperty(value = "数据库字段名称") - private String columnName; - - @ApiModelProperty(value = "数据库字段类型") - private String columnType; - - @ApiModelProperty(value = "数据库字段键类型") - private String keyType; - - @ApiModelProperty(value = "字段额外的参数") - private String extra; - - @ApiModelProperty(value = "数据库字段描述") - private String remark; - - @ApiModelProperty(value = "是否必填") - private Boolean notNull; - - @ApiModelProperty(value = "是否在列表显示") - private Boolean listShow; - - @ApiModelProperty(value = "是否表单显示") - private Boolean formShow; - - @ApiModelProperty(value = "表单类型") - private String formType; - - @ApiModelProperty(value = "查询 1:模糊 2:精确") - private String queryType; - - @ApiModelProperty(value = "字典名称") - private String dictName; - - @ApiModelProperty(value = "日期注解") - private String dateAnnotation; - - public ColumnInfo(String tableName, String columnName, Boolean notNull, String columnType, String remark, String keyType, String extra) { - this.tableName = tableName; - this.columnName = columnName; - this.columnType = columnType; - this.keyType = keyType; - this.extra = extra; - this.notNull = notNull; - if(GenUtil.PK.equalsIgnoreCase(keyType) && GenUtil.EXTRA.equalsIgnoreCase(extra)){ - this.notNull = false; - } - this.remark = remark; - this.listShow = true; - this.formShow = true; - } -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/GenConfig.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/GenConfig.java deleted file mode 100644 index 454b1e93f..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/GenConfig.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.domain; - -import io.swagger.annotations.ApiModelProperty; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; - -import javax.persistence.*; -import javax.validation.constraints.NotBlank; -import java.io.Serializable; - -/** - * 代码生成配置 - * @author Zheng Jie - * @date 2019-01-03 - */ -@Getter -@Setter -@Entity -@NoArgsConstructor -@Table(name = "code_gen_config") -public class GenConfig implements Serializable { - - public GenConfig(String tableName) { - this.tableName = tableName; - } - - @Id - @Column(name = "config_id") - @ApiModelProperty(value = "ID", hidden = true) - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @NotBlank - @ApiModelProperty(value = "表名") - private String tableName; - - @ApiModelProperty(value = "接口名称") - private String apiAlias; - - @NotBlank - @ApiModelProperty(value = "包路径") - private String pack; - - @NotBlank - @ApiModelProperty(value = "模块名") - private String moduleName; - - @NotBlank - @ApiModelProperty(value = "前端文件路径") - private String path; - - @ApiModelProperty(value = "前端文件路径") - private String apiPath; - - @ApiModelProperty(value = "作者") - private String author; - - @ApiModelProperty(value = "表前缀") - private String prefix; - - @ApiModelProperty(value = "是否覆盖") - private Boolean cover = false; -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/vo/TableInfo.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/vo/TableInfo.java deleted file mode 100644 index ddf3388cd..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/domain/vo/TableInfo.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.domain.vo; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * 表的数据信息 - * @author Zheng Jie - * @date 2019-01-02 - */ -@Data -@AllArgsConstructor -@NoArgsConstructor -public class TableInfo { - - /** 表名称 */ - private Object tableName; - - /** 创建日期 */ - private Object createTime; - - /** 数据库引擎 */ - private Object engine; - - /** 编码集 */ - private Object coding; - - /** 备注 */ - private Object remark; - - -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/ColumnInfoRepository.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/ColumnInfoRepository.java deleted file mode 100644 index 8af5fbb07..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/ColumnInfoRepository.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.repository; - -import org.nl.modules.generator.domain.ColumnInfo; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.List; - -/** - * @author Zheng Jie - * @date 2019-01-14 - */ -public interface ColumnInfoRepository extends JpaRepository { - - /** - * 查询表信息 - * @param tableName 表格名 - * @return 表信息 - */ - List findByTableNameOrderByIdAsc(String tableName); -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/GenConfigRepository.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/GenConfigRepository.java deleted file mode 100644 index c6afcef2a..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/repository/GenConfigRepository.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.repository; - -import org.nl.modules.generator.domain.GenConfig; -import org.springframework.data.jpa.repository.JpaRepository; - -/** - * @author Zheng Jie - * @date 2019-01-14 - */ -public interface GenConfigRepository extends JpaRepository { - - /** - * 查询表配置 - * @param tableName 表名 - * @return / - */ - GenConfig findByTableName(String tableName); -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GenConfigService.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GenConfigService.java deleted file mode 100644 index 43d9ab312..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GenConfigService.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.service; - -import org.nl.modules.generator.domain.GenConfig; - -/** - * @author Zheng Jie - * @date 2019-01-14 - */ -public interface GenConfigService { - - /** - * 查询表配置 - * @param tableName 表名 - * @return 表配置 - */ - GenConfig find(String tableName); - - /** - * 更新表配置 - * @param tableName 表名 - * @param genConfig 表配置 - * @return 表配置 - */ - GenConfig update(String tableName, GenConfig genConfig); -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GeneratorService.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GeneratorService.java deleted file mode 100644 index 0e749f382..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/GeneratorService.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.service; - -import org.nl.modules.generator.domain.ColumnInfo; -import org.nl.modules.generator.domain.GenConfig; -import org.springframework.http.ResponseEntity; -import org.springframework.scheduling.annotation.Async; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.List; - -/** - * @author Zheng Jie - * @date 2019-01-02 - */ -public interface GeneratorService { - - /** - * 查询数据库元数据 - * @param name 表名 - * @param startEnd 分页参数 - * @return / - */ - Object getTables(String name, int[] startEnd); - - /** - * 得到数据表的元数据 - * @param name 表名 - * @return / - */ - List getColumns(String name); - - /** - * 同步表数据 - * @param columnInfos / - * @param columnInfoList / - */ - @Async - void sync(List columnInfos, List columnInfoList); - - /** - * 保持数据 - * @param columnInfos / - */ - void save(List columnInfos); - - /** - * 获取所有table - * @return / - */ - Object getTables(); - - /** - * 代码生成 - * @param genConfig 配置信息 - * @param columns 字段信息 - */ - void generator(GenConfig genConfig, List columns); - - /** - * 预览 - * @param genConfig 配置信息 - * @param columns 字段信息 - * @return / - */ - ResponseEntity preview(GenConfig genConfig, List columns); - - /** - * 打包下载 - * @param genConfig 配置信息 - * @param columns 字段信息 - * @param request / - * @param response / - */ - void download(GenConfig genConfig, List columns, HttpServletRequest request, HttpServletResponse response); - - /** - * 查询数据库的表字段数据数据 - * @param table / - * @return / - */ - List query(String table); -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GenConfigServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GenConfigServiceImpl.java deleted file mode 100644 index 179516408..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GenConfigServiceImpl.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.service.impl; - -import cn.hutool.core.util.StrUtil; -import lombok.RequiredArgsConstructor; -import org.nl.modules.generator.domain.GenConfig; -import org.nl.modules.generator.repository.GenConfigRepository; -import org.nl.modules.generator.service.GenConfigService; -import org.springframework.stereotype.Service; - -import java.io.File; - -/** - * @author Zheng Jie - * @date 2019-01-14 - */ -@Service -@RequiredArgsConstructor -public class GenConfigServiceImpl implements GenConfigService { - - private final GenConfigRepository genConfigRepository; - - @Override - public GenConfig find(String tableName) { - GenConfig genConfig = genConfigRepository.findByTableName(tableName); - if(genConfig == null){ - return new GenConfig(tableName); - } - return genConfig; - } - - @Override - public GenConfig update(String tableName, GenConfig genConfig) { - // 如果 api 路径为空,则自动生成路径 - if(StrUtil.isEmpty(genConfig.getApiPath())){ - String separator = File.separator; - String[] paths; - String symbol = "\\"; - if (symbol.equals(separator)) { - paths = genConfig.getPath().split("\\\\"); - } else { - paths = genConfig.getPath().split(File.separator); - } - StringBuilder api = new StringBuilder(); - for (String path : paths) { - api.append(path); - api.append(separator); - if ("src".equals(path)) { - api.append("api"); - break; - } - } - genConfig.setApiPath(api.toString()); - } - return genConfigRepository.save(genConfig); - } -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GeneratorServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GeneratorServiceImpl.java deleted file mode 100644 index 3fea2a993..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/service/impl/GeneratorServiceImpl.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.service.impl; - -import cn.hutool.core.collection.CollectionUtil; -import cn.hutool.core.util.ObjectUtil; -import cn.hutool.core.util.StrUtil; -import cn.hutool.core.util.ZipUtil; -import lombok.RequiredArgsConstructor; -import org.nl.modules.common.exception.BadRequestException; -import org.nl.modules.common.utils.FileUtil; -import org.nl.modules.common.utils.PageUtil; -import org.nl.modules.generator.domain.ColumnInfo; -import org.nl.modules.generator.domain.GenConfig; -import org.nl.modules.generator.domain.vo.TableInfo; -import org.nl.modules.generator.repository.ColumnInfoRepository; -import org.nl.modules.generator.service.GeneratorService; -import org.nl.modules.generator.utils.GenUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.stereotype.Service; - -import javax.persistence.EntityManager; -import javax.persistence.PersistenceContext; -import javax.persistence.Query; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * @author Zheng Jie - * @date 2019-01-02 - */ -@Service -@RequiredArgsConstructor -public class GeneratorServiceImpl implements GeneratorService { - private static final Logger log = LoggerFactory.getLogger(GeneratorServiceImpl.class); - @PersistenceContext - private EntityManager em; - - private final ColumnInfoRepository columnInfoRepository; - - @Override - public Object getTables() { - // 使用预编译防止sql注入 - String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " + - "where table_schema = (select database()) " + - "order by create_time desc"; - Query query = em.createNativeQuery(sql); - return query.getResultList(); - } - - @Override - public Object getTables(String name, int[] startEnd) { - // 使用预编译防止sql注入 - String sql = "select table_name ,create_time , engine, table_collation, table_comment from information_schema.tables " + - "where table_schema = (select database()) " + - "and table_name like ? order by create_time desc"; - Query query = em.createNativeQuery(sql); - query.setFirstResult(startEnd[0]); - query.setMaxResults(startEnd[1] - startEnd[0]); - query.setParameter(1, StrUtil.isNotEmpty(name) ? ("%" + name + "%") : "%%"); - List result = query.getResultList(); - List tableInfos = new ArrayList<>(); - for (Object obj : result) { - Object[] arr = (Object[]) obj; - tableInfos.add(new TableInfo(arr[0], arr[1], arr[2], arr[3], ObjectUtil.isNotEmpty(arr[4]) ? arr[4] : "-")); - } - Query query1 = em.createNativeQuery("SELECT COUNT(*) from information_schema.tables where table_schema = (select database())"); - Object totalElements = query1.getSingleResult(); - return PageUtil.toPage(tableInfos, totalElements); - } - - @Override - public List getColumns(String tableName) { - List columnInfos = columnInfoRepository.findByTableNameOrderByIdAsc(tableName); - if (CollectionUtil.isNotEmpty(columnInfos)) { - return columnInfos; - } else { - columnInfos = query(tableName); - return columnInfoRepository.saveAll(columnInfos); - } - } - - @Override - public List query(String tableName) { - // 使用预编译防止sql注入 - String sql = "select column_name, is_nullable, data_type, column_comment, column_key, extra from information_schema.columns " + - "where table_name = ? and table_schema = (select database()) order by ordinal_position"; - Query query = em.createNativeQuery(sql); - query.setParameter(1, tableName); - List result = query.getResultList(); - List columnInfos = new ArrayList<>(); - for (Object obj : result) { - Object[] arr = (Object[]) obj; - columnInfos.add( - new ColumnInfo( - tableName, - arr[0].toString(), - "NO".equals(arr[1]), - arr[2].toString(), - ObjectUtil.isNotNull(arr[3]) ? arr[3].toString() : null, - ObjectUtil.isNotNull(arr[4]) ? arr[4].toString() : null, - ObjectUtil.isNotNull(arr[5]) ? arr[5].toString() : null) - ); - } - return columnInfos; - } - - @Override - public void sync(List columnInfos, List columnInfoList) { - // 第一种情况,数据库类字段改变或者新增字段 - for (ColumnInfo columnInfo : columnInfoList) { - // 根据字段名称查找 - List columns = columnInfos.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); - // 如果能找到,就修改部分可能被字段 - if (CollectionUtil.isNotEmpty(columns)) { - ColumnInfo column = columns.get(0); - column.setColumnType(columnInfo.getColumnType()); - column.setExtra(columnInfo.getExtra()); - column.setKeyType(columnInfo.getKeyType()); - if (StrUtil.isEmpty(column.getRemark())) { - column.setRemark(columnInfo.getRemark()); - } - columnInfoRepository.save(column); - } else { - // 如果找不到,则保存新字段信息 - columnInfoRepository.save(columnInfo); - } - } - // 第二种情况,数据库字段删除了 - for (ColumnInfo columnInfo : columnInfos) { - // 根据字段名称查找 - List columns = columnInfoList.stream().filter(c -> c.getColumnName().equals(columnInfo.getColumnName())).collect(Collectors.toList()); - // 如果找不到,就代表字段被删除了,则需要删除该字段 - if (CollectionUtil.isEmpty(columns)) { - columnInfoRepository.delete(columnInfo); - } - } - } - - @Override - public void save(List columnInfos) { - columnInfoRepository.saveAll(columnInfos); - } - - @Override - public void generator(GenConfig genConfig, List columns) { - if (genConfig.getId() == null) { - throw new BadRequestException("请先配置生成器"); - } - try { - GenUtil.generatorCode(columns, genConfig); - } catch (IOException e) { - log.error(e.getMessage(), e); - throw new BadRequestException("生成失败,请手动处理已生成的文件"); - } - } - - @Override - public ResponseEntity preview(GenConfig genConfig, List columns) { - if (genConfig.getId() == null) { - throw new BadRequestException("请先配置生成器"); - } - List> genList = GenUtil.preview(columns, genConfig); - return new ResponseEntity<>(genList, HttpStatus.OK); - } - - @Override - public void download(GenConfig genConfig, List columns, HttpServletRequest request, HttpServletResponse response) { - if (genConfig.getId() == null) { - throw new BadRequestException("请先配置生成器"); - } - try { - File file = new File(GenUtil.download(columns, genConfig)); - String zipPath = file.getPath() + ".zip"; - ZipUtil.zip(file.getPath(), zipPath); - FileUtil.downloadFile(request, response, new File(zipPath), true); - } catch (IOException e) { - throw new BadRequestException("打包失败"); - } - } -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/config/JobRunner.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/config/JobRunner.java deleted file mode 100644 index 85f1b8b74..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/config/JobRunner.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.config; - -import lombok.RequiredArgsConstructor; -import org.nl.modules.quartz.domain.QuartzJob; -import org.nl.modules.quartz.repository.QuartzJobRepository; -import org.nl.modules.quartz.utils.QuartzManage; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.core.annotation.Order; -import org.springframework.stereotype.Component; - -import java.util.List; - -/** - * @author Zheng Jie - * @date 2019-01-07 - */ -@Component -@RequiredArgsConstructor -@Order(100) -public class JobRunner implements ApplicationRunner { - private static final Logger log = LoggerFactory.getLogger(JobRunner.class); - private final QuartzJobRepository quartzJobRepository; - private final QuartzManage quartzManage; - - /** - * 项目启动时重新激活启用的定时任务 - * - * @param applicationArguments / - */ - @Override - public void run(ApplicationArguments applicationArguments) { - log.info("--------------------注入定时任务---------------------"); - List quartzJobs = quartzJobRepository.findByIsPauseIsFalse(); - quartzJobs.forEach(quartzManage::addJob); - log.info("--------------------定时任务注入完成---------------------"); - } -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/config/QuartzConfig.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/config/QuartzConfig.java deleted file mode 100644 index 27baea90b..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/config/QuartzConfig.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.config; - -import org.quartz.Scheduler; -import org.quartz.spi.TriggerFiredBundle; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.scheduling.quartz.AdaptableJobFactory; -import org.springframework.scheduling.quartz.SchedulerFactoryBean; -import org.springframework.stereotype.Component; - -/** - * 定时任务配置 - * @author / - * @date 2019-01-07 - */ -@Configuration -public class QuartzConfig { - - /** - * 解决Job中注入Spring Bean为null的问题 - */ - @Component("quartzJobFactory") - public static class QuartzJobFactory extends AdaptableJobFactory { - - private final AutowireCapableBeanFactory capableBeanFactory; - - public QuartzJobFactory(AutowireCapableBeanFactory capableBeanFactory) { - this.capableBeanFactory = capableBeanFactory; - } - - @Override - protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { - - //调用父类的方法 - Object jobInstance = super.createJobInstance(bundle); - capableBeanFactory.autowireBean(jobInstance); - return jobInstance; - } - } - - /** - * 注入scheduler到spring - * @param quartzJobFactory / - * @return Scheduler - * @throws Exception / - */ - @Bean(name = "scheduler") - public Scheduler scheduler(QuartzJobFactory quartzJobFactory) throws Exception { - SchedulerFactoryBean factoryBean=new SchedulerFactoryBean(); - factoryBean.setJobFactory(quartzJobFactory); - factoryBean.afterPropertiesSet(); - Scheduler scheduler=factoryBean.getScheduler(); - scheduler.start(); - return scheduler; - } -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/domain/QuartzJob.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/domain/QuartzJob.java deleted file mode 100644 index bce16045d..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/domain/QuartzJob.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.domain; - -import io.swagger.annotations.ApiModelProperty; -import lombok.Getter; -import lombok.Setter; -import org.nl.modules.common.base.BaseEntity; - -import javax.persistence.*; -import javax.validation.constraints.NotBlank; -import javax.validation.constraints.NotNull; -import java.io.Serializable; - -/** - * @author Zheng Jie - * @date 2019-01-07 - */ -@Getter -@Setter -@Entity -@Table(name = "sys_quartz_job") -public class QuartzJob extends BaseEntity implements Serializable { - - public static final String JOB_KEY = "JOB_KEY"; - - @Id - @Column(name = "job_id") - @NotNull(groups = {Update.class}) - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @Transient - @ApiModelProperty(value = "用于子任务唯一标识", hidden = true) - private String uuid; - - @ApiModelProperty(value = "定时器名称") - private String jobName; - - @NotBlank - @ApiModelProperty(value = "Bean名称") - private String beanName; - - @NotBlank - @ApiModelProperty(value = "方法名称") - private String methodName; - - @ApiModelProperty(value = "参数") - private String params; - - @NotBlank - @ApiModelProperty(value = "cron表达式") - private String cronExpression; - - @ApiModelProperty(value = "状态,暂时或启动") - private Boolean isPause = false; - - @ApiModelProperty(value = "负责人") - private String personInCharge; - - @ApiModelProperty(value = "报警邮箱") - private String email; - - @ApiModelProperty(value = "子任务") - private String subTask; - - @ApiModelProperty(value = "失败后暂停") - private Boolean pauseAfterFailure; - - @NotBlank - @ApiModelProperty(value = "备注") - private String description; -} \ No newline at end of file diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/domain/QuartzLog.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/domain/QuartzLog.java deleted file mode 100644 index fbdb2d1e4..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/domain/QuartzLog.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.domain; - -import io.swagger.annotations.ApiModelProperty; -import lombok.Data; -import org.hibernate.annotations.CreationTimestamp; - -import javax.persistence.*; -import java.io.Serializable; -import java.sql.Timestamp; - -/** - * @author Zheng Jie - * @date 2019-01-07 - */ -@Entity -@Data -@Table(name = "sys_quartz_log") -public class QuartzLog implements Serializable { - - @Id - @Column(name = "log_id") - @ApiModelProperty(value = "ID", hidden = true) - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; - - @ApiModelProperty(value = "任务名称", hidden = true) - private String jobName; - - @ApiModelProperty(value = "bean名称", hidden = true) - private String beanName; - - @ApiModelProperty(value = "方法名称", hidden = true) - private String methodName; - - @ApiModelProperty(value = "参数", hidden = true) - private String params; - - @ApiModelProperty(value = "cron表达式", hidden = true) - private String cronExpression; - - @ApiModelProperty(value = "状态", hidden = true) - private Boolean isSuccess; - - @ApiModelProperty(value = "异常详情", hidden = true) - private String exceptionDetail; - - @ApiModelProperty(value = "执行耗时", hidden = true) - private Long time; - - @CreationTimestamp - @ApiModelProperty(value = "创建时间", hidden = true) - private Timestamp createTime; -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/repository/QuartzJobRepository.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/repository/QuartzJobRepository.java deleted file mode 100644 index a63fcf291..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/repository/QuartzJobRepository.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.repository; - -import org.nl.modules.quartz.domain.QuartzJob; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -import java.util.List; - -/** - * @author Zheng Jie - * @date 2019-01-07 - */ -public interface QuartzJobRepository extends JpaRepository, JpaSpecificationExecutor { - - /** - * 查询启用的任务 - * @return List - */ - List findByIsPauseIsFalse(); -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/repository/QuartzLogRepository.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/repository/QuartzLogRepository.java deleted file mode 100644 index 54c5101fb..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/repository/QuartzLogRepository.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.repository; - -import org.nl.modules.quartz.domain.QuartzLog; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -/** - * @author Zheng Jie - * @date 2019-01-07 - */ -public interface QuartzLogRepository extends JpaRepository, JpaSpecificationExecutor { - -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/service/QuartzJobService.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/service/QuartzJobService.java deleted file mode 100644 index 74ec177f6..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/service/QuartzJobService.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.service; - -import org.nl.modules.quartz.domain.QuartzJob; -import org.nl.modules.quartz.domain.QuartzLog; -import org.nl.modules.quartz.service.dto.JobQueryCriteria; -import org.springframework.data.domain.Pageable; - -import java.util.List; -import java.util.Set; - -/** - * @author Zheng Jie - * @date 2019-01-07 - */ -public interface QuartzJobService { - - /** - * 分页查询 - * - * @param criteria 条件 - * @param pageable 分页参数 - * @return / - */ - Object queryAll(JobQueryCriteria criteria, Pageable pageable); - - /** - * 查询全部 - * - * @param criteria 条件 - * @return / - */ - List queryAll(JobQueryCriteria criteria); - - /** - * 分页查询日志 - * - * @param criteria 条件 - * @param pageable 分页参数 - * @return / - */ - Object queryAllLog(JobQueryCriteria criteria, Pageable pageable); - - /** - * 查询全部 - * - * @param criteria 条件 - * @return / - */ - List queryAllLog(JobQueryCriteria criteria); - - /** - * 创建 - * - * @param resources / - */ - void create(QuartzJob resources); - - /** - * 编辑 - * - * @param resources / - */ - void update(QuartzJob resources); - - /** - * 删除任务 - * - * @param ids / - */ - void delete(Set ids); - - /** - * 根据ID查询 - * - * @param id ID - * @return / - */ - QuartzJob findById(Long id); - - /** - * 更改定时任务状态 - * - * @param quartzJob / - */ - void updateIsPause(QuartzJob quartzJob); - - /** - * 立即执行定时任务 - * - * @param quartzJob / - */ - void execution(QuartzJob quartzJob); - - - /** - * 执行子任务 - * - * @param tasks / - * @throws InterruptedException / - */ - void executionSubJob(String[] tasks) throws InterruptedException; -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/service/dto/JobQueryCriteria.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/service/dto/JobQueryCriteria.java deleted file mode 100644 index 2279effc9..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/service/dto/JobQueryCriteria.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.service.dto; - -import lombok.Data; -import org.nl.modules.common.annotation.Query; - -import java.sql.Timestamp; -import java.util.List; - -/** - * @author Zheng Jie - * @date 2019-6-4 10:33:02 - */ -@Data -public class JobQueryCriteria { - - @Query(type = Query.Type.INNER_LIKE) - private String jobName; - - @Query - private Boolean isSuccess; - - @Query(type = Query.Type.BETWEEN) - private List createTime; -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/service/impl/QuartzJobServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/service/impl/QuartzJobServiceImpl.java deleted file mode 100644 index edc15b6b6..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/service/impl/QuartzJobServiceImpl.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.service.impl; - -import cn.hutool.core.util.IdUtil; -import cn.hutool.core.util.StrUtil; -import lombok.RequiredArgsConstructor; -import org.nl.modules.common.exception.BadRequestException; -import org.nl.modules.common.utils.PageUtil; -import org.nl.modules.common.utils.QueryHelp; -import org.nl.modules.common.utils.RedisUtils; -import org.nl.modules.common.utils.ValidationUtil; -import org.nl.modules.quartz.domain.QuartzJob; -import org.nl.modules.quartz.domain.QuartzLog; -import org.nl.modules.quartz.repository.QuartzJobRepository; -import org.nl.modules.quartz.repository.QuartzLogRepository; -import org.nl.modules.quartz.service.QuartzJobService; -import org.nl.modules.quartz.service.dto.JobQueryCriteria; -import org.nl.modules.quartz.utils.QuartzManage; -import org.quartz.CronExpression; -import org.springframework.data.domain.Pageable; -import org.springframework.scheduling.annotation.Async; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -/** - * @author Zheng Jie - * @date 2019-01-07 - */ -@RequiredArgsConstructor -@Service(value = "quartzJobService") -public class QuartzJobServiceImpl implements QuartzJobService { - - private final QuartzJobRepository quartzJobRepository; - private final QuartzLogRepository quartzLogRepository; - private final QuartzManage quartzManage; - private final RedisUtils redisUtils; - - @Override - public Object queryAll(JobQueryCriteria criteria, Pageable pageable) { - return PageUtil.toPage(quartzJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable)); - } - - @Override - public Object queryAllLog(JobQueryCriteria criteria, Pageable pageable) { - return PageUtil.toPage(quartzLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable)); - } - - @Override - public List queryAll(JobQueryCriteria criteria) { - return quartzJobRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); - } - - @Override - public List queryAllLog(JobQueryCriteria criteria) { - return quartzLogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)); - } - - @Override - public QuartzJob findById(Long id) { - QuartzJob quartzJob = quartzJobRepository.findById(id).orElseGet(QuartzJob::new); - ValidationUtil.isNull(quartzJob.getId(), "QuartzJob", "id", id); - return quartzJob; - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void create(QuartzJob resources) { - if (!CronExpression.isValidExpression(resources.getCronExpression())) { - throw new BadRequestException("cron表达式格式错误"); - } - resources = quartzJobRepository.save(resources); - quartzManage.addJob(resources); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void update(QuartzJob resources) { - if (!CronExpression.isValidExpression(resources.getCronExpression())) { - throw new BadRequestException("cron表达式格式错误"); - } - if (StrUtil.isNotEmpty(resources.getSubTask())) { - List tasks = Arrays.asList(resources.getSubTask().split("[,,]")); - if (tasks.contains(resources.getId().toString())) { - throw new BadRequestException("子任务中不能添加当前任务ID"); - } - } - resources = quartzJobRepository.save(resources); - quartzManage.updateJobCron(resources); - } - - @Override - public void updateIsPause(QuartzJob quartzJob) { - if (quartzJob.getIsPause()) { - quartzManage.resumeJob(quartzJob); - quartzJob.setIsPause(false); - } else { - quartzManage.pauseJob(quartzJob); - quartzJob.setIsPause(true); - } - quartzJobRepository.save(quartzJob); - } - - @Override - public void execution(QuartzJob quartzJob) { - quartzManage.runJobNow(quartzJob); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void delete(Set ids) { - for (Long id : ids) { - QuartzJob quartzJob = findById(id); - quartzManage.deleteJob(quartzJob); - quartzJobRepository.delete(quartzJob); - } - } - - @Async - @Override - @Transactional(rollbackFor = Exception.class) - public void executionSubJob(String[] tasks) throws InterruptedException { - for (String id : tasks) { - QuartzJob quartzJob = findById(Long.parseLong(id)); - // 执行任务 - String uuid = IdUtil.simpleUUID(); - quartzJob.setUuid(uuid); - // 执行任务 - execution(quartzJob); - // 获取执行状态,如果执行失败则停止后面的子任务执行 - Boolean result = (Boolean) redisUtils.get(uuid); - while (result == null) { - // 休眠5秒,再次获取子任务执行情况 - Thread.sleep(5000); - result = (Boolean) redisUtils.get(uuid); - } - if (!result) { - redisUtils.del(uuid); - break; - } - } - } - -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/task/TestTask.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/task/TestTask.java deleted file mode 100644 index 0d67ce09e..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/task/TestTask.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.task; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; - -/** - * 测试用 - * @author Zheng Jie - * @date 2019-01-08 - */ -@Slf4j -@Component -public class TestTask { - - public void run(){ - log.info("run 执行成功"); - } - - public void run1(String str){ - log.info("run1 执行成功,参数为: {}" + str); - } - - public void run2(){ - log.info("run2 执行成功"); - } -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/utils/QuartzRunnable.java b/lms/nladmin-system/src/main/java/org/nl/modules/quartz/utils/QuartzRunnable.java deleted file mode 100644 index e2ef49bad..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/utils/QuartzRunnable.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.utils; - -import cn.hutool.core.util.StrUtil; -import lombok.extern.slf4j.Slf4j; -import org.nl.modules.wql.util.SpringContextHolder; -import org.springframework.util.ReflectionUtils; - -import java.lang.reflect.Method; -import java.util.concurrent.Callable; - -/** - * 执行定时任务 - * @author / - */ -@Slf4j -public class QuartzRunnable implements Callable { - - private final Object target; - private final Method method; - private final String params; - - QuartzRunnable(String beanName, String methodName, String params) - throws NoSuchMethodException, SecurityException { - this.target = SpringContextHolder.getBean(beanName); - this.params = params; - - if (StrUtil.isNotEmpty(params)) { - this.method = target.getClass().getDeclaredMethod(methodName, String.class); - } else { - this.method = target.getClass().getDeclaredMethod(methodName); - } - } - - @Override - public Object call() throws Exception { - ReflectionUtils.makeAccessible(method); - if (StrUtil.isNotEmpty(params)) { - method.invoke(target, params); - } else { - method.invoke(target); - } - return null; - } -} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/tools/config/MultipartConfig.java b/lms/nladmin-system/src/main/java/org/nl/modules/tools/config/MultipartConfig.java index 853d7f85a..dbfe213f1 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/tools/config/MultipartConfig.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/tools/config/MultipartConfig.java @@ -1,18 +1,3 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.nl.modules.tools.config; import org.springframework.boot.web.servlet.MultipartConfigFactory; @@ -23,8 +8,9 @@ import javax.servlet.MultipartConfigElement; import java.io.File; /** - * @date 2018-12-28 - * @author https://blog.csdn.net/llibin1024530411/article/details/79474953 + * @author: lyd + * @description: + * @Date: 2022/12/6 */ @Configuration public class MultipartConfig { @@ -45,4 +31,4 @@ public class MultipartConfig { factory.setLocation(location); return factory.createMultipartConfig(); } -} \ No newline at end of file +} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/tools/domain/LocalStorage.java b/lms/nladmin-system/src/main/java/org/nl/modules/tools/domain/LocalStorage.java index b9e535ec1..97bacbde2 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/tools/domain/LocalStorage.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/tools/domain/LocalStorage.java @@ -1,76 +1,78 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.nl.modules.tools.domain; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.copier.CopyOptions; -import io.swagger.annotations.ApiModelProperty; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import org.nl.modules.common.base.BaseEntity; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.IdUtil; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; +import org.nl.sso.tools.SecurityUtils; -import javax.persistence.*; import java.io.Serializable; /** -* @author Zheng Jie -* @date 2019-09-05 -*/ -@Getter -@Setter -@Entity -@Table(name="tool_local_storage") -@NoArgsConstructor -public class LocalStorage extends BaseEntity implements Serializable { + * @author: lyd + * @description: + * @Date: 2022/12/6 + */ +@Data +public class LocalStorage implements Serializable { + /** 标识 */ + /** 防止精度丢失 */ + @JsonSerialize(using= ToStringSerializer.class) + private Long storage_id; - @Id - @Column(name = "storage_id") - @ApiModelProperty(value = "ID", hidden = true) - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long id; + /** 文件真实的名称 */ + private String real_name; - @ApiModelProperty(value = "真实文件名") - private String realName; - - @ApiModelProperty(value = "文件名") + /** 文件名 */ private String name; - @ApiModelProperty(value = "后缀") + /** 后缀 */ private String suffix; - @ApiModelProperty(value = "路径") + /** 路径 */ private String path; - @ApiModelProperty(value = "类型") + /** 类型 */ private String type; - @ApiModelProperty(value = "大小") + /** 大小 */ private String size; - public LocalStorage(String realName,String name, String suffix, String path, String type, String size) { - this.realName = realName; + /** 创建人标识 */ + private String create_id; + + /** 创建人 */ + private String create_name; + + /** 创建时间 */ + private String create_time; + + /** 修改人标识 */ + private String update_optid; + + /** 修改人 */ + private String update_optname; + + /** 修改时间 */ + private String update_time; + + public LocalStorage(String realName, String name, String suffix, String path, String type, String size) { + this.storage_id = IdUtil.getSnowflake(1,1).nextId(); + this.real_name = realName; this.name = name; this.suffix = suffix; this.path = path; this.type = type; this.size = size; + this.create_id = this.update_optid = SecurityUtils.getCurrentUserId().toString(); + this.create_name = this.update_optname = SecurityUtils.getCurrentNickName(); + this.create_time = this.update_time = DateUtil.now(); } public void copy(LocalStorage source){ BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true)); } -} \ No newline at end of file +} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/tools/repository/LocalStorageRepository.java b/lms/nladmin-system/src/main/java/org/nl/modules/tools/repository/LocalStorageRepository.java deleted file mode 100644 index 3278bdcce..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/tools/repository/LocalStorageRepository.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.tools.repository; - -import org.nl.modules.tools.domain.LocalStorage; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.JpaSpecificationExecutor; - -/** -* @author Zheng Jie -* @date 2019-09-05 -*/ -public interface LocalStorageRepository extends JpaRepository, JpaSpecificationExecutor { -} \ No newline at end of file diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/tools/rest/LocalStorageController.java b/lms/nladmin-system/src/main/java/org/nl/modules/tools/rest/LocalStorageController.java index 475274e80..e0af9d155 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/tools/rest/LocalStorageController.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/tools/rest/LocalStorageController.java @@ -1,18 +1,3 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.nl.modules.tools.rest; import cn.dev33.satoken.annotation.SaCheckPermission; @@ -25,7 +10,6 @@ import org.nl.modules.common.utils.FileUtil; import org.nl.modules.logging.annotation.Log; import org.nl.modules.tools.domain.LocalStorage; import org.nl.modules.tools.service.LocalStorageService; -import org.nl.modules.tools.service.dto.LocalStorageQueryCriteria; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -33,41 +17,33 @@ import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; +import java.util.Map; /** - * @author Zheng Jie - * @date 2019-09-05 + * @author: lyd + * @description: 本地存储管理 + * @Date: 2022/12/5 */ @RestController @RequiredArgsConstructor @Api(tags = "工具:本地存储管理") @RequestMapping("/api/localStorage") public class LocalStorageController { - private final LocalStorageService localStorageService; @ApiOperation("查询文件") @GetMapping - @SaCheckPermission("storage:list") - public ResponseEntity query(LocalStorageQueryCriteria criteria, Pageable pageable) { +// @SaCheckPermission("storage:list") + public ResponseEntity query(@RequestParam Map criteria, Pageable pageable) { return new ResponseEntity<>(localStorageService.queryAll(criteria, pageable), HttpStatus.OK); } - @ApiOperation("导出数据") - @GetMapping(value = "/download") - @SaCheckPermission("storage:list") - public void download(HttpServletResponse response, LocalStorageQueryCriteria criteria) throws IOException { - localStorageService.download(localStorageService.queryAll(criteria), response); - } - @ApiOperation("上传文件") @PostMapping - @SaCheckPermission("storage:add") + @SaIgnore +// @SaCheckPermission("storage:add") public ResponseEntity create(@RequestParam String name, @RequestParam("file") MultipartFile file) { - LocalStorage localStorage = localStorageService.create(name, file); - return new ResponseEntity<>(localStorage, HttpStatus.CREATED); + return new ResponseEntity<>(localStorageService.create(name, file), HttpStatus.CREATED); } @PostMapping("/pictures") @@ -78,8 +54,7 @@ public class LocalStorageController { if (!FileUtil.IMAGE.equals(FileUtil.getFileType(suffix))) { throw new BadRequestException("只能上传图片"); } - LocalStorage localStorage = localStorageService.create(null, file); - return new ResponseEntity<>(localStorage, HttpStatus.OK); + return new ResponseEntity<>(localStorageService.create(null, file), HttpStatus.OK); } @Log("修改文件") @@ -98,12 +73,4 @@ public class LocalStorageController { localStorageService.deleteAll(ids); return new ResponseEntity<>(HttpStatus.OK); } - - @ApiOperation("导入数据") - @PostMapping("/importExcel") - @SaIgnore - public ResponseEntity importExcel(@RequestBody String path) { - localStorageService.importExcel(path); - return new ResponseEntity<>(HttpStatus.OK); - } } diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/LocalStorageService.java b/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/LocalStorageService.java index ea1cbba36..ae9a7b143 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/LocalStorageService.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/LocalStorageService.java @@ -1,58 +1,25 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.nl.modules.tools.service; - +import com.alibaba.fastjson.JSONObject; import org.nl.modules.tools.domain.LocalStorage; -import org.nl.modules.tools.service.dto.LocalStorageDto; -import org.nl.modules.tools.service.dto.LocalStorageQueryCriteria; import org.springframework.data.domain.Pageable; import org.springframework.web.multipart.MultipartFile; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.List; +import java.util.Map; /** -* @author Zheng Jie -* @date 2019-09-05 -*/ + * @author: lyd + * @description: + * @Date: 2022/12/5 + */ public interface LocalStorageService { - /** - * 分页查询 - * @param criteria 条件 - * @param pageable 分页参数 - * @return / + * + * @param criteria + * @param pageable + * @return */ - Object queryAll(LocalStorageQueryCriteria criteria, Pageable pageable); - - /** - * 查询全部数据 - * @param criteria 条件 - * @return / - */ - List queryAll(LocalStorageQueryCriteria criteria); - - /** - * 根据ID查询 - * @param id / - * @return / - */ - LocalStorageDto findById(Long id); + Object queryAll(Map criteria, Pageable pageable); /** * 上传 @@ -60,7 +27,7 @@ public interface LocalStorageService { * @param file 文件 * @return */ - LocalStorage create(String name, MultipartFile file); + JSONObject create(String name, MultipartFile multipartFile); /** * 编辑 @@ -68,23 +35,17 @@ public interface LocalStorageService { */ void update(LocalStorage resources); + /** + * 通过id找文件信息 + * @param id + * @return + */ + JSONObject findById(String id); + /** * 多选删除 * @param ids / */ void deleteAll(Long[] ids); - /** - * 导出数据 - * @param localStorageDtos 待导出的数据 - * @param response / - * @throws IOException / - */ - void download(List localStorageDtos, HttpServletResponse response) throws IOException; - - /** - * 导入数据 - * @param path - */ - void importExcel(String path); -} \ No newline at end of file +} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/dto/LocalStorageDto.java b/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/dto/LocalStorageDto.java deleted file mode 100644 index 264a284f0..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/dto/LocalStorageDto.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.tools.service.dto; - -import lombok.Getter; -import lombok.Setter; -import org.nl.modules.common.base.BaseDTO; - -import java.io.Serializable; - -/** -* @author Zheng Jie -* @date 2019-09-05 -*/ -@Getter -@Setter -public class LocalStorageDto extends BaseDTO implements Serializable { - - private Long id; - - private String realName; - - private String name; - - private String suffix; - - private String type; - - private String size; -} \ No newline at end of file diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/dto/LocalStorageQueryCriteria.java b/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/dto/LocalStorageQueryCriteria.java deleted file mode 100644 index 00cc53072..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/dto/LocalStorageQueryCriteria.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.tools.service.dto; - -import lombok.Data; -import org.nl.modules.common.annotation.Query; - -import java.sql.Timestamp; -import java.util.List; - - -/** -* @author Zheng Jie -* @date 2019-09-05 -*/ -@Data -public class LocalStorageQueryCriteria{ - - @Query(blurry = "name,suffix,type,createBy,size") - private String blurry; - - @Query(type = Query.Type.BETWEEN) - private List createTime; -} \ No newline at end of file diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/impl/LocalStorageServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/impl/LocalStorageServiceImpl.java index e04a50cd2..12d9b8e69 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/impl/LocalStorageServiceImpl.java +++ b/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/impl/LocalStorageServiceImpl.java @@ -1,279 +1,144 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ package org.nl.modules.tools.service.impl; import cn.hutool.core.date.DateUtil; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; -import com.alibaba.excel.EasyExcel; -import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import lombok.RequiredArgsConstructor; import org.nl.modules.common.config.FileProperties; import org.nl.modules.common.exception.BadRequestException; -import org.nl.modules.common.utils.*; +import org.nl.modules.common.utils.FileUtil; import org.nl.modules.tools.domain.LocalStorage; -import org.nl.modules.tools.repository.LocalStorageRepository; import org.nl.modules.tools.service.LocalStorageService; -import org.nl.modules.tools.service.dto.LocalStorageDto; -import org.nl.modules.tools.service.dto.LocalStorageQueryCriteria; -import org.nl.modules.tools.service.mapstruct.LocalStorageMapper; -import org.nl.modules.wql.WQL; +import org.nl.modules.wql.core.bean.ResultBean; import org.nl.modules.wql.core.bean.WQLObject; +import org.nl.modules.wql.util.WqlUtil; import org.nl.sso.tools.SecurityUtils; -import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; -import javax.servlet.http.HttpServletResponse; import java.io.File; -import java.io.IOException; -import java.util.*; +import java.util.Map; /** - * @author Zheng Jie - * @date 2019-09-05 + * @author: lyd + * @description: + * @Date: 2022/12/5 */ @Service @RequiredArgsConstructor public class LocalStorageServiceImpl implements LocalStorageService { - private final LocalStorageRepository localStorageRepository; - private final LocalStorageMapper localStorageMapper; private final FileProperties properties; - + /** + * @param criteria + * @param pageable + * @return + */ @Override - public Object queryAll(LocalStorageQueryCriteria criteria, Pageable pageable) { - Page page = localStorageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable); - return PageUtil.toPage(page.map(localStorageMapper::toDto)); - } - - @Override - public List queryAll(LocalStorageQueryCriteria criteria) { - return localStorageMapper.toDto(localStorageRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder))); - } - - @Override - public LocalStorageDto findById(Long id) { - LocalStorage localStorage = localStorageRepository.findById(id).orElseGet(LocalStorage::new); - ValidationUtil.isNull(localStorage.getId(), "LocalStorage", "id", id); - return localStorageMapper.toDto(localStorage); + public Object queryAll(Map criteria, Pageable pageable) { + WQLObject toolTab = WQLObject.getWQLObject("tool_local_storage"); + String param = "1=1"; + if (ObjectUtil.isNotEmpty(criteria.get("blurry"))) { + param = param + " AND name = '%" + criteria.get("blurry").toString() + "%'"; + } + ResultBean rb = toolTab.pagequery(WqlUtil.getHttpContext(pageable), param, "create_time desc"); + final JSONObject json = rb.pageResult(); + return json; } + /** + * 上传 + * + * @param name 文件名称 + * @param multipartFile 文件 + * @return + */ @Override @Transactional(rollbackFor = Exception.class) - public LocalStorage create(String name, MultipartFile multipartFile) { + public JSONObject create(String name, MultipartFile multipartFile) { + WQLObject toolTab = WQLObject.getWQLObject("tool_local_storage"); FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize()); String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename()); String type = FileUtil.getFileType(suffix); - File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type + File.separator); - if (ObjectUtil.isNull(file)) { + File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type + File.separator); + if(ObjectUtil.isNull(file)){ throw new BadRequestException("上传失败"); } try { + Long userId = SecurityUtils.getCurrentUserId(); + String nickName = SecurityUtils.getCurrentNickName(); + String now = DateUtil.now(); name = StrUtil.isEmpty(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name; - LocalStorage localStorage = new LocalStorage( - file.getName(), - name, - suffix, - file.getPath(), - type, - FileUtil.getSize(multipartFile.getSize()) - ); - return localStorageRepository.save(localStorage); - } catch (Exception e) { + JSONObject localStorage = new JSONObject(); + localStorage.put("storage_id", IdUtil.getSnowflake(1,1).nextId()); + localStorage.put("real_name", file.getName()); + localStorage.put("name", name); + localStorage.put("suffix", suffix); + localStorage.put("path", file.getPath()); + localStorage.put("type", type); + localStorage.put("size", FileUtil.getSize(multipartFile.getSize())); + localStorage.put("create_id", userId); + localStorage.put("update_optid", userId); + localStorage.put("create_name", nickName); + localStorage.put("update_optname", nickName); + localStorage.put("create_time", now); + localStorage.put("update_time", now); + + toolTab.insert(localStorage); + return localStorage; + }catch (Exception e){ FileUtil.del(file); throw e; } } - @Override - @Transactional(rollbackFor = Exception.class) - public void update(LocalStorage resources) { - LocalStorage localStorage = localStorageRepository.findById(resources.getId()).orElseGet(LocalStorage::new); - ValidationUtil.isNull(localStorage.getId(), "LocalStorage", "id", resources.getId()); - localStorage.copy(resources); - localStorageRepository.save(localStorage); - } - - @Override - @Transactional(rollbackFor = Exception.class) - public void deleteAll(Long[] ids) { - for (Long id : ids) { - LocalStorage storage = localStorageRepository.findById(id).orElseGet(LocalStorage::new); - FileUtil.del(storage.getPath()); - localStorageRepository.delete(storage); - } - } - - @Override - public void download(List queryAll, HttpServletResponse response) throws IOException { - List> list = new ArrayList<>(); - for (LocalStorageDto localStorageDTO : queryAll) { - Map map = new LinkedHashMap<>(); - map.put("文件名", localStorageDTO.getRealName()); - map.put("备注名", localStorageDTO.getName()); - map.put("文件类型", localStorageDTO.getType()); - map.put("文件大小", localStorageDTO.getSize()); - map.put("创建者", localStorageDTO.getCreateBy()); - map.put("创建日期", localStorageDTO.getCreateTime()); - list.add(map); - } - FileUtil.downloadExcel(list, response); - } - /** - * 导入数据 + * 编辑 * - * @param path + * @param resources 文件信息 */ @Override @Transactional(rollbackFor = Exception.class) - public void importExcel(String path) { - WQLObject measureunitTab = WQLObject.getWQLObject("md_pb_measureunit"); - WQLObject materialbaseTab = WQLObject.getWQLObject("md_me_materialbase"); - Long currentUserId = SecurityUtils.getCurrentUserId(); - String nickName = SecurityUtils.getCurrentNickName(); - String now = DateUtil.now(); - List> listMap = EasyExcel.read(path).sheet(0).doReadSync(); -// listMap.remove(0); - for (int i = 2; i < 86; i++) { - Map map = listMap.get(i); - String package_box_sn = String.valueOf(map.get(17)); - String container_name = String.valueOf(map.get(9)); - String sale_order = String.valueOf(map.get(15)); - String no = String.valueOf(map.get(16)); - String customer_name = String.valueOf(map.get(21)); - String customer_description = String.valueOf(map.get(22)); - String product_name = String.valueOf(map.get(2)); - String product_description = String.valueOf(map.get(3)); - String date_of_FG_inbound = String.valueOf(map.get(11)); - String width = String.valueOf(map.get(23)); - String thickness = String.valueOf(map.get(24)); - String net_weight = String.valueOf(map.get(4)); - String length = String.valueOf(map.get(26)); - String is_un_plan_production = String.valueOf(map.get(27)); + public void update(LocalStorage resources) { + JSONObject entity = this.findById(resources.getCreate_id()); + if (ObjectUtil.isEmpty(entity)) throw new BadRequestException("文件信息不存在"); + WQLObject toolTab = WQLObject.getWQLObject("tool_local_storage"); + JSONObject json = JSONObject.parseObject(JSON.toJSONString(resources)); + toolTab.update(json); + } - if (StrUtil.isEmpty(package_box_sn)) { - throw new BadRequestException("第" + (i + 2) + "行的木箱唯一码为空!"); - } - if (StrUtil.isEmpty(sale_order)) { - throw new BadRequestException("第" + (i + 2) + "行的销售订单及行号为空!"); - } - if (StrUtil.isEmpty(customer_name)) { - throw new BadRequestException("第" + (i + 2) + "行的客户编号为空!"); - } - if (StrUtil.isEmpty(customer_description)) { - throw new BadRequestException("第" + (i + 2) + "行的客户名称为空!"); - } - if (StrUtil.isEmpty(product_name)) { - throw new BadRequestException("第" + (i + 2) + "行的产品编码为空!"); - } - if (StrUtil.isEmpty(product_description)) { - throw new BadRequestException("第" + (i + 2) + "行的产品描述为空!"); - } - if (StrUtil.isEmpty(container_name)) { - throw new BadRequestException("第" + (i + 2) + "行的子卷号为空!"); - } - if (StrUtil.isEmpty(width)) { - throw new BadRequestException("第" + (i + 2) + "行的产品规格(幅宽)为空!"); - } - if (StrUtil.isEmpty(net_weight)) { - throw new BadRequestException("第" + (i + 2) + "行的净重为空!"); - } - if (StrUtil.isEmpty(length)) { - throw new BadRequestException("第" + (i + 2) + "行的长度为空!"); - } - if (StrUtil.isEmpty(is_un_plan_production)) { - throw new BadRequestException("第" + (i + 2) + "行的计划外分切的子卷为空!"); - } + /** + * 通过id找文件信息 + * + * @param id + * @return + */ + @Override + public JSONObject findById(String id) { + WQLObject toolTab = WQLObject.getWQLObject("tool_local_storage"); + JSONObject object = toolTab.query("storage_id = '" + id + "'").uniqueResult(0); + return object; + } - String material_code = String.valueOf(map.get(5)); - if (StrUtil.isEmpty(material_code)) { - continue; - } - JSONObject jo = new JSONObject(); - jo.put("workorder_id", IdUtil.getSnowflake(1, 1).nextId()); - jo.put("package_box_sn", package_box_sn); - jo.put("sap_pcsn", container_name); -// jo.put("box_weight", BoxWeight); - jo.put("quality_guaran_period", "90"); - jo.put("sale_order_name", sale_order + "-" + no); - jo.put("customer_name", customer_name); - jo.put("customer_description", customer_description); - jo.put("product_name", product_name); - jo.put("product_description", product_description); - jo.put("date_of_FG_inbound", date_of_FG_inbound); - jo.put("container_name", container_name); - jo.put("width", width); - jo.put("thickness", thickness); - jo.put("net_weight", net_weight); - jo.put("length", length); - jo.put("date_of_production", date_of_FG_inbound); - jo.put("is_un_plan_production", is_un_plan_production); - jo.put("status", "0"); - jo.put("create_id", "1"); - jo.put("create_name", "管理员"); - jo.put("create_time", DateUtil.now()); - WQLObject tab = WQLObject.getWQLObject("PDM_BI_SubPackageRelation"); - tab.insert(jo); - } - - JSONArray rows = WQL.getWO("ST_REGION_IN_01").addParam("flag", "3").process().getResultJSONArray(0); - for (int i = 0; i < rows.size(); i++) { - JSONObject row = rows.getJSONObject(i); - String package_box_sn = row.getString("package_box_sn"); - double total_weight = 0; - JSONArray box_rows = WQLObject.getWQLObject("pdm_bi_subpackagerelation").query("package_box_sn = '"+package_box_sn+"'").getResultJSONArray(0); - //查询一个空的虚拟区货位 - JSONObject struct = WQL.getWO("PDA_ST_01").addParam("flag", "3").process().uniqueResult(0); - for (int j = 0; j < box_rows.size(); j++) { - JSONObject box_row = box_rows.getJSONObject(j); - JSONObject ivt_jo = new JSONObject(); - //插入库存数据 - ivt_jo.put("stockrecord_id",IdUtil.getSnowflake(1,1).nextId()); - ivt_jo.put("struct_id",struct.getString("struct_id")); - ivt_jo.put("struct_code",struct.getString("struct_code")); - ivt_jo.put("struct_name",struct.getString("struct_name")); - ivt_jo.put("region_id",""); - ivt_jo.put("quality_scode","01"); - ivt_jo.put("pcsn",box_row.getString("container_name")); - ivt_jo.put("canuse_qty",box_row.getString("net_weight")); - ivt_jo.put("frozen_qty",0); - ivt_jo.put("ivt_qty",box_row.getString("net_weight")); - ivt_jo.put("instorage_time",DateUtil.now()); - JSONObject mater = WQLObject.getWQLObject("md_me_materialbase").query("material_code = '"+box_row.getString("product_name")+"'").uniqueResult(0); - ivt_jo.put("material_id",mater.getString("material_id")); - ivt_jo.put("qty_unit_id",mater.getString("base_unit_id")); - WQLObject.getWQLObject("st_ivt_structivt").insert(ivt_jo); - total_weight += box_row.getDoubleValue("net_weight"); - } - - //更新总重量 - HashMap sub_map = new HashMap<>(); - sub_map.put("box_weight",total_weight+""); - sub_map.put("status","2"); - WQLObject.getWQLObject("pdm_bi_subpackagerelation").update(sub_map,"package_box_sn = '"+package_box_sn+"'"); - - //更新仓位字段 - struct.put("storagevehicle_code",package_box_sn); - WQLObject.getWQLObject("st_ivt_structattr").update(struct); + /** + * 多选删除 + * + * @param ids / + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void deleteAll(Long[] ids) { + WQLObject toolTab = WQLObject.getWQLObject("tool_local_storage"); + for (Long id : ids) { + JSONObject storage = this.findById(id.toString()); + if (ObjectUtil.isEmpty(storage)) continue; + FileUtil.del(storage.getString("path")); + toolTab.delete(storage); } } } diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/mapstruct/LocalStorageMapper.java b/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/mapstruct/LocalStorageMapper.java deleted file mode 100644 index f1b3b6984..000000000 --- a/lms/nladmin-system/src/main/java/org/nl/modules/tools/service/mapstruct/LocalStorageMapper.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.tools.service.mapstruct; - - -import org.mapstruct.Mapper; -import org.mapstruct.ReportingPolicy; -import org.nl.modules.common.base.BaseMapper; -import org.nl.modules.tools.domain.LocalStorage; -import org.nl.modules.tools.service.dto.LocalStorageDto; - -/** -* @author Zheng Jie -* @date 2019-09-05 -*/ -@Mapper(componentModel = "spring",unmappedTargetPolicy = ReportingPolicy.IGNORE) -public interface LocalStorageMapper extends BaseMapper { - -} \ No newline at end of file diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/generator/domain/ColumnInfo.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/domain/ColumnInfo.java new file mode 100644 index 000000000..87d982bf5 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/domain/ColumnInfo.java @@ -0,0 +1,78 @@ +package org.nl.sso.generator.domain; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import org.nl.sso.generator.utils.GenUtil; + +import java.io.Serializable; + +/** + * @author: lyd + * @description: + * @Date: 2022/12/2 + */ +@Data +public class ColumnInfo implements Serializable { + + /** 防止精度丢失 */ + @JsonSerialize(using= ToStringSerializer.class) + private Long column_id; + + @ApiModelProperty(value = "表名") + private String table_name; + + @ApiModelProperty(value = "数据库字段名称") + private String column_name; + + @ApiModelProperty(value = "数据库字段类型") + private String column_type; + + @ApiModelProperty(value = "数据库字段键类型") + private String key_type; + + @ApiModelProperty(value = "字段额外的参数") + private String extra; + + @ApiModelProperty(value = "数据库字段描述") + private String remark; + + @ApiModelProperty(value = "是否必填") + private String not_null; + + @ApiModelProperty(value = "是否在列表显示") + private String list_show; + + @ApiModelProperty(value = "是否表单显示") + private String form_show; + + @ApiModelProperty(value = "表单类型") + private String form_type; + + @ApiModelProperty(value = "查询 1:模糊 2:精确") + private String query_type; + + @ApiModelProperty(value = "字典名称") + private String dict_name; + + @ApiModelProperty(value = "日期注解") + private String date_annotation; + + public ColumnInfo(String tableName, Long column_id, String columnName, Boolean notNull, String columnType, String remark, String keyType, String extra) { + this.table_name = tableName; + this.column_id = column_id; + this.column_name = columnName; + this.column_type = columnType; + this.key_type = keyType; + this.extra = extra; + this.not_null = notNull?"1":"0"; + if(GenUtil.PK.equalsIgnoreCase(keyType) && GenUtil.EXTRA.equalsIgnoreCase(extra)){ + this.not_null = "0"; + } + this.remark = remark; + this.list_show = "1"; + this.form_show = "1"; + } +} + diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/generator/domain/GenConfig.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/domain/GenConfig.java new file mode 100644 index 000000000..9454756b3 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/domain/GenConfig.java @@ -0,0 +1,55 @@ +package org.nl.sso.generator.domain; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; + +import javax.validation.constraints.NotBlank; +import java.io.Serializable; + +/** + * @author: lyd + * @description: code_gen_config + * @Date: 2022/12/2 + */ +@Data +public class GenConfig implements Serializable { + public GenConfig(String tableName) { + this.table_name = tableName; + } + /** 防止精度丢失 */ + @JsonSerialize(using= ToStringSerializer.class) + private Long config_id; + + @NotBlank + @ApiModelProperty(value = "表名") + private String table_name; + + @ApiModelProperty(value = "接口名称") + private String api_alias; + + @NotBlank + @ApiModelProperty(value = "包路径") + private String pack; + + @NotBlank + @ApiModelProperty(value = "模块名") + private String module_name; + + @NotBlank + @ApiModelProperty(value = "前端文件路径") + private String path; + + @ApiModelProperty(value = "前端文件路径") + private String api_path; + + @ApiModelProperty(value = "作者") + private String author; + + @ApiModelProperty(value = "表前缀") + private String prefix; + + @ApiModelProperty(value = "是否覆盖") + private String cover = "0"; +} diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/generator/domain/vo/TableInfo.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/domain/vo/TableInfo.java new file mode 100644 index 000000000..b6e0d6502 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/domain/vo/TableInfo.java @@ -0,0 +1,33 @@ +package org.nl.sso.generator.domain.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * @author: lyd + * @description: 表的数据信息 + * @Date: 2022/12/2 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class TableInfo { + + /** 表名称 */ + private Object tableName; + + /** 创建日期 */ + private Object createTime; + + /** 数据库引擎 */ + private Object engine; + + /** 编码集 */ + private Object coding; + + /** 备注 */ + private Object remark; + + +} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GenConfigController.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/rest/GenConfigController.java similarity index 52% rename from lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GenConfigController.java rename to lms/nladmin-system/src/main/java/org/nl/sso/generator/rest/GenConfigController.java index 75ee5b512..a40c47bd2 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GenConfigController.java +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/rest/GenConfigController.java @@ -1,40 +1,25 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.rest; +package org.nl.sso.generator.rest; +import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; -import org.nl.modules.generator.domain.GenConfig; -import org.nl.modules.generator.service.GenConfigService; +import org.nl.sso.generator.service.GenConfigService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; /** - * @author Zheng Jie - * @date 2019-01-14 + * @author: lyd + * @description: 代码生成器配置管理 + * @Date: 2022/12/2 */ @RestController @RequiredArgsConstructor @RequestMapping("/api/genConfig") @Api(tags = "系统:代码生成器配置管理") public class GenConfigController { - private final GenConfigService genConfigService; @ApiOperation("查询") @@ -45,7 +30,7 @@ public class GenConfigController { @ApiOperation("修改") @PutMapping - public ResponseEntity update(@Validated @RequestBody GenConfig genConfig){ - return new ResponseEntity<>(genConfigService.update(genConfig.getTableName(), genConfig),HttpStatus.OK); + public ResponseEntity update(@Validated @RequestBody JSONObject genConfig){ + return new ResponseEntity<>(genConfigService.update(genConfig),HttpStatus.OK); } } diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GeneratorController.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/rest/GeneratorController.java similarity index 66% rename from lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GeneratorController.java rename to lms/nladmin-system/src/main/java/org/nl/sso/generator/rest/GeneratorController.java index 10238435f..805c206a8 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/rest/GeneratorController.java +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/rest/GeneratorController.java @@ -1,29 +1,14 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.rest; +package org.nl.sso.generator.rest; +import com.alibaba.fastjson.JSONArray; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import org.nl.modules.common.exception.BadRequestException; -import org.nl.modules.common.utils.PageUtil; -import org.nl.modules.generator.domain.ColumnInfo; -import org.nl.modules.generator.service.GenConfigService; -import org.nl.modules.generator.service.GeneratorService; +import org.nl.sso.generator.service.GenConfigService; +import org.nl.sso.generator.service.GeneratorService; import org.springframework.beans.factory.annotation.Value; +import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @@ -33,15 +18,15 @@ import javax.servlet.http.HttpServletResponse; import java.util.List; /** - * @author Zheng Jie - * @date 2019-01-02 + * @author: lyd + * @description: 代码生成管理 + * @Date: 2022/12/2 */ @RestController @RequiredArgsConstructor @RequestMapping("/api/generator") @Api(tags = "系统:代码生成管理") public class GeneratorController { - private final GeneratorService generatorService; private final GenConfigService genConfigService; @@ -57,22 +42,19 @@ public class GeneratorController { @ApiOperation("查询数据库数据") @GetMapping(value = "/tables") public ResponseEntity queryTables(@RequestParam(defaultValue = "") String name, - @RequestParam(defaultValue = "0")Integer page, - @RequestParam(defaultValue = "10")Integer size){ - int[] startEnd = PageUtil.transToStartEnd(page, size); - return new ResponseEntity<>(generatorService.getTables(name,startEnd), HttpStatus.OK); + Pageable pageable){ + return new ResponseEntity<>(generatorService.getTables(name,pageable), HttpStatus.OK); } @ApiOperation("查询字段数据") @GetMapping(value = "/columns") public ResponseEntity queryColumns(@RequestParam String tableName){ - List columnInfos = generatorService.getColumns(tableName); - return new ResponseEntity<>(PageUtil.toPage(columnInfos,columnInfos.size()), HttpStatus.OK); + return new ResponseEntity<>(generatorService.getColumns(tableName), HttpStatus.OK); } @ApiOperation("保存字段数据") @PutMapping - public ResponseEntity save(@RequestBody List columnInfos){ + public ResponseEntity save(@RequestBody JSONArray columnInfos){ generatorService.save(columnInfos); return new ResponseEntity<>(HttpStatus.OK); } @@ -95,14 +77,15 @@ public class GeneratorController { switch (type){ // 生成代码 case 0: generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(tableName)); - break; + break; // 预览 case 1: return generatorService.preview(genConfigService.find(tableName), generatorService.getColumns(tableName)); - // 打包 + // 下载 case 2: generatorService.download(genConfigService.find(tableName), generatorService.getColumns(tableName), request, response); - break; + break; default: throw new BadRequestException("没有这个选项"); } return new ResponseEntity<>(HttpStatus.OK); } + } diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/GenConfigService.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/GenConfigService.java new file mode 100644 index 000000000..7c1be1fcc --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/GenConfigService.java @@ -0,0 +1,24 @@ +package org.nl.sso.generator.service; + +import com.alibaba.fastjson.JSONObject; + +/** + * @author: lyd + * @description: + * @Date: 2022/12/2 + */ +public interface GenConfigService { + /** + * 查询表配置 + * @param tableName 表名 + * @return 表配置 + */ + JSONObject find(String tableName); + + /** + * 更新表配置 + * @param genConfig 表配置 + * @return 表配置 + */ + JSONObject update(JSONObject genConfig); +} diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/GeneratorService.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/GeneratorService.java new file mode 100644 index 000000000..392f6375f --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/GeneratorService.java @@ -0,0 +1,85 @@ +package org.nl.sso.generator.service; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import org.springframework.data.domain.Pageable; +import org.springframework.http.ResponseEntity; +import org.springframework.scheduling.annotation.Async; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author: lyd + * @description: + * @Date: 2022/12/2 + */ +public interface GeneratorService { + + /** + * 查询数据库元数据 + * @param name 表名 + * @param pageable 分页参数 + * @return / + */ + Object getTables(String name, Pageable pageable); + + /** + * 得到数据表的元数据 + * @param name 表名 + * @return / + */ + JSONObject getColumns(String name); + + /** + * 同步表数据 + * @param columnInfos / content + * @param columnInfoList / + */ + @Async + void sync(JSONObject columnInfos, JSONArray columnInfoList); + + + /** + * 获取所有table + * @return / + */ + Object getTables(); + + /** + * 查询数据库的表字段数据数据 + * @param table / + * @return / + */ + JSONArray query(String table); + + /** + * 保存字段 + * @param columnInfos + */ + void save(JSONArray columnInfos); + + /** + * 预览 + * @param genConfig 配置信息 + * @param columns 字段信息 数组存在content + * @return / + */ + ResponseEntity preview(JSONObject genConfig, JSONObject columns); + + /** + * 代码生成 + * @param genConfig 配置信息 + * @param columns 字段信息 数组存在content + */ + void generator(JSONObject genConfig, JSONObject columns); + + /** + * 打包下载 + * @param genConfig 配置信息 + * @param columns 字段信息 数组存在content + * @param request / + * @param response / + */ + void download(JSONObject genConfig, JSONObject columns, HttpServletRequest request, HttpServletResponse response); +} diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/impl/GenConfigServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/impl/GenConfigServiceImpl.java new file mode 100644 index 000000000..4fe1ada9c --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/impl/GenConfigServiceImpl.java @@ -0,0 +1,54 @@ +package org.nl.sso.generator.service.impl; + +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import com.alibaba.fastjson.JSONObject; +import lombok.RequiredArgsConstructor; +import org.nl.sso.generator.domain.GenConfig; +import org.nl.sso.generator.service.GenConfigService; +import org.nl.modules.wql.core.bean.WQLObject; +import org.springframework.stereotype.Service; + +/** + * @author: lyd + * @description: + * @Date: 2022/12/2 + */ +@Service +@RequiredArgsConstructor +public class GenConfigServiceImpl implements GenConfigService { + /** + * 查询表配置 + * + * @param tableName 表名 + * @return 表配置 + */ + @Override + public JSONObject find(String tableName) { + WQLObject genTab = WQLObject.getWQLObject("code_gen_config"); + JSONObject jsonObject = genTab.query("table_name = '" + tableName + "'").uniqueResult(0); + if (ObjectUtil.isEmpty(jsonObject)) + return JSONObject.parseObject(JSONObject.toJSONString(new GenConfig(tableName))); + return jsonObject; + } + + /** + * 更新表配置 + * + * @param genConfig 表名 + 表配置 + * @return 表配置 + */ + @Override + public JSONObject update(JSONObject genConfig) { + WQLObject genTab = WQLObject.getWQLObject("code_gen_config"); + if (ObjectUtil.isEmpty(genConfig.getString("config_id"))) { + // 创建 + genConfig.put("config_id", IdUtil.getSnowflake(1, 1).nextId()); + genTab.insert(genConfig); + } else { + // 更新 + genTab.update(genConfig); + } + return genConfig; + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/impl/GeneratorServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/impl/GeneratorServiceImpl.java new file mode 100644 index 000000000..5c625d710 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/service/impl/GeneratorServiceImpl.java @@ -0,0 +1,242 @@ +package org.nl.sso.generator.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.core.util.ZipUtil; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import lombok.RequiredArgsConstructor; +import org.nl.modules.common.exception.BadRequestException; +import org.nl.modules.common.utils.FileUtil; +import org.nl.sso.generator.domain.ColumnInfo; +import org.nl.sso.generator.service.GeneratorService; +import org.nl.sso.generator.utils.GenUtil; +import org.nl.modules.wql.WQL; +import org.nl.modules.wql.core.bean.WQLObject; +import org.nl.modules.wql.util.WqlUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Service; + +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; + +/** + * @author: lyd + * @description: + * @Date: 2022/12/2 + */ +@Service +@RequiredArgsConstructor +public class GeneratorServiceImpl implements GeneratorService { + private static final Logger log = LoggerFactory.getLogger(GeneratorServiceImpl.class); + + @PersistenceContext + private EntityManager em; + /** + * 查询数据库元数据 + * + * @param name 表名 + * @param pageable 分页参数 + * @return / + */ + @Override + public Object getTables(String name, Pageable pageable) { + JSONObject map = new JSONObject(); + map.put("flag", "1"); + map.put("table_name", name); + JSONObject json = WQL.getWO("Generator").addParamMap(map).pageQuery(WqlUtil.getHttpContext(pageable), "create_time desc"); + return json; + } + + /** + * 得到数据表的元数据 + * + * @param name 表名 + * @return / + */ + @Override + public JSONObject getColumns(String name) { + WQLObject colTab = WQLObject.getWQLObject("code_column_config"); + JSONObject content = new JSONObject(); + JSONArray array = colTab.query("table_name = '" + name + "'").getResultJSONArray(0); + if (ObjectUtil.isEmpty(array)) { + array = query(name); + // 保存 + for (int i = 0; i < array.size(); i++) { + JSONObject jsonObject = array.getJSONObject(i); + colTab.insert(jsonObject); + } + } + content.put("content", array); + return content; + } + + /** + * 同步表数据 + * + * @param content / + * @param columnInfoList / + */ + @Override + public void sync(JSONObject content, JSONArray columnInfoList) { + WQLObject colTab = WQLObject.getWQLObject("code_column_config"); + JSONArray columnInfos = content.getJSONArray("content"); + // 第一种情况,数据库类字段改变或者新增字段 + for (int i = 0; i < columnInfoList.size(); i++) { + JSONObject columnInfoObj = columnInfoList.getJSONObject(i); + JSONArray columns = new JSONArray(); + for (int j = 0; j < columnInfos.size(); j++) { + JSONObject columnInfosObj = columnInfos.getJSONObject(j); + if (columnInfoObj.getString("column_name").equals(columnInfosObj.getString("column_name"))) { + columns.add(columnInfosObj); + } + } + // 如果能找到,就修改部分可能被字段 + if (CollectionUtil.isNotEmpty(columns)) { + JSONObject column = columns.getJSONObject(0); + column.put("column_type", columnInfoObj.getString("column_type")); + column.put("extra", columnInfoObj.getString("extra")); + column.put("key_type", columnInfoObj.getString("key_type")); + if (StrUtil.isEmpty(column.getString("remark"))) { + column.put("remark", columnInfoObj.getString("remark")); + } + colTab.update(column); + } else { + // 如果找不到,则保存新字段信息 + colTab.insert(columnInfoObj); + } + } + // 第二种情况,数据库字段删除了 + for (int k = 0; k < columnInfos.size(); k++) { + JSONArray columns = new JSONArray(); + JSONObject columnInfo = columnInfos.getJSONObject(k); + for (int l = 0; l < columnInfoList.size(); l++) { + JSONObject c = columnInfoList.getJSONObject(l); + if (columnInfo.getString("column_name").equals(c.getString("column_name"))) { + columns.add(c); + } + } + if (ObjectUtil.isEmpty(columnInfo)) colTab.delete(columnInfo); + } + } + + @Override + public JSONArray query(String tableName) { + JSONObject map = new JSONObject(); + map.put("flag", "2"); + map.put("table_name", tableName); + JSONArray generator = WQL.getWO("Generator").addParamMap(map).process().getResultJSONArray(0); + JSONArray columnInfos = new JSONArray(); + for (int i = 0; i < generator.size(); i++) { + JSONObject obj = generator.getJSONObject(i); + columnInfos.add( + JSONObject.parseObject(JSON.toJSONString(new ColumnInfo( + tableName, + IdUtil.getSnowflake(1,1).nextId(), + obj.getString("column_name"), + "NO".equals(obj.getString("is_nullable")), + obj.getString("data_type"), + ObjectUtil.isNotEmpty(obj.getString("column_comment")) ? obj.getString("column_comment") : null, + ObjectUtil.isNotEmpty(obj.getString("column_key")) ? obj.getString("column_key") : null, + ObjectUtil.isNotEmpty(obj.getString("extra")) ? obj.getString("extra") : null + ))) + ); + } + return columnInfos; + } + + /** + * 保存字段 + * + * @param columnInfos + */ + @Override + public void save(JSONArray columnInfos) { + WQLObject colTab = WQLObject.getWQLObject("code_column_config"); + for (int i = 0; i < columnInfos.size(); i++) { + JSONObject object = columnInfos.getJSONObject(i); + colTab.update(object); + } + } + + /** + * 预览 + * + * @param genConfig 配置信息 + * @param columns 字段信息 数组存在content + * @return / + */ + @Override + public ResponseEntity preview(JSONObject genConfig, JSONObject columns) { + JSONArray column = columns.getJSONArray("content"); + if (ObjectUtil.isEmpty(genConfig.getString("config_id"))) throw new BadRequestException("请先配置生成器"); + JSONArray genList = GenUtil.preview(column, genConfig); + return new ResponseEntity<>(genList, HttpStatus.OK); + } + + /** + * 代码生成 + * + * @param genConfig 配置信息 + * @param columns 字段信息 数组存在content + */ + @Override + public void generator(JSONObject genConfig, JSONObject columns) { + JSONArray column = columns.getJSONArray("content"); + if (ObjectUtil.isEmpty(genConfig.getString("config_id"))) throw new BadRequestException("请先配置生成器"); + try { + GenUtil.generatorCode(column, genConfig); + } catch (IOException e) { + log.error(e.getMessage(), e); + throw new BadRequestException("生成失败,请手动处理已生成的文件"); + } + } + + /** + * 打包下载 + * + * @param genConfig 配置信息 + * @param columns 字段信息 数组存在content + * @param request / + * @param response / + */ + @Override + public void download(JSONObject genConfig, JSONObject columns, HttpServletRequest request, HttpServletResponse response) { + JSONArray column = columns.getJSONArray("content"); + if (ObjectUtil.isEmpty(genConfig.getString("config_id"))) throw new BadRequestException("请先配置生成器"); + try { + File file = new File(GenUtil.download(column, genConfig)); + String zipPath = file.getPath() + ".zip"; + ZipUtil.zip(file.getPath(), zipPath); + FileUtil.downloadFile(request, response, new File(zipPath), true); + } catch (IOException e) { + throw new BadRequestException("下载失败"); + } + } + + /** + * 获取所有table + * + * @return / + */ + @Override + public Object getTables() { + // 使用预编译防止sql注入 + JSONObject map = new JSONObject(); + map.put("flag", "1"); + JSONArray generator = WQL.getWO("Generator").addParamMap(map).process().getResultJSONArray(0); + return generator; + } + +} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/ColUtil.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/utils/ColUtil.java similarity index 57% rename from lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/ColUtil.java rename to lms/nladmin-system/src/main/java/org/nl/sso/generator/utils/ColUtil.java index ff5a97192..b441b616e 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/ColUtil.java +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/utils/ColUtil.java @@ -1,19 +1,4 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.utils; +package org.nl.sso.generator.utils; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; @@ -22,10 +7,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * sql字段转java - * - * @author Zheng Jie - * @date 2019-01-03 + * @author: lyd + * @description: sql字段转java + * @Date: 2022/12/3 */ public class ColUtil { private static final Logger log = LoggerFactory.getLogger(ColUtil.class); diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/GenUtil.java b/lms/nladmin-system/src/main/java/org/nl/sso/generator/utils/GenUtil.java similarity index 72% rename from lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/GenUtil.java rename to lms/nladmin-system/src/main/java/org/nl/sso/generator/utils/GenUtil.java index 46bcf3bd2..42ff16ca7 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/generator/utils/GenUtil.java +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/utils/GenUtil.java @@ -1,27 +1,12 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.generator.utils; +package org.nl.sso.generator.utils; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.template.*; +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.nl.modules.common.utils.FileUtil; import org.nl.modules.common.utils.StringUtils; -import org.nl.modules.generator.domain.ColumnInfo; -import org.nl.modules.generator.domain.GenConfig; import org.springframework.util.ObjectUtils; import java.io.File; @@ -36,19 +21,18 @@ import java.util.Map; import static org.nl.modules.common.utils.FileUtil.SYS_TEM_DIR; - /** - * 代码生成 - * - * @author Zheng Jie - * @date 2019-01-02 + * @author: lyd + * @description: 代码生成 + * @Date: 2022/12/2 */ @Slf4j @SuppressWarnings({"unchecked", "all"}) public class GenUtil { - private static final String TIMESTAMP = "Timestamp"; + private static final String Date = "Date"; + private static final String BIGDECIMAL = "BigDecimal"; public static final String PK = "PRI"; @@ -62,14 +46,14 @@ public class GenUtil { */ private static List getAdminTemplateNames() { List templateNames = new ArrayList<>(); - // templateNames.add("Entity"); + // templateNames.add("Entity"); templateNames.add("Dto"); - // templateNames.add("Mapper"); + // templateNames.add("Mapper"); templateNames.add("Controller"); //templateNames.add("QueryCriteria"); templateNames.add("Service"); templateNames.add("ServiceImpl"); - // templateNames.add("Repository"); + // templateNames.add("Repository"); return templateNames; } @@ -85,9 +69,9 @@ public class GenUtil { return templateNames; } - public static List> preview(List columns, GenConfig genConfig) { - Map genMap = getGenMap(columns, genConfig); - List> genList = new ArrayList<>(); + public static JSONArray preview(JSONArray columns, JSONObject genConfig) { + JSONObject genMap = getGenMap(columns, genConfig); + JSONArray genList = new JSONArray(); // 获取后端模版 List templates = getAdminTemplateNames(); TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); @@ -111,48 +95,8 @@ public class GenUtil { return genList; } - public static String download(List columns, GenConfig genConfig) throws IOException { - // 拼接的路径:/tmpnladmin-gen-temp/,这个路径在Linux下需要root用户才有权限创建,非root用户会权限错误而失败,更改为: /tmp/nladmin-gen-temp/ - // String tempPath =SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; - String tempPath = SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; - Map genMap = getGenMap(columns, genConfig); - TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); - // 生成后端代码 - List templates = getAdminTemplateNames(); - for (String templateName : templates) { - Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); - String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), tempPath + "eladmin" + File.separator); - assert filePath != null; - File file = new File(filePath); - // 如果非覆盖生成 - if (!genConfig.getCover() && FileUtil.exist(file)) { - continue; - } - // 生成代码 - genFile(file, template, genMap); - } - // 生成前端代码 - templates = getFrontTemplateNames(); - for (String templateName : templates) { - Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); - String path = tempPath + "nladmin-web" + File.separator; - String apiPath = path + "src" + File.separator + "api" + File.separator; - String srcPath = path + "src" + File.separator + "views" + File.separator + genMap.get("changeClassName").toString() + File.separator; - String filePath = getFrontFilePath(templateName, apiPath, srcPath, genMap.get("changeClassName").toString()); - assert filePath != null; - File file = new File(filePath); - // 如果非覆盖生成 - if (!genConfig.getCover() && FileUtil.exist(file)) { - continue; - } - // 生成代码 - genFile(file, template, genMap); - } - return tempPath; - } - - public static void generatorCode(List columnInfos, GenConfig genConfig) throws IOException { - Map genMap = getGenMap(columnInfos, genConfig); + public static void generatorCode(JSONArray columns, JSONObject genConfig) throws IOException { + JSONObject genMap = getGenMap(columns, genConfig); TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); // 生成后端代码 List templates = getAdminTemplateNames(); @@ -164,24 +108,24 @@ public class GenUtil { File file = new File(filePath); // 如果非覆盖生成 - if (!genConfig.getCover() && FileUtil.exist(file)) { + if (!genConfig.getString("cover").equals("1") && FileUtil.exist(file)) { continue; } // 生成代码 genFile(file, template, genMap); } - // 生成前端代码 templates = getFrontTemplateNames(); for (String templateName : templates) { Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); - String filePath = getFrontFilePath(templateName, genConfig.getApiPath(), genConfig.getPath(), genMap.get("changeClassName").toString()); + // api 和 vue文件都放一起,所以这里不需要传api_path + String filePath = getFrontFilePath(templateName, genConfig.getString("path"), genConfig.getString("path"), genMap.get("changeClassName").toString()); assert filePath != null; File file = new File(filePath); // 如果非覆盖生成 - if (!genConfig.getCover() && FileUtil.exist(file)) { + if (!genConfig.getString("cover").equals("1") && FileUtil.exist(file)) { continue; } // 生成代码 @@ -189,175 +133,60 @@ public class GenUtil { } } - // 获取模版数据 - private static Map getGenMap(List columnInfos, GenConfig genConfig) { - // 存储模版字段数据 - Map genMap = new HashMap<>(16); - // 接口别名 - genMap.put("apiAlias", genConfig.getApiAlias()); - // 包名称 - genMap.put("package", genConfig.getPack()); - // 模块名称 - genMap.put("moduleName", genConfig.getModuleName()); - // 作者 - genMap.put("author", genConfig.getAuthor()); - // 创建日期 - genMap.put("date", LocalDate.now().toString()); - // 表名 - genMap.put("tableName", genConfig.getTableName()); - // 大写开头的类名 - String className = StringUtils.toCapitalizeCamelCase(genConfig.getTableName()); - // 小写开头的类名 - String changeClassName = StringUtils.toCamelCase(genConfig.getTableName()); - // 判断是否去除表前缀 - if (StrUtil.isNotEmpty(genConfig.getPrefix())) { - className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); - changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getTableName(), genConfig.getPrefix())); + // 下载 + public static String download(JSONArray columns, JSONObject genConfig) throws IOException { + // 拼接的路径:/tmpnladmin-gen-temp/,这个路径在Linux下需要root用户才有权限创建,非root用户会权限错误而失败,更改为: /tmp/nladmin-gen-temp/ + // String tempPath =SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getTableName() + File.separator; + String tempPath = SYS_TEM_DIR + "nladmin-gen-temp" + File.separator + genConfig.getString("table_name") + File.separator; + JSONObject genMap = getGenMap(columns, genConfig); + TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH)); + // 生成后端代码 + List templates = getAdminTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/admin/" + templateName + ".ftl"); + String filePath = getAdminFilePath(templateName, genConfig, genMap.get("className").toString(), tempPath + "eladmin" + File.separator); + assert filePath != null; + File file = new File(filePath); + // 如果非覆盖生成 + if (!genConfig.getString("cover").equals("1") && FileUtil.exist(file)) { + continue; + } + // 生成代码 + genFile(file, template, genMap); } - // 保存类名 - genMap.put("className", className); - // 保存小写开头的类名 - genMap.put("changeClassName", changeClassName); - // 存在 Timestamp 字段 - genMap.put("hasTimestamp", false); - // 查询类中存在 Timestamp 字段 - genMap.put("queryHasTimestamp", false); - // 存在 BigDecimal 字段 - genMap.put("hasBigDecimal", false); - // 查询类中存在 BigDecimal 字段 - genMap.put("queryHasBigDecimal", false); - // 是否需要创建查询 - genMap.put("hasQuery", false); - // 自增主键 - genMap.put("auto", false); - // 存在字典 - genMap.put("hasDict", false); - // 存在日期注解 - genMap.put("hasDateAnnotation", false); - // 保存字段信息 - List> columns = new ArrayList<>(); - // 保存查询字段的信息 - List> queryColumns = new ArrayList<>(); - // 存储字典信息 - List dicts = new ArrayList<>(); - // 存储 between 信息 - List> betweens = new ArrayList<>(); - // 存储不为空的字段信息 - List> isNotNullColumns = new ArrayList<>(); + // 生成前端代码 + templates = getFrontTemplateNames(); + for (String templateName : templates) { + Template template = engine.getTemplate("generator/front/" + templateName + ".ftl"); + // api 和 vue文件都放一起,所以这里不需要传api_path + String filePath = getFrontFilePath(templateName, genConfig.getString("path"), genConfig.getString("path"), genMap.get("changeClassName").toString()); - for (ColumnInfo column : columnInfos) { - Map listMap = new HashMap<>(16); - // 字段描述 - listMap.put("remark", column.getRemark()); - // 字段类型 - listMap.put("columnKey", column.getKeyType()); - // 主键类型 - String colType = ColUtil.cloToJava(column.getColumnType()); - // 小写开头的字段名 - //String changeColumnName = StringUtils.toCamelCase(column.getColumnName()); - String changeColumnName = column.getColumnName(); - // 大写开头的字段名 - String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getColumnName()); - if (PK.equals(column.getKeyType())) { - // 存储主键类型 - genMap.put("pkColumnType", colType); - // 存储小写开头的字段名 - genMap.put("pkChangeColName", changeColumnName); - // 存储大写开头的字段名 - genMap.put("pkCapitalColName", capitalColumnName); - } - // 是否存在 Timestamp 类型的字段 - if (TIMESTAMP.equals(colType)) { - genMap.put("hasTimestamp", true); - } - // 是否存在 BigDecimal 类型的字段 - if (BIGDECIMAL.equals(colType)) { - genMap.put("hasBigDecimal", true); - } - // 主键是否自增 - if (EXTRA.equals(column.getExtra())) { - genMap.put("auto", true); - } - // 主键存在字典 - if (StrUtil.isNotEmpty(column.getDictName())) { - genMap.put("hasDict", true); - dicts.add(column.getDictName()); - } + assert filePath != null; + File file = new File(filePath); - // 存储字段类型 - listMap.put("columnType", colType); - // 存储字原始段名称 - listMap.put("columnName", column.getColumnName()); - // 不为空 - listMap.put("istNotNull", column.getNotNull()); - // 字段列表显示 - listMap.put("columnShow", column.getListShow()); - // 表单显示 - listMap.put("formShow", column.getFormShow()); - // 表单组件类型 - listMap.put("formType", StrUtil.isNotEmpty(column.getFormType()) ? column.getFormType() : "Input"); - // 小写开头的字段名称 - listMap.put("changeColumnName", changeColumnName); - //大写开头的字段名称 - listMap.put("capitalColumnName", capitalColumnName); - // 字典名称 - listMap.put("dictName", column.getDictName()); - // 日期注解 - listMap.put("dateAnnotation", column.getDateAnnotation()); - if (StrUtil.isNotEmpty(column.getDateAnnotation())) { - genMap.put("hasDateAnnotation", true); + // 如果非覆盖生成 + if (!genConfig.getString("cover").equals("1") && FileUtil.exist(file)) { + continue; } - // 添加非空字段信息 - if (column.getNotNull()) { - isNotNullColumns.add(listMap); - } - // 判断是否有查询,如有则把查询的字段set进columnQuery - if (!StrUtil.isEmpty(column.getQueryType())) { - // 查询类型 - listMap.put("queryType", column.getQueryType()); - // 是否存在查询 - genMap.put("hasQuery", true); - if (TIMESTAMP.equals(colType)) { - // 查询中存储 Timestamp 类型 - genMap.put("queryHasTimestamp", true); - } - if (BIGDECIMAL.equals(colType)) { - // 查询中存储 BigDecimal 类型 - genMap.put("queryHasBigDecimal", true); - } - if ("between".equalsIgnoreCase(column.getQueryType())) { - betweens.add(listMap); - } else { - // 添加到查询列表中 - queryColumns.add(listMap); - } - } - // 添加到字段列表中 - columns.add(listMap); + // 生成代码 + genFile(file, template, genMap); } - // 保存字段列表 - genMap.put("columns", columns); - // 保存查询列表 - genMap.put("queryColumns", queryColumns); - // 保存字段列表 - genMap.put("dicts", dicts); - // 保存查询列表 - genMap.put("betweens", betweens); - // 保存非空字段信息 - genMap.put("isNotNullColumns", isNotNullColumns); - return genMap; + return tempPath; } /** * 定义后端文件路径以及名称 */ - private static String getAdminFilePath(String templateName, GenConfig genConfig, String className, String rootPath) { - String projectPath = rootPath + File.separator + genConfig.getModuleName(); + private static String getAdminFilePath(String templateName, JSONObject genConfig, String className, String rootPath) { + // projectPath: rootPath(项目绝对路径到项目名)+File.separator(\)+genConfig.getString("module_name")(前端输入的模块名) + // eg: D:\code\work\nl-sso-server\nladmin-system\nlsso-server + String projectPath = rootPath + File.separator + genConfig.getString("module_name"); + // packagePath: 包路径 + // eg:D:\code\work\nl-sso-server\nladmin-system\nlsso-server\src\main\java\输入的包名 String packagePath = projectPath + File.separator + "src" + File.separator + "main" + File.separator + "java" + File.separator; - if (!ObjectUtils.isEmpty(genConfig.getPack())) { - packagePath += genConfig.getPack().replace(".", File.separator) + File.separator; + if (!ObjectUtils.isEmpty(genConfig.getString("pack"))) { // 将点转成\ + packagePath += genConfig.getString("pack").replace(".", File.separator) + File.separator; } - if ("Entity".equals(templateName)) { return packagePath + "domain" + File.separator + className + ".java"; } @@ -389,15 +218,12 @@ public class GenUtil { if ("Repository".equals(templateName)) { return packagePath + "repository" + File.separator + className + "Repository.java"; } - return null; } - /** * 定义前端文件路径以及名称 */ private static String getFrontFilePath(String templateName, String apiPath, String path, String apiName) { - if ("api".equals(templateName)) { return apiPath + File.separator + apiName + ".js"; } @@ -409,6 +235,174 @@ public class GenUtil { return null; } + + // 获取模版数据 + private static JSONObject getGenMap(JSONArray columnInfos, JSONObject genConfig) { + // 存储模版字段数据 + JSONObject genMap = new JSONObject(16); + // 接口别名 + genMap.put("apiAlias", genConfig.getString("api_alias")); + // 包名称 + genMap.put("package", genConfig.getString("pack")); + // 模块名称 + genMap.put("moduleName", genConfig.getString("module_name")); + // 作者 + genMap.put("author", genConfig.getString("author")); + // 创建日期 + genMap.put("date", LocalDate.now().toString()); + // 表名 + genMap.put("tableName", genConfig.getString("table_name")); + // 大写开头的类名 + String className = StringUtils.toCapitalizeCamelCase(genConfig.getString("table_name")); + // 小写开头的类名 + String changeClassName = StringUtils.toCamelCase(genConfig.getString("table_name")); + // 判断是否去除表前缀 + if (StrUtil.isNotEmpty(genConfig.getString("prefix"))) { + className = StringUtils.toCapitalizeCamelCase(StrUtil.removePrefix(genConfig.getString("table_name"), genConfig.getString("prefix"))); + changeClassName = StringUtils.toCamelCase(StrUtil.removePrefix(genConfig.getString("table_name"), genConfig.getString("prefix"))); + } + // 保存类名 + genMap.put("className", className); + // 保存小写开头的类名 + genMap.put("changeClassName", changeClassName); + // 存在 Timestamp 字段 + genMap.put("hasTimestamp", false); + // 查询类中存在 Timestamp 字段 + genMap.put("queryHasTimestamp", false); + // 存在 BigDecimal 字段 + genMap.put("hasBigDecimal", false); + // 查询类中存在 BigDecimal 字段 + genMap.put("queryHasBigDecimal", false); + // 是否需要创建查询 + genMap.put("hasQuery", false); + // 自增主键 + genMap.put("auto", false); + // 存在字典 + genMap.put("hasDict", false); + // 存在日期注解 + genMap.put("hasDateAnnotation", false); + // 日期包 + genMap.put("hasDate", false); + // 保存字段信息 + List> columns = new ArrayList<>(); + // 保存查询字段的信息 + List> queryColumns = new ArrayList<>(); + // 存储字典信息 + List dicts = new ArrayList<>(); + // 存储 between 信息 + List> betweens = new ArrayList<>(); + // 存储不为空的字段信息 + List> isNotNullColumns = new ArrayList<>(); + + for (int i = 0; i < columnInfos.size(); i++) { + JSONObject column = columnInfos.getJSONObject(i); + JSONObject listMap = new JSONObject(16); + // 字段描述 + listMap.put("remark", column.getString("remark")); + // 字段类型 + listMap.put("columnKey", column.getString("key_type")); + // 主键类型 + String colType = ColUtil.cloToJava(column.getString("column_type")); + // 小写开头的字段名 + //String changeColumnName = StringUtils.toCamelCase(column.getColumnName()); + String changeColumnName = column.getString("column_name"); + // 大写开头的字段名 + String capitalColumnName = StringUtils.toCapitalizeCamelCase(column.getString("column_name")); + if (PK.equals(column.getString("key_type"))) { + // 存储主键类型 + genMap.put("pkColumnType", colType); + // 存储小写开头的字段名 + genMap.put("pkChangeColName", changeColumnName); + // 存储大写开头的字段名 + genMap.put("pkCapitalColName", capitalColumnName); + } + // 是否存在 Timestamp 类型的字段 + if (TIMESTAMP.equals(colType)) { + genMap.put("hasTimestamp", true); + } + // 是否存在 Timestamp 类型的字段 + if (Date.equals(colType)) { + genMap.put("hasDate", true); + } + // 是否存在 BigDecimal 类型的字段 + if (BIGDECIMAL.equals(colType)) { + genMap.put("hasBigDecimal", true); + } + // 主键是否自增 + if (EXTRA.equals(column.getString("extra"))) { + genMap.put("auto", true); + } + // 主键存在字典 + if (StrUtil.isNotEmpty(column.getString("dict_name"))) { + genMap.put("hasDict", true); + dicts.add(column.getString("dict_name")); + } + + // 存储字段类型 + listMap.put("columnType", colType); + // 存储字原始段名称 + listMap.put("columnName", column.getString("column_name")); + // 不为空 + listMap.put("istNotNull", (column.getString("not_null").equals("1"))?true:false); + // 字段列表显示 + listMap.put("columnShow", (column.getString("list_show").equals("1"))?true:false); + // 表单显示 + listMap.put("formShow", (column.getString("form_show").equals("1"))?true:false); + // 表单组件类型 + listMap.put("formType", StrUtil.isNotEmpty(column.getString("form_type")) ? column.getString("form_type") : "Input"); + // 小写开头的字段名称 + listMap.put("changeColumnName", changeColumnName); + //大写开头的字段名称 + listMap.put("capitalColumnName", capitalColumnName); + // 字典名称 + listMap.put("dictName", column.getString("dict_name")); + // 日期注解 + listMap.put("dateAnnotation", column.getString("date_annotation")); + if (StrUtil.isNotEmpty(column.getString("date_annotation"))) { + genMap.put("hasDateAnnotation", true); + } + // 添加非空字段信息 + if (column.getString("not_null").equals("1")) { + isNotNullColumns.add(listMap); + } + // 判断是否有查询,如有则把查询的字段set进columnQuery + if (!StrUtil.isEmpty(column.getString("query_type"))) { + // 查询类型 + listMap.put("queryType", column.getString("query_type")); + // 是否存在查询 + genMap.put("hasQuery", true); + if (TIMESTAMP.equals(colType)) { + // 查询中存储 Timestamp 类型 + genMap.put("queryHasTimestamp", true); + } + if (BIGDECIMAL.equals(colType)) { + // 查询中存储 BigDecimal 类型 + genMap.put("queryHasBigDecimal", true); + } + if ("between".equalsIgnoreCase(column.getString("query_type"))) { + betweens.add(listMap); + } else { + // 添加到查询列表中 + queryColumns.add(listMap); + } + } + // 添加到字段列表中 + columns.add(listMap); + } + // 保存字段列表 + genMap.put("columns", columns); + // 保存查询列表 + genMap.put("queryColumns", queryColumns); + // 保存字段列表 + genMap.put("dicts", dicts); + // 保存查询列表 + genMap.put("betweens", betweens); + // 保存非空字段信息 + genMap.put("isNotNullColumns", isNotNullColumns); + return genMap; + } + + // 生成文件 private static void genFile(File file, Template template, Map map) throws IOException { // 生成目标文件 Writer writer = null; diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/generator/wql/Generator.wql b/lms/nladmin-system/src/main/java/org/nl/sso/generator/wql/Generator.wql new file mode 100644 index 000000000..77019abc3 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/generator/wql/Generator.wql @@ -0,0 +1,82 @@ +[交易说明] + 交易名: 代码生成分页查询 + 所属模块: + 功能简述: + 版权所有: + 表引用: + 版本经历: + +[数据库] + --指定数据库,为空采用默认值,默认为db.properties中列出的第一个库 + +[IO定义] + ################################################# + ## 表字段对应输入参数 + ################################################# + 输入.flag TYPEAS s_string + 输入.table_name TYPEAS s_string + +[临时表] + --这边列出来的临时表就会在运行期动态创建 + +[临时变量] + --所有中间过程变量均可在此处定义 + +[业务过程] + + ########################################## + # 1、输入输出检查 # + ########################################## + + + ########################################## + # 2、主过程前处理 # + ########################################## + + + ########################################## + # 3、业务主过程 # + ########################################## + + IF 输入.flag = "1" + PAGEQUERY + SELECT + table_name, + DATE_FORMAT(now(),"%Y-%m-%d %T") create_time, + ENGINE, + table_collation as coding, + table_comment as remark + FROM + information_schema.TABLES + WHERE + table_schema = (SELECT DATABASE()) + OPTION 输入.table_name <> "" + table_name like "%" 输入.table_name "%" + ENDOPTION + ENDSELECT + ENDPAGEQUERY + ENDIF + + IF 输入.flag = "2" + PAGEQUERY + SELECT + column_name, + is_nullable, + data_type, + column_comment, + column_key, + extra + FROM + information_schema.COLUMNS + WHERE + table_schema = ( + SELECT DATABASE + ()) + OPTION 输入.table_name <> "" + table_name = 输入.table_name + ENDOPTION + ORDER BY + ordinal_position + ENDSELECT + ENDPAGEQUERY + ENDIF diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/quartz/config/JobRunner.java b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/config/JobRunner.java new file mode 100644 index 000000000..8cf0044a4 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/config/JobRunner.java @@ -0,0 +1,40 @@ +package org.nl.sso.quartz.config; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import lombok.RequiredArgsConstructor; +import org.nl.modules.wql.core.bean.WQLObject; +import org.nl.sso.quartz.utils.QuartzManage; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +/** + * @author: lyd + * @description: + * @Date: 2022/12/5 + */ +@Component +@RequiredArgsConstructor +@Order(100) +public class JobRunner implements ApplicationRunner { + private static final Logger log = LoggerFactory.getLogger(JobRunner.class); + private final QuartzManage quartzManage; + + /** + * 项目启动时重新激活启用的定时任务 + * + * @param applicationArguments / + */ + @Override + public void run(ApplicationArguments applicationArguments) { + log.info("--------------------注入定时任务---------------------"); + WQLObject jobTab = WQLObject.getWQLObject("sys_quartz_job"); + JSONArray quartzJobs = jobTab.query("is_pause = '0'").getResultJSONArray(0); + quartzJobs.forEach( job -> quartzManage.addJob((JSONObject) job)); + log.info("--------------------定时任务注入完成---------------------"); + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/quartz/config/QuartzConfig.java b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/config/QuartzConfig.java new file mode 100644 index 000000000..b3c6e0857 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/config/QuartzConfig.java @@ -0,0 +1,57 @@ +package org.nl.sso.quartz.config; + +import org.quartz.Scheduler; +import org.quartz.spi.TriggerFiredBundle; +import org.springframework.beans.factory.config.AutowireCapableBeanFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.quartz.AdaptableJobFactory; +import org.springframework.scheduling.quartz.SchedulerFactoryBean; +import org.springframework.stereotype.Component; + +/** + * @author: lyd + * @description: 定时任务配置 + * @Date: 2022/12/5 + */ +@Configuration +public class QuartzConfig { + + /** + * 解决Job中注入Spring Bean为null的问题 + */ + @Component("quartzJobFactory") + public static class QuartzJobFactory extends AdaptableJobFactory { + + private final AutowireCapableBeanFactory capableBeanFactory; + + public QuartzJobFactory(AutowireCapableBeanFactory capableBeanFactory) { + this.capableBeanFactory = capableBeanFactory; + } + + @Override + protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { + + //调用父类的方法 + Object jobInstance = super.createJobInstance(bundle); + capableBeanFactory.autowireBean(jobInstance); + return jobInstance; + } + } + + /** + * 注入scheduler到spring + * @param quartzJobFactory / + * @return Scheduler + * @throws Exception / + */ + @Bean(name = "scheduler") + public Scheduler scheduler(QuartzJobFactory quartzJobFactory) throws Exception { + SchedulerFactoryBean factoryBean=new SchedulerFactoryBean(); + factoryBean.setJobFactory(quartzJobFactory); + factoryBean.afterPropertiesSet(); + Scheduler scheduler=factoryBean.getScheduler(); + scheduler.start(); + return scheduler; + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/rest/QuartzJobController.java b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/rest/QuartzJobController.java similarity index 53% rename from lms/nladmin-system/src/main/java/org/nl/modules/quartz/rest/QuartzJobController.java rename to lms/nladmin-system/src/main/java/org/nl/sso/quartz/rest/QuartzJobController.java index f84511bab..214a1a999 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/rest/QuartzJobController.java +++ b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/rest/QuartzJobController.java @@ -1,41 +1,25 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.rest; +package org.nl.sso.quartz.rest; import cn.dev33.satoken.annotation.SaCheckPermission; +import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.nl.modules.common.exception.BadRequestException; import org.nl.modules.logging.annotation.Log; -import org.nl.modules.quartz.domain.QuartzJob; -import org.nl.modules.quartz.service.QuartzJobService; -import org.nl.modules.quartz.service.dto.JobQueryCriteria; +import org.nl.sso.quartz.service.QuartzJobService; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import java.util.Map; import java.util.Set; /** - * @author Zheng Jie - * @date 2019-01-07 + * @author: lyd + * @description: + * @Date: 2022/12/5 */ @Slf4j @RestController @@ -43,32 +27,28 @@ import java.util.Set; @RequestMapping("/api/jobs") @Api(tags = "系统:定时任务管理") public class QuartzJobController { - - private static final String ENTITY_NAME = "quartzJob"; private final QuartzJobService quartzJobService; - @ApiOperation("查询定时任务") @GetMapping - @SaCheckPermission("timing:list") - public ResponseEntity query(JobQueryCriteria criteria, Pageable pageable) { - return new ResponseEntity<>(quartzJobService.queryAll(criteria, pageable), HttpStatus.OK); + @Log("查询点位") + @ApiOperation("查询点位") + //@SaCheckPermission("timing:list") + public ResponseEntity query(@RequestParam Map whereJson, Pageable page) { + return new ResponseEntity<>(quartzJobService.queryAll(whereJson, page), HttpStatus.OK); } @ApiOperation("查询任务执行日志") @GetMapping(value = "/logs") @SaCheckPermission("timing:list") - public ResponseEntity queryJobLog(JobQueryCriteria criteria, Pageable pageable) { + public ResponseEntity queryJobLog(@RequestParam Map criteria, Pageable pageable) { return new ResponseEntity<>(quartzJobService.queryAllLog(criteria, pageable), HttpStatus.OK); } @Log("新增定时任务") @ApiOperation("新增定时任务") @PostMapping - @SaCheckPermission("timing:add") - public ResponseEntity create(@Validated @RequestBody QuartzJob resources) { - if (resources.getId() != null) { - throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID"); - } +// @SaCheckPermission("timing:add") + public ResponseEntity create(@RequestBody JSONObject resources) { quartzJobService.create(resources); return new ResponseEntity<>(HttpStatus.CREATED); } @@ -76,8 +56,8 @@ public class QuartzJobController { @Log("修改定时任务") @ApiOperation("修改定时任务") @PutMapping - @SaCheckPermission("timing:edit") - public ResponseEntity update(@Validated(QuartzJob.Update.class) @RequestBody QuartzJob resources) { +// @SaCheckPermission("timing:edit") + public ResponseEntity update(@RequestBody JSONObject resources) { quartzJobService.update(resources); return new ResponseEntity<>(HttpStatus.NO_CONTENT); } @@ -85,7 +65,7 @@ public class QuartzJobController { @Log("更改定时任务状态") @ApiOperation("更改定时任务状态") @PutMapping(value = "/{id}") - @SaCheckPermission("timing:edit") +// @SaCheckPermission("timing:edit") public ResponseEntity update(@PathVariable Long id) { quartzJobService.updateIsPause(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -94,7 +74,7 @@ public class QuartzJobController { @Log("执行定时任务") @ApiOperation("执行定时任务") @PutMapping(value = "/exec/{id}") - @SaCheckPermission("timing:edit") +// @SaCheckPermission("timing:edit") public ResponseEntity execution(@PathVariable Long id) { quartzJobService.execution(quartzJobService.findById(id)); return new ResponseEntity<>(HttpStatus.NO_CONTENT); @@ -103,7 +83,7 @@ public class QuartzJobController { @Log("删除定时任务") @ApiOperation("删除定时任务") @DeleteMapping - @SaCheckPermission("timing:del") +// @SaCheckPermission("timing:del") public ResponseEntity delete(@RequestBody Set ids) { quartzJobService.delete(ids); return new ResponseEntity<>(HttpStatus.OK); diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/quartz/service/QuartzJobService.java b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/service/QuartzJobService.java new file mode 100644 index 000000000..da9231002 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/service/QuartzJobService.java @@ -0,0 +1,79 @@ +package org.nl.sso.quartz.service; + +import com.alibaba.fastjson.JSONObject; +import org.springframework.data.domain.Pageable; + +import java.util.Map; +import java.util.Set; + +/** + * @author: lyd + * @description: + * @Date: 2022/12/5 + */ +public interface QuartzJobService { + + /** + * 分页查询 + * @param whereJson + * @param page + * @return + */ + Object queryAll(Map whereJson, Pageable page); + + /** + * 添加 + * @param resources + */ + void create(JSONObject resources); + + /** + * 日志查询 + * @param criteria + * @param pageable + * @return + */ + Object queryAllLog(Map criteria, Pageable pageable); + + /** + * 修改任务 + * @param resources + */ + void update(JSONObject resources); + + /** + * 根据ID查询 + * + * @param id ID + * @return / + */ + JSONObject findById(Long id); + + /** + * 立即执行定时任务 + * + * @param quartzJob / + */ + void execution(JSONObject quartzJob); + + /** + * 更改定时任务状态 + * + * @param job / + */ + void updateIsPause(JSONObject job); + + /** + * 执行子任务 + * + * @param tasks / + * @throws InterruptedException / + */ + void executionSubJob(String[] tasks) throws InterruptedException; + + /** + * 批量删除 + * @param ids + */ + void delete(Set ids); +} diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/quartz/service/impl/QuartzJobServiceImpl.java b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/service/impl/QuartzJobServiceImpl.java new file mode 100644 index 000000000..d913ec7a4 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/service/impl/QuartzJobServiceImpl.java @@ -0,0 +1,221 @@ +package org.nl.sso.quartz.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.ObjectUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONObject; +import lombok.RequiredArgsConstructor; +import org.nl.modules.common.exception.BadRequestException; +import org.nl.modules.common.utils.RedisUtils; +import org.nl.modules.wql.core.bean.ResultBean; +import org.nl.modules.wql.core.bean.WQLObject; +import org.nl.modules.wql.util.WqlUtil; +import org.nl.sso.quartz.service.QuartzJobService; +import org.nl.sso.quartz.utils.QuartzManage; +import org.nl.sso.tools.SecurityUtils; +import org.quartz.CronExpression; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author: lyd + * @description: + * @Date: 2022/12/5 + */ +@RequiredArgsConstructor +@Service(value = "quartzJobService") +public class QuartzJobServiceImpl implements QuartzJobService { + + private final RedisUtils redisUtils; + private final QuartzManage quartzManage; + + @Override + public Object queryAll(Map whereJson, Pageable page) { + WQLObject quartzTab = WQLObject.getWQLObject("sys_quartz_job"); + String param = "1 = 1"; + if (ObjectUtil.isNotEmpty(whereJson.get("job_name"))) { + String job_name = whereJson.get("job_name").toString(); + param = param + " AND job_name like '%" + job_name + "%'"; + } + ResultBean rb = quartzTab.pagequery(WqlUtil.getHttpContext(page), param, "update_time desc"); + final JSONObject json = rb.pageResult(); + return json; + } + + /** + * 添加 + * + * @param resources + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void create(JSONObject resources) { + if (!CronExpression.isValidExpression(resources.getString("cron_expression"))) { + throw new BadRequestException("cron表达式格式错误"); + } + WQLObject quartzTab = WQLObject.getWQLObject("sys_quartz_job"); + Long userId = SecurityUtils.getCurrentUserId(); + String nickName = SecurityUtils.getCurrentNickName(); + String now = DateUtil.now(); + resources.put("job_id", IdUtil.getSnowflake(1,1).nextId()); + resources.put("create_id", userId); + resources.put("create_name", nickName); + resources.put("create_time", now); + resources.put("update_optid", userId); + resources.put("update_optname", nickName); + resources.put("update_time", now); + quartzTab.insert(resources); + // 添加任务 + quartzManage.addJob(resources); + } + + /** + * 日志查询 + * + * @param criteria + * @param pageable + * @return + */ + @Override + public Object queryAllLog(Map criteria, Pageable pageable) { + WQLObject logTab = WQLObject.getWQLObject("sys_quartz_log"); + String param = "1=1"; + if (ObjectUtil.isNotEmpty(criteria.get("job_name"))) { + param = param + " AND job_name = '" + criteria.get("job_name").toString() + "'"; + } + if (ObjectUtil.isNotEmpty(criteria.get("is_success"))) { + param = param + " AND is_success = '" + criteria.get("is_success").toString() + "'"; + } + if (ObjectUtil.isNotEmpty(criteria.get("createTime"))) { + param = param + " AND create_time >= " + criteria.get("begin_time") + " AND" + + " create_time <= " + criteria.get("end_time"); + } + ResultBean rb = logTab.pagequery(WqlUtil.getHttpContext(pageable), param, "create_time desc"); + final JSONObject json = rb.pageResult(); + return json; + } + + /** + * 修改任务 + * + * @param resources + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void update(JSONObject resources) { + WQLObject jobTab = WQLObject.getWQLObject("sys_quartz_job"); + JSONObject entity = this.findById(resources.getLong("job_id")); + if (entity == null) { + throw new BadRequestException("被删除或无权限,操作失败!"); + } + if (!CronExpression.isValidExpression(resources.getString("cron_expression"))) { + throw new BadRequestException("cron表达式格式错误"); + } + if (StrUtil.isNotEmpty(resources.getString("sub_task"))) { + List tasks = Arrays.asList(resources.getString("sub_task").split("[,,]")); + if (tasks.contains(resources.getString("job_id"))) { + throw new BadRequestException("子任务中不能添加当前任务ID"); + } + } + resources.put("update_optid", SecurityUtils.getCurrentUserId()); + resources.put("update_optname", SecurityUtils.getCurrentNickName()); + resources.put("update_time", DateUtil.now()); + jobTab.update(resources); + quartzManage.updateJobCron(resources); + } + + /** + * 根据ID查询 + * + * @param id ID + * @return / + */ + @Override + public JSONObject findById(Long id) { + WQLObject jobTab = WQLObject.getWQLObject("sys_quartz_job"); + JSONObject entity = jobTab.query("job_id = '" + id + "'").uniqueResult(0); + return entity; + } + + /** + * 立即执行定时任务 + * + * @param quartzJob / + */ + @Override + public void execution(JSONObject quartzJob) { + quartzManage.runJobNow(quartzJob); + } + + /** + * 更改定时任务状态 + * + * @param quartzJob / + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void updateIsPause(JSONObject quartzJob) { + WQLObject jobTab = WQLObject.getWQLObject("sys_quartz_job"); + if (quartzJob.getString("is_pause").equals("1")) { + quartzManage.resumeJob(quartzJob); + quartzJob.put("is_pause", "0"); + } else { + quartzManage.pauseJob(quartzJob); + quartzJob.put("is_pause", "1"); + } + jobTab.update(quartzJob); + } + + /** + * 执行子任务 + * + * @param tasks / + * @throws InterruptedException / + */ + @Override + public void executionSubJob(String[] tasks) throws InterruptedException { + for (String id : tasks) { + JSONObject quartzJob = findById(Long.parseLong(id)); + // 执行任务 + String uuid = IdUtil.simpleUUID(); + quartzJob.put("job_id", uuid); + // 执行任务 + execution(quartzJob); + // 获取执行状态,如果执行失败则停止后面的子任务执行 + Boolean result = (Boolean) redisUtils.get(uuid); + while (result == null) { + // 休眠5秒,再次获取子任务执行情况 + Thread.sleep(5000); + result = (Boolean) redisUtils.get(uuid); + } + if (!result) { + redisUtils.del(uuid); + break; + } + } + } + + /** + * 批量删除 + * + * @param ids + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Set ids) { + WQLObject jobTab = WQLObject.getWQLObject("sys_quartz_job"); + WQLObject logTab = WQLObject.getWQLObject("sys_quartz_log"); + for (Long id : ids) { + JSONObject quartzJob = findById(id); + quartzManage.deleteJob(quartzJob); + jobTab.delete(quartzJob); + } + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/quartz/task/TestTask.java b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/task/TestTask.java new file mode 100644 index 000000000..417e2eb41 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/task/TestTask.java @@ -0,0 +1,26 @@ +package org.nl.sso.quartz.task; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * @author: lyd + * @description: 测试任务 + * @Date: 2022/12/5 + */ +@Slf4j +@Component +public class TestTask { + + public void run(){ + log.info("run 执行成功"); + } + + public void run1(String str){ + log.info("run1 执行成功,参数为: {}" + str); + } + + public void run2(){ + log.info("run2 执行成功"); + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/utils/ExecutionJob.java b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/utils/ExecutionJob.java similarity index 53% rename from lms/nladmin-system/src/main/java/org/nl/modules/quartz/utils/ExecutionJob.java rename to lms/nladmin-system/src/main/java/org/nl/sso/quartz/utils/ExecutionJob.java index ee4f68570..dbc2311d5 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/utils/ExecutionJob.java +++ b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/utils/ExecutionJob.java @@ -1,30 +1,16 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.utils; +package org.nl.sso.quartz.utils; +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; +import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.nl.config.thread.ThreadPoolExecutorUtil; import org.nl.modules.common.utils.RedisUtils; import org.nl.modules.common.utils.ThrowableUtil; -import org.nl.modules.quartz.domain.QuartzJob; -import org.nl.modules.quartz.domain.QuartzLog; -import org.nl.modules.quartz.repository.QuartzLogRepository; -import org.nl.modules.quartz.service.QuartzJobService; +import org.nl.modules.wql.core.bean.WQLObject; import org.nl.modules.wql.util.SpringContextHolder; +import org.nl.sso.quartz.service.QuartzJobService; import org.quartz.JobExecutionContext; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.quartz.QuartzJobBean; @@ -33,10 +19,9 @@ import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; /** - * 参考人人开源,https://gitee.com/renrenio/renren-security - * - * @author / - * @date 2019-01-07 + * @author: lyd + * @description: + * @Date: 2022/12/5 */ @Async @SuppressWarnings({"unchecked", "all"}) @@ -50,41 +35,43 @@ public class ExecutionJob extends QuartzJobBean { @Override public void executeInternal(JobExecutionContext context) { - QuartzJob quartzJob = (QuartzJob) context.getMergedJobDataMap().get(QuartzJob.JOB_KEY); + JSONObject quartzJob = (JSONObject) context.getMergedJobDataMap().get(QuartzManage.JOB_KEY); // 获取spring bean - QuartzLogRepository quartzLogRepository = SpringContextHolder.getBean(QuartzLogRepository.class); QuartzJobService quartzJobService = SpringContextHolder.getBean(QuartzJobService.class); RedisUtils redisUtils = SpringContextHolder.getBean(RedisUtils.class); + WQLObject logTab = WQLObject.getWQLObject("sys_quartz_log"); - String uuid = quartzJob.getUuid(); + String uuid = quartzJob.getString("job_id"); - QuartzLog logDto = new QuartzLog(); - logDto.setJobName(quartzJob.getJobName()); - logDto.setBeanName(quartzJob.getBeanName()); - logDto.setMethodName(quartzJob.getMethodName()); - logDto.setParams(quartzJob.getParams()); + JSONObject logDto = new JSONObject(); + logDto.put("log_id", IdUtil.getSnowflake(1,1).nextId()); + logDto.put("create_time", DateUtil.now()); // ???? + logDto.put("job_name", quartzJob.getString("job_name")); + logDto.put("bean_name", quartzJob.getString("bean_name")); + logDto.put("method_name", quartzJob.getString("method_name")); + logDto.put("params", quartzJob.getString("params")); long startTime = System.currentTimeMillis(); - logDto.setCronExpression(quartzJob.getCronExpression()); + logDto.put("cron_expression", quartzJob.getString("cron_expression")); try { // 执行任务 System.out.println("--------------------------------------------------------------"); - System.out.println("任务开始执行,任务名称:" + quartzJob.getJobName()); - QuartzRunnable task = new QuartzRunnable(quartzJob.getBeanName(), quartzJob.getMethodName(), - quartzJob.getParams()); + System.out.println("任务开始执行,任务名称:" + quartzJob.getString("bean_name")); + QuartzRunnable task = new QuartzRunnable(quartzJob.getString("bean_name"), quartzJob.getString("method_name"), + quartzJob.getString("params")); Future future = EXECUTOR.submit(task); future.get(); long times = System.currentTimeMillis() - startTime; - logDto.setTime(times); + logDto.put("time", times); if (StrUtil.isNotEmpty(uuid)) { redisUtils.set(uuid, true); } // 任务状态 - logDto.setIsSuccess(true); - System.out.println("任务执行完毕,任务名称:" + quartzJob.getJobName() + ", 执行时间:" + times + "毫秒"); + logDto.put("is_success", "1"); + System.out.println("任务执行完毕,任务名称:" + quartzJob.getString("job_name") + ", 执行时间:" + times + "毫秒"); System.out.println("--------------------------------------------------------------"); // 判断是否存在子任务 - if (StrUtil.isNotEmpty(quartzJob.getSubTask())) { - String[] tasks = quartzJob.getSubTask().split("[,,]"); + if (StrUtil.isNotEmpty(quartzJob.getString("sub_task"))) { + String[] tasks = quartzJob.getString("sub_task").split("[,,]"); // 执行子任务 quartzJobService.executionSubJob(tasks); } @@ -92,24 +79,23 @@ public class ExecutionJob extends QuartzJobBean { if (StrUtil.isNotEmpty(uuid)) { redisUtils.set(uuid, false); } - System.out.println("任务执行失败,任务名称:" + quartzJob.getJobName()); + System.out.println("任务执行失败,任务名称:" + quartzJob.getString("job_name")); System.out.println("--------------------------------------------------------------"); long times = System.currentTimeMillis() - startTime; - logDto.setTime(times); + logDto.put("time", times); // 任务状态 0:成功 1:失败 - logDto.setIsSuccess(false); - logDto.setExceptionDetail(ThrowableUtil.getStackTrace(e)); + logDto.put("is_success", "0"); + logDto.put("exception_detail", ThrowableUtil.getStackTrace(e)); // 任务如果失败了则暂停 - if (quartzJob.getPauseAfterFailure() != null && quartzJob.getPauseAfterFailure()) { - quartzJob.setIsPause(false); + if (quartzJob.getString("pause_after_failure") != null && quartzJob.getString("pause_after_failure").equals("1")) { + quartzJob.put("is_pause", "0"); //更新状态 quartzJobService.updateIsPause(quartzJob); } //异常时候打印日志 log.info(logDto.toString()); - quartzLogRepository.save(logDto); + logTab.insert(logDto); } finally { - } } diff --git a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/utils/QuartzManage.java b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/utils/QuartzManage.java similarity index 71% rename from lms/nladmin-system/src/main/java/org/nl/modules/quartz/utils/QuartzManage.java rename to lms/nladmin-system/src/main/java/org/nl/sso/quartz/utils/QuartzManage.java index ac20ccf3c..ecccc9460 100644 --- a/lms/nladmin-system/src/main/java/org/nl/modules/quartz/utils/QuartzManage.java +++ b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/utils/QuartzManage.java @@ -1,23 +1,8 @@ -/* - * Copyright 2019-2020 Zheng Jie - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.nl.modules.quartz.utils; +package org.nl.sso.quartz.utils; +import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.nl.modules.common.exception.BadRequestException; -import org.nl.modules.quartz.domain.QuartzJob; import org.quartz.*; import org.quartz.impl.triggers.CronTriggerImpl; import org.springframework.stereotype.Component; @@ -28,32 +13,33 @@ import java.util.Date; import static org.quartz.TriggerBuilder.newTrigger; /** - * @author Zheng Jie - * @date 2019-01-07 + * @author: lyd + * @description: 任务管理 + * @Date: 2022/12/5 */ @Slf4j @Component public class QuartzManage { - private static final String JOB_NAME = "TASK_"; + public static final String JOB_KEY = "JOB_KEY"; @Resource(name = "scheduler") private Scheduler scheduler; - public void addJob(QuartzJob quartzJob){ + public void addJob(JSONObject quartzJob){ try { // 构建job信息 JobDetail jobDetail = JobBuilder.newJob(ExecutionJob.class). - withIdentity(JOB_NAME + quartzJob.getId()).build(); + withIdentity(JOB_NAME + quartzJob.getString("job_id")).build(); //通过触发器名和cron 表达式创建 Trigger Trigger cronTrigger = newTrigger() - .withIdentity(JOB_NAME + quartzJob.getId()) + .withIdentity(JOB_NAME + quartzJob.getString("job_id")) .startNow() - .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression())) + .withSchedule(CronScheduleBuilder.cronSchedule(quartzJob.getString("cron_expression"))) .build(); - cronTrigger.getJobDataMap().put(QuartzJob.JOB_KEY, quartzJob); + cronTrigger.getJobDataMap().put(QuartzManage.JOB_KEY, quartzJob); //重置启动时间 ((CronTriggerImpl)cronTrigger).setStartTime(new Date()); @@ -62,7 +48,7 @@ public class QuartzManage { scheduler.scheduleJob(jobDetail,cronTrigger); // 暂停任务 - if (quartzJob.getIsPause()) { + if (quartzJob.getString("is_pause").equals("1")) { pauseJob(quartzJob); } } catch (Exception e){ @@ -72,86 +58,20 @@ public class QuartzManage { } /** - * 更新job cron表达式 - * @param quartzJob / + * 执行任务 + * @param quartzJob */ - public void updateJobCron(QuartzJob quartzJob){ + public void runJobNow(JSONObject quartzJob) { try { - TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); - CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); - // 如果不存在则创建一个定时任务 - if(trigger == null){ - addJob(quartzJob); - trigger = (CronTrigger) scheduler.getTrigger(triggerKey); - } - CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getCronExpression()); - trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); - //重置启动时间 - ((CronTriggerImpl)trigger).setStartTime(new Date()); - trigger.getJobDataMap().put(QuartzJob.JOB_KEY,quartzJob); - - scheduler.rescheduleJob(triggerKey, trigger); - // 暂停任务 - if (quartzJob.getIsPause()) { - pauseJob(quartzJob); - } - } catch (Exception e){ - log.error("更新定时任务失败", e); - throw new BadRequestException("更新定时任务失败"); - } - - } - - /** - * 删除一个job - * @param quartzJob / - */ - public void deleteJob(QuartzJob quartzJob){ - try { - JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); - scheduler.pauseJob(jobKey); - scheduler.deleteJob(jobKey); - } catch (Exception e){ - log.error("删除定时任务失败", e); - throw new BadRequestException("删除定时任务失败"); - } - } - - /** - * 恢复一个job - * @param quartzJob / - */ - public void resumeJob(QuartzJob quartzJob){ - try { - TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); - CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); - // 如果不存在则创建一个定时任务 - if(trigger == null) { - addJob(quartzJob); - } - JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); - scheduler.resumeJob(jobKey); - } catch (Exception e){ - log.error("恢复定时任务失败", e); - throw new BadRequestException("恢复定时任务失败"); - } - } - - /** - * 立即执行job - * @param quartzJob / - */ - public void runJobNow(QuartzJob quartzJob){ - try { - TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getId()); + TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getString("job_id")); CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); // 如果不存在则创建一个定时任务 if(trigger == null) { addJob(quartzJob); } JobDataMap dataMap = new JobDataMap(); - dataMap.put(QuartzJob.JOB_KEY, quartzJob); - JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); + dataMap.put(QuartzManage.JOB_KEY, quartzJob); + JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getString("job_id")); scheduler.triggerJob(jobKey,dataMap); } catch (Exception e){ log.error("定时任务执行失败", e); @@ -163,13 +83,74 @@ public class QuartzManage { * 暂停一个job * @param quartzJob / */ - public void pauseJob(QuartzJob quartzJob){ + public void pauseJob(JSONObject quartzJob){ try { - JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getId()); + JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getString("job_id")); scheduler.pauseJob(jobKey); } catch (Exception e){ log.error("定时任务暂停失败", e); throw new BadRequestException("定时任务暂停失败"); } } + + /** + * 更新job cron表达式 + * @param quartzJob / + */ + public void updateJobCron(JSONObject quartzJob) { + try { + TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getString("job_id")); + CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); + // 如果不存在则创建一个定时任务 + if(trigger == null){ + addJob(quartzJob); + trigger = (CronTrigger) scheduler.getTrigger(triggerKey); + } + CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(quartzJob.getString("cron_expression")); + trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); + //重置启动时间 + ((CronTriggerImpl)trigger).setStartTime(new Date()); + trigger.getJobDataMap().put(QuartzManage.JOB_KEY, quartzJob); + + scheduler.rescheduleJob(triggerKey, trigger); + // 暂停任务 + if (quartzJob.getString("is_pause").equals("1")) { + pauseJob(quartzJob); + } + } catch (Exception e){ + log.error("更新定时任务失败", e); + throw new BadRequestException("更新定时任务失败"); + } + } + + /** + * 恢复一个job + * @param quartzJob / + */ + public void resumeJob(JSONObject quartzJob) { + try { + TriggerKey triggerKey = TriggerKey.triggerKey(JOB_NAME + quartzJob.getString("job_id")); + CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey); + // 如果不存在则创建一个定时任务 + if(trigger == null) { + addJob(quartzJob); + } + JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getString("job_id")); + scheduler.resumeJob(jobKey); + } catch (Exception e){ + log.error("恢复定时任务失败", e); + throw new BadRequestException("恢复定时任务失败"); + } + } + + public void deleteJob(JSONObject quartzJob) { + try { + JobKey jobKey = JobKey.jobKey(JOB_NAME + quartzJob.getString("job_id")); + scheduler.pauseJob(jobKey); + scheduler.deleteJob(jobKey); + } catch (Exception e){ + log.error("删除定时任务失败", e); + throw new BadRequestException("删除定时任务失败"); + } + } } diff --git a/lms/nladmin-system/src/main/java/org/nl/sso/quartz/utils/QuartzRunnable.java b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/utils/QuartzRunnable.java new file mode 100644 index 000000000..7230f3dc2 --- /dev/null +++ b/lms/nladmin-system/src/main/java/org/nl/sso/quartz/utils/QuartzRunnable.java @@ -0,0 +1,45 @@ +package org.nl.sso.quartz.utils; + +import cn.hutool.core.util.StrUtil; +import lombok.extern.slf4j.Slf4j; +import org.nl.modules.wql.util.SpringContextHolder; +import org.springframework.util.ReflectionUtils; + +import java.lang.reflect.Method; +import java.util.concurrent.Callable; + +/** + * @author: lyd + * @description: 执行定时任务 + * @Date: 2022/12/5 + */ +@Slf4j +public class QuartzRunnable implements Callable { + + private final Object target; + private final Method method; + private final String params; + + QuartzRunnable(String beanName, String methodName, String params) + throws NoSuchMethodException, SecurityException { + this.target = SpringContextHolder.getBean(beanName); + this.params = params; + + if (StrUtil.isNotEmpty(params)) { + this.method = target.getClass().getDeclaredMethod(methodName, String.class); + } else { + this.method = target.getClass().getDeclaredMethod(methodName); + } + } + + @Override + public Object call() throws Exception { + ReflectionUtils.makeAccessible(method); + if (StrUtil.isNotEmpty(params)) { + method.invoke(target, params); + } else { + method.invoke(target); + } + return null; + } +} diff --git a/lms/nladmin-system/src/main/java/org/nl/start/Init.java b/lms/nladmin-system/src/main/java/org/nl/start/Init.java index 11be8ca76..0b10b58c5 100644 --- a/lms/nladmin-system/src/main/java/org/nl/start/Init.java +++ b/lms/nladmin-system/src/main/java/org/nl/start/Init.java @@ -1,12 +1,7 @@ package org.nl.start; -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.util.IdUtil; -import com.alibaba.fastjson.JSONObject; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.nl.modules.common.utils.SecurityUtils; -import org.nl.modules.wql.core.bean.WQLObject; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; diff --git a/lms/nladmin-system/src/main/resources/config/application-dev.yml b/lms/nladmin-system/src/main/resources/config/application-dev.yml index 1fdd31fe4..45a373c6c 100644 --- a/lms/nladmin-system/src/main/resources/config/application-dev.yml +++ b/lms/nladmin-system/src/main/resources/config/application-dev.yml @@ -1,5 +1,5 @@ server: - port: 8010 + port: 8113 #配置数据源 spring: datasource: @@ -10,7 +10,7 @@ spring: # url: jdbc:log4jdbc:mysql://${DB_HOST:127.0.0.1}:${DB_PORT:3306}/${DB_NAME:nladmin}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true # username: ${DB_USER:root} username: ${DB_USER:root} - password: ${DB_PWD:Root.123456} + password: ${DB_PWD:Root.123456} # password: ${DB_PWD:12356} # 初始连接数 initial-size: 5 @@ -53,12 +53,12 @@ spring: wall: config: multi-statement-allow: true -redis: - #数据库索引 - database: ${REDIS_DB:15} - host: ${REDIS_HOST:127.0.0.1} - port: ${REDIS_PORT:6379} - password: ${REDIS_PWD:} + redis: + #数据库索引 + database: ${REDIS_DB:15} + host: ${REDIS_HOST:127.0.0.1} + port: ${REDIS_PORT:6379} + password: ${REDIS_PWD:} # 登录相关配置 login: diff --git a/lms/nladmin-ui/src/views/generator/config.vue b/lms/nladmin-ui/src/views/generator/config.vue index 98f0286c2..dc506afbd 100644 --- a/lms/nladmin-ui/src/views/generator/config.vue +++ b/lms/nladmin-ui/src/views/generator/config.vue @@ -34,8 +34,8 @@ - - + +