diff --git a/buildpackage/pom.xml b/buildpackage/pom.xml new file mode 100644 index 00000000..8feb8f73 --- /dev/null +++ b/buildpackage/pom.xml @@ -0,0 +1,43 @@ + + + + kangarooDataCenterV3 + com.hzya.frame + ${revision} + + 4.0.0 + buildpackage + war + + + + com.hzya.frame + webapp + ${revision} + + + + + + + + + + + + + + + + + + + + + + kangarooDataCenterV3 + + + diff --git a/buildpackage/src/main/java/com/hzya/frame/WarStartApplication.java b/buildpackage/src/main/java/com/hzya/frame/WarStartApplication.java new file mode 100644 index 00000000..fc8205ec --- /dev/null +++ b/buildpackage/src/main/java/com/hzya/frame/WarStartApplication.java @@ -0,0 +1,19 @@ +package com.hzya.frame; + +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; + +/*** + * @Content:War启动类 继承SpringBootServletInitializer 初始化servlet 环境 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2022-11-29 14:27 + * @Param + * @return + **/ +public class WarStartApplication extends SpringBootServletInitializer { + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + // 指向Application 这个启动类 + return builder.sources(WebappApplication.class); + } +} diff --git a/buildpackage/src/main/java/com/hzya/frame/WebappApplication.java b/buildpackage/src/main/java/com/hzya/frame/WebappApplication.java new file mode 100644 index 00000000..a1bedb90 --- /dev/null +++ b/buildpackage/src/main/java/com/hzya/frame/WebappApplication.java @@ -0,0 +1,35 @@ +package com.hzya.frame; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.ImportResource; + +@EnableCaching +@ServletComponentScan(basePackages = {"com.hzya.frame"}) +@ImportResource(locations = {"classpath:cfgHome/**/spring/spring-*.xml"}) +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}) +//@SpringBootApplication(scanBasePackages = {"com.hzya.frame"}) +public class WebappApplication { + + public static void main(String[] args) { + SpringApplication.run(WebappApplication.class, args); + System.out.println(" (♥◠‿◠)ノ゙ 启动成功 ლ(´ڡ`ლ)゙ \n" + + " .----------------. .----------------. .-----------------. .----------------. .-----------------.\n" + + "| .--------------. || .--------------. || .--------------. || .--------------. || .--------------. |\n" + + "| | ____ ____ | || | ____ | || | ____ _____ | || | __ | || | ____ _____ | |\n" + + "| | |_ _||_ _| | || | .' `. | || ||_ \\|_ _| | || | / \\ | || ||_ \\|_ _| | |\n" + + "| | \\ \\ / / | || | / .--. \\ | || | | \\ | | | || | / /\\ \\ | || | | \\ | | | |\n" + + "| | \\ \\/ / | || | | | | | | || | | |\\ \\| | | || | / ____ \\ | || | | |\\ \\| | | |\n" + + "| | _| |_ | || | \\ `--' / | || | _| |_\\ |_ | || | _/ / \\ \\_ | || | _| |_\\ |_ | |\n" + + "| | |______| | || | `.____.' | || ||_____|\\____| | || ||____| |____|| || ||_____|\\____| | |\n" + + "| | | || | | || | | || | | || | | |\n" + + "| '--------------' || '--------------' || '--------------' || '--------------' || '--------------' |\n" + + " '----------------' '----------------' '----------------' '----------------' '----------------' "); + } + + +} diff --git a/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/entity/SysESBMessageManageLogEntity.java b/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/entity/SysESBMessageManageLogEntity.java new file mode 100644 index 00000000..1d39e5c6 --- /dev/null +++ b/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/entity/SysESBMessageManageLogEntity.java @@ -0,0 +1,12 @@ +package com.hzya.frame.plugin.sysMessageManageLogBack.entity; + +import com.hzya.frame.web.entity.BaseEntity; + +public class SysESBMessageManageLogEntity extends BaseEntity { + + private String name; + + + +} + diff --git a/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/plugin/SysMessageManageLogPluginInitializer.java b/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/plugin/SysMessageManageLogPluginInitializer.java new file mode 100644 index 00000000..f2d8ed97 --- /dev/null +++ b/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/plugin/SysMessageManageLogPluginInitializer.java @@ -0,0 +1,57 @@ +package com.hzya.frame.plugin.sysMessageManageLogBack.plugin; + +import com.alibaba.fastjson.JSONObject; +import com.hzya.frame.base.PluginBaseEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * 消息管理日志(SysMessageManageLog)表服务接口 + * + * @author makejava + * @since 2024-03-08 10:22:00 + */ +public class SysMessageManageLogPluginInitializer extends PluginBaseEntity { + Logger logger = LoggerFactory.getLogger(SysMessageManageLogPluginInitializer.class); + + @Override + public void initialize() { + logger.info(getPluginLabel() + "執行初始化方法initialize()"); + } + + @Override + public void destroy() { + logger.info(getPluginLabel() + "執行銷毀方法destroy()"); + } + + @Override + public String getPluginId() { + return "SysMessageManageLogPlugin"; + } + + @Override + public String getPluginName() { + return "ESB消息日志备份"; + } + + @Override + public String getPluginLabel() { + return "ESB消息日志备份"; + } + + @Override + public String getPluginType() { + return "1"; + } + + @Override + public String executeBusiness(JSONObject requestJson) throws Exception { + try { + return "备份成功"; + }catch (Exception e){ + e.printStackTrace(); + } + return null; + } + +} diff --git a/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/service/ISysESBMessageManageLogService.java b/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/service/ISysESBMessageManageLogService.java new file mode 100644 index 00000000..b30d5da9 --- /dev/null +++ b/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/service/ISysESBMessageManageLogService.java @@ -0,0 +1,13 @@ +package com.hzya.frame.plugin.sysMessageManageLogBack.service; + +import com.hzya.frame.basedao.service.IBaseService; +import com.hzya.frame.plugin.sysMessageManageLogBack.entity.SysESBMessageManageLogEntity; + +/** + * 消息管理日志(SysMessageManageLog)表服务接口 + * + * @author makejava + * @since 2024-03-08 10:22:00 + */ +public interface ISysESBMessageManageLogService extends IBaseService { +} diff --git a/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/service/impl/SysESBMessageManageLogServiceImpl.java b/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/service/impl/SysESBMessageManageLogServiceImpl.java new file mode 100644 index 00000000..a1494624 --- /dev/null +++ b/buildpackage/src/main/java/com/hzya/frame/plugin/sysMessageManageLogBack/service/impl/SysESBMessageManageLogServiceImpl.java @@ -0,0 +1,15 @@ +package com.hzya.frame.plugin.sysMessageManageLogBack.service.impl; + +import com.hzya.frame.basedao.service.impl.BaseService; +import com.hzya.frame.plugin.sysMessageManageLogBack.entity.SysESBMessageManageLogEntity; +import com.hzya.frame.plugin.sysMessageManageLogBack.service.ISysESBMessageManageLogService; + +/** + * 消息管理日志(SysMessageManageLog)表服务实现类 + * + * @author makejava + * @since 2024-03-08 10:22:00 + */ +public class SysESBMessageManageLogServiceImpl extends BaseService implements ISysESBMessageManageLogService { + +} diff --git a/buildpackage/src/main/resources/application.properties b/buildpackage/src/main/resources/application.properties new file mode 100644 index 00000000..0e2cc4b2 --- /dev/null +++ b/buildpackage/src/main/resources/application.properties @@ -0,0 +1,25 @@ +#应用名 +spring.application.name=kangarooDataCenterV3 +#端口 +server.port=9999 +#编码集 +server.tomcat.uri-encoding=utf-8 +#工程访问名称 +server.servlet.context-path=/kangarooDataCenterV3 +#json日期格式化 +spring.jackson.date-format=yyyy-MM-dd HH:mm:ss +spring.jackson.time-zone=GMT+8 +context.initializer.classes= com.hzya.frame.web.init.ApplicationContextInitialized +spring.batch.job.enabled = false +mybatis.mapper-locations = classpath*:com/hzya/**/*.xml +mybatis.config-location= classpath:mybatis/mybatis-config.xml +#mybatis.configuration.call-setters-on-nulls=true + +#日志配置 +logging.config= classpath:log/logback-spring.xml +logging.file.path = /Users/xiangerlin/work/app/logs/zhongtai + +#文件最大大小 +spring.servlet.multipart.enabled=true +spring.servlet.multipart.max-file-size=100MB +spring.servlet.multipart.max-request-size=100MB \ No newline at end of file diff --git a/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/pluginCfg.xml b/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/pluginCfg.xml new file mode 100644 index 00000000..00d5dc0b --- /dev/null +++ b/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/pluginCfg.xml @@ -0,0 +1,6 @@ + + +SysMessageManageLogPlugin +SysMessageManageLogPlugin插件 +202403080010 + diff --git a/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/spring/spring-buildpackage-dao.xml b/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/spring/spring-buildpackage-dao.xml new file mode 100644 index 00000000..f857d7fc --- /dev/null +++ b/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/spring/spring-buildpackage-dao.xml @@ -0,0 +1,4 @@ + + + + diff --git a/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/spring/spring-buildpackage-plugin.xml b/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/spring/spring-buildpackage-plugin.xml new file mode 100644 index 00000000..2ca55124 --- /dev/null +++ b/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/spring/spring-buildpackage-plugin.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/spring/spring-buildpackage-service.xml b/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/spring/spring-buildpackage-service.xml new file mode 100644 index 00000000..4f0c39ab --- /dev/null +++ b/buildpackage/src/main/resources/cfgHome/plugin/sysMessageManageLogBack/spring/spring-buildpackage-service.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/buildpackage/src/main/resources/log/logback-spring.xml b/buildpackage/src/main/resources/log/logback-spring.xml new file mode 100644 index 00000000..3dd69b42 --- /dev/null +++ b/buildpackage/src/main/resources/log/logback-spring.xml @@ -0,0 +1,124 @@ + + + + + + + + + logback + + + + + + + + + + + + + + + + + + INFO + + + ${CONSOLE_LOG_PATTERN} + + UTF-8 + + + + + + ${LOG_PATH}/info/info.log + + ${LOG_PATH}/info/%d{yyyy-MM-dd,aux}/info.%d{HH}.log + + + INFO + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + ${LOG_PATH}/debug/debug.log + + ${LOG_PATH}/debug/%d{yyyy-MM-dd,aux}/debug.%d{HH}.log + ${MAX_HISTORY} + + + DEBUG + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + ${MAX_FILE_SIZE} + + + + + + ${LOG_PATH}/error/error.log + + ${LOG_PATH}/error/%d{yyyy-MM-dd,aux}/error.%d{HH}.log + ${MAX_HISTORY} + + + + ERROR + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + ${LOG_PATH}/warn/warn.log + + ${LOG_PATH}/warn/%d{yyyy-MM-dd,aux}/warn.%d{HH:mm}.log + ${MAX_HISTORY} + + + WARN + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/buildpackage/src/main/resources/mybatis/common.xml b/buildpackage/src/main/resources/mybatis/common.xml new file mode 100644 index 00000000..6c555dee --- /dev/null +++ b/buildpackage/src/main/resources/mybatis/common.xml @@ -0,0 +1,7 @@ + + + + + \ No newline at end of file diff --git a/buildpackage/src/main/resources/mybatis/mybatis-config.xml b/buildpackage/src/main/resources/mybatis/mybatis-config.xml new file mode 100644 index 00000000..2993693c --- /dev/null +++ b/buildpackage/src/main/resources/mybatis/mybatis-config.xml @@ -0,0 +1,43 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/buildpackage/src/main/resources/templates/index.html b/buildpackage/src/main/resources/templates/index.html new file mode 100644 index 00000000..566549bd --- /dev/null +++ b/buildpackage/src/main/resources/templates/index.html @@ -0,0 +1,10 @@ + + + + + Title + + + + + \ No newline at end of file diff --git a/buildpackage/src/main/test/com/hzya/frame/SpringTransactionalApplicationTests.java b/buildpackage/src/main/test/com/hzya/frame/SpringTransactionalApplicationTests.java new file mode 100644 index 00000000..0dbc877d --- /dev/null +++ b/buildpackage/src/main/test/com/hzya/frame/SpringTransactionalApplicationTests.java @@ -0,0 +1,25 @@ +package com.hzya.frame; + +import com.hzya.frame.demo.service.TestService; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.Resource; +import java.sql.SQLException; + +@SpringBootTest +class SpringTransactionalApplicationTests { + + + @Resource + private TestService testService; + + @Test + void contextLoads() { + } + + @Test + void testS() throws SQLException { + } + +} diff --git a/buildpackage/src/main/test/com/hzya/frame/Test01.java b/buildpackage/src/main/test/com/hzya/frame/Test01.java new file mode 100644 index 00000000..cc57b5e6 --- /dev/null +++ b/buildpackage/src/main/test/com/hzya/frame/Test01.java @@ -0,0 +1,26 @@ +package com.hzya.frame; + +import com.alibaba.fastjson.JSONObject; +import com.hzya.frame.nc.service.impl.NcInterfaceServiceImpl; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import javax.annotation.Resource; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2023-07-19 10:54 + * @Version 1.0 + */ +@SpringBootTest +public class Test01 { + @Resource + private NcInterfaceServiceImpl ncInterfaceService; + + @Test + public void test01() { + JSONObject jsonObject = new JSONObject(); + ncInterfaceService.updateUser(jsonObject); + } +} diff --git a/buildpackage/src/main/webapp/WEB-INF/lib/openapi-sdk-1.0.0.jar b/buildpackage/src/main/webapp/WEB-INF/lib/openapi-sdk-1.0.0.jar new file mode 100644 index 00000000..e69de29b diff --git a/buildpackage/src/main/webapp/WEB-INF/lib/taobao-sdk-java-auto-1.1.jar b/buildpackage/src/main/webapp/WEB-INF/lib/taobao-sdk-java-auto-1.1.jar new file mode 100644 index 00000000..e69de29b diff --git a/buildpackage/src/main/webapp/WEB-INF/web.xml b/buildpackage/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000..d80081d1 --- /dev/null +++ b/buildpackage/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,6 @@ + + + \ No newline at end of file diff --git a/buildpackage/src/test/java/com/hzya/frame/temButtom.java b/buildpackage/src/test/java/com/hzya/frame/temButtom.java new file mode 100644 index 00000000..998d393e --- /dev/null +++ b/buildpackage/src/test/java/com/hzya/frame/temButtom.java @@ -0,0 +1,19 @@ +package com.hzya.frame; + +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @ClassName dsasas + * @Description + * @Author llg + * Date 2023/7/16 8:18 上午 + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = {WebappApplication.class}) +public class temButtom { + + + +} diff --git a/common/pom.xml b/common/pom.xml new file mode 100644 index 00000000..b2ea702f --- /dev/null +++ b/common/pom.xml @@ -0,0 +1,32 @@ + + + + kangarooDataCenterV3 + com.hzya.frame + ${revision} + + 4.0.0 + common + jar + + + + org.springframework.boot + spring-boot-maven-plugin + + none + execute + + + + + repackage + + + + + + + diff --git a/common/src/main/java/com/hzya/frame/basedao/dao/IBaseDao.java b/common/src/main/java/com/hzya/frame/basedao/dao/IBaseDao.java new file mode 100644 index 00000000..e69bb46c --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/dao/IBaseDao.java @@ -0,0 +1,202 @@ +package com.hzya.frame.basedao.dao; + + +import com.hzya.frame.page.PageAttribute; + +import java.io.Serializable; +import java.util.List; + + +public interface IBaseDao { + + /** + * 查询一个对象 + * @param paramPK 主键ID + * @return + */ + E get(PK paramPK); + + /** + * 获取所有的结果集 + * @return + */ + List getAll(); + + /** + * 查询一个对象 + * @param paramString mapper ID + * @param paramObject 查询条件 + * @return + */ + Object selectOne(String paramString, Object paramObject); + + /** + * 查询一个List + * @param paramString mapper ID + * @param paramObject 查询条件 + * @return + */ + List selectList(String paramString, Object paramObject); + + /** + * 逻辑删除 ,sts置为 N + * @param o + * @return + */ + int logicRemove(E o); + + /** + * 逻辑删除 ,sts置为 N + * @param o 多个条件 + * @return + */ + int logicRemoveMultiCondition(E o); + /**** + * @Content:多条件删除数据,设置数据状态STS为N + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-07-24 11:26 + * @Param [id, o] + * @return int + **/ + int logicRemoveMultiCondition(String id,E o); + /** + * 物理删除 + * @param paramPK 主键ID + * @return + */ + int delete(PK paramPK); + + /** + * 物理删除 + * @param paramString sqlMapperID + * @param paramObject 条件参数 + * @return + */ + int delete(String paramString, Object paramObject); + + /** + * 修改 + * @param paramString sqlMapperID + * @param paramObject 条件参数 + * @return + */ + int update(String paramString, Object paramObject); + + /** + * 条件查询一个对象 + * @param paramE 条件参数 + * @return + */ + E queryOne(E paramE); + + /** + * 插入数据或者修改数据(ID为空是插入,ID不为空是修改) + * @param paramE + * @return + */ + E saveOrUpdate(E paramE); + + /** + * 保存方法 + * @param paramE + * @return + */ + E save(E paramE); + /** + * 保存方法 + * @param paramString id + * @param paramE entitty + * @return + */ + E save(String paramString, E paramE); + + + /**** + * @Content:保存方法 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-07-24 11:41 + * @Param [paramString, paramE] + * @return java.lang.Integer + **/ + Integer insert(String paramString, Object paramE); + + /** + * 修改方法 + * @param paramE + * @return + */ + E update(E paramE); + + /** + * 查询单个对象 + * @param paramE 条件参数 + * @param paramString mapperID + * @return + */ + E query(E paramE, String paramString); + + /** + * 查询一个List + * @param paramE 条件参数 + * @param paramString msqpperID + * @return + */ + List queryList(E paramE, String paramString); + /** + * 查询一个List + * @param paramE 条件参数 + * @return + */ + List queryBase(E paramE); + + /** + * 查询结果集 + * @param paramE 条件参数 + * @return + */ + List query(E paramE); + + + /** + * wehere条件为 like + * @param paramE 条件参数 + * @return + */ + List queryByLike(E paramE); + + /** + * where条件为or + * @param paramE + * @return + */ + List queryByOr(E paramE); + + /** + * 获取数据条数 + * @param paramObject 条件参数 + * @return + */ + Integer getCount(Object paramObject); + + /** + * 分页查询 + * @param paramString mapperID + * @param paramObject 条件参数 + * @return + */ + PageAttribute queryPaged(String paramString, Object paramObject); + + /** + * 分页查询 + * @param paramObject 条件参数 + * @return + */ + PageAttribute queryPaged(Object paramObject); + + /** + * 判断是否重复 + * @param paramE 参数条件 + * @return + */ + boolean checkRepeated(E paramE); +} diff --git a/common/src/main/java/com/hzya/frame/basedao/dao/MybatisGenericDao.java b/common/src/main/java/com/hzya/frame/basedao/dao/MybatisGenericDao.java new file mode 100644 index 00000000..178e24e2 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/dao/MybatisGenericDao.java @@ -0,0 +1,343 @@ +package com.hzya.frame.basedao.dao; + +import cn.hutool.core.util.StrUtil; +import com.baomidou.dynamic.datasource.annotation.DS; +import com.github.pagehelper.PageInfo; +import com.hzya.frame.page.PageAttribute; +import com.hzya.frame.page.PageHelper; +import com.hzya.frame.web.entity.BaseEntity; +import org.apache.commons.beanutils.BeanUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.ibatis.session.SqlSession; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.Assert; + +import javax.annotation.Resource; +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.List; + +/** + * @author Administrator + */ +@Component +public abstract class MybatisGenericDao implements IBaseDao { + public static final String POSTFIX_INSERT = "_insert"; + public static final String POSTFIX_UPDATE = "_update"; + public static final String POSTFIX_UPDATE_SELECTIVE = "_updateSelective"; + public static final String POSTFIX_LOGIC_DELETE = "_logicDelete"; + public static final String POSTFIX_LOGIC_DELETE_LOGICDELETE_MULTI_CONDITION = "_logicDelete_Multi_Condition"; + public static final String POSTFIX_DELETE = "_delete"; + public static final String POSTFIX_DELETE_MULTI_CONDITION = "_delete_Multi_Condition"; + public static final String POSTFIX_DELETE_BYKEY = "_deleteByPrimaryKey"; + public static final String POSTFIX_GET = "_get"; + public static final String POSTFIX_SELECT = "_list"; + public static final String POSTFIX_COUNT = "_count"; + public static final String POSTFIX_CUSTOM1 = "_custom1"; + public static final String POSTFIX_CUSTOM2 = "_custom2"; + public static final String POSTFIX_CUSTOM3 = "_custom3"; + private static final Log LOG = LogFactory.getLog(MybatisGenericDao.class); + + @Resource + private SqlSession sqlSession; + private Class entityClass; + + public MybatisGenericDao() { + Class c = super.getClass(); + Type t = c.getGenericSuperclass(); + if (t instanceof ParameterizedType) { + this.entityClass = ((Class) ((ParameterizedType) t).getActualTypeArguments()[0]); + //LOG.info("enityClass : " + this.entityClass.toString()); + } + } + + public String getSqlIdPrifx() { + String path = this.getClass().getName() + "."; + return path; + } + + + @Override + public Object selectOne(String id, Object param) { + return this.sqlSession.selectOne(id, param); + } + +// @DS("#param.dataSourceCode") + @Override + public List selectList(String id, Object param) { + return this.sqlSession.selectList(id, param); + } + + @Override + public List queryByLike(E o) { + List tempList = this.sqlSession.selectList(getSqlIdPrifx() + "entity_list_like", o); + return tempList; + } + + @Override + public List queryByOr(E o) { + List tempList = this.sqlSession.selectList(getSqlIdPrifx() + "entity_list_or", o); + return tempList; + } + + @Override + public E get(PK id) { + Assert.notNull(id, "get: ID不能为null"); + Object o = this.sqlSession.selectOne(getSqlIdPrifx() + "entity_get", id); + return (E) o; + } + + @DS("#o.dataSourceCode") + @Override + public E query(E o, String stamentID) { + return (E) this.sqlSession.selectOne(stamentID, o); + } + + @Override + public List queryList(E o, String stamentID) { + List tempList = this.sqlSession.selectList(stamentID, o); + return tempList; + } + + @Override + public List queryBase(E o) { + List tempList = this.sqlSession.selectList(getSqlIdPrifx() + "entity_list_base", o); + return tempList; + } + + @Override + public List getAll() { + List tempList = this.sqlSession.selectList(getSqlIdPrifx() + "entity_list_base"); + return tempList; + } + + @Override + @DS("#param.dataSourceCode") + public List query(Serializable param) { + String str = getSqlIdPrifx() + "entity_list_base"; + List tempList = this.sqlSession.selectList(str, param); + return tempList; + } + + public E selectOne(Serializable param) { + String str = getSqlIdPrifx() + "entity_list_base"; + E e = this.sqlSession.selectOne(str, param); + return e; + } + + @Override + public E saveOrUpdate(E o) { + Assert.notNull(o, "saveOrUpdate : 参数列表不能为NULL"); + Object id = null; + try { + id = BeanUtils.getProperty(o, "id"); + } catch (IllegalAccessException e) { + e.printStackTrace(); + } catch (InvocationTargetException e) { + e.printStackTrace(); + } catch (NoSuchMethodException e) { + e.printStackTrace(); + } + + if ((id == null) || ("".equals(String.valueOf(id)))) { + this.sqlSession.insert(getSqlIdPrifx() + "entity_insert", o); + } else { + this.sqlSession.update(getSqlIdPrifx() + "entity_update", o); + } + + return o; + } + + @Override + public E queryOne(E o) { + E e = selectOne(o); + return e; + } + + @Override + public E update(E o) { + Assert.notNull(o, "update : 参数列表不能为NULL"); + this.sqlSession.update(getSqlIdPrifx() + "entity_update", o); + return o; + } + + @Override + public E save(E o) { + Assert.notNull(o, "save : 参数列表不能为NULL"); + this.sqlSession.insert(getSqlIdPrifx() + "entity_insert", o); + return o; + } + + @Override + public Integer insert(String paramString, Object paramE) { + return this.sqlSession.insert(paramString, paramE); + } + + @Override + public E save(String id, E param) { + this.sqlSession.insert(id, param); + return param; + } + + @Override + public int logicRemove(E o) { + Assert.notNull(o, "logicRemove : 参数列表不能为NULL"); + return this.sqlSession.update(getSqlIdPrifx() + "entity_logicDelete", o); + } + + @Override + public int logicRemoveMultiCondition(E o) { + Assert.notNull(o, "logicRemoveMultiCondition : 参数列表不能为NULL"); + return this.sqlSession.update(getSqlIdPrifx() + "entity_logicDelete_Multi_Condition", o); + } + + @Override + public int logicRemoveMultiCondition(String id, E o) { + return this.sqlSession.update(id, o); + } + + public int removeById(PK id) { + Assert.notNull(id, "removeById : 参数列表不能为NULL"); + int result = this.sqlSession.delete(getSqlIdPrifx() + "entity_delete", id); + + return result; + } + + public int remove(String id, Object param) { + return this.sqlSession.update(id, param); + } + + @Override + public int delete(String id, Object param) { + return this.sqlSession.delete(id, param); + } + + @Override + public int update(String id, Object param) { + return this.sqlSession.update(id, param); + } + + @Override + public PageAttribute queryPaged(Object baseEntity) { + String sqlId = getSqlIdPrifx() + "entity_list_like"; + return queryPaged(sqlId, baseEntity); + } + + /** + * 分页查询 + */ + @Override + public PageAttribute queryPaged(String statement, Object baseEntity) { + Assert.notNull(statement, "queryPaged ID 不能为NULL"); + Assert.notNull(baseEntity, "queryPaged baseEntity :参数列表不能为NULL"); + BaseEntity realEntity = (BaseEntity) baseEntity; + Long rowsParam = realEntity.getRows(); + Long pageParam = realEntity.getPage(); + Long limitParam = realEntity.getLimit(); + Long offsetParam = realEntity.getOffset(); + int page = 1; + int rows = 10; + + try { + if (rowsParam != null) { + rows = rowsParam.intValue(); + } else if (limitParam != null) { + rows = limitParam.intValue(); + } + + if (pageParam != null) { + page = pageParam.intValue(); + } else if (offsetParam != null) { + page = offsetParam.intValue() / rows + 1; + } + } catch (Exception var12) { + var12.printStackTrace(); + } + PageHelper.startPage(page, rows); + if (StrUtil.isEmpty(realEntity.getDialect_type())) { + PageHelper.dialect_type.set(PageHelper.MYSQL); + } else { + PageHelper.dialect_type.set(realEntity.getDialect_type()); + } + PageHelper.startPage(page, rows); + List list = this.query(statement, baseEntity); + PageAttribute pageInfo = new PageAttribute(list); + return pageInfo; + } + + public List query(String statement, Object baseEntity) { + Assert.notNull(statement, "query :ID 不能为NULL"); + Assert.notNull(baseEntity, "query baseEntity :不能为NULL"); + List list = this.sqlSession.selectList(statement, baseEntity); + return list; + } + + public List query(Object baseEntity) { + + Assert.notNull(baseEntity, "query baseEntity :不能为NULL"); + List list = this.sqlSession.selectList(getSqlIdPrifx() + "entity_list_like", baseEntity); + return list; + } + + @Override + public Integer getCount(Object parameterObject) { + + Integer totalCount = this.sqlSession.selectOne(getSqlIdPrifx() + "entity_count", parameterObject); + + return totalCount; + } + + @Override + public int delete(PK id) { + return this.sqlSession.delete(getSqlIdPrifx() + "entity_delete", id); + } + + @Override + public boolean checkRepeated(E o) { +// Class TargetClass; +// try { +// TargetClass = o.getClass(); +// List fieldList = UtilHelper.getPrimaryNameList(TargetClass); +// String id = BeanUtils.getProperty(o, "id"); +// boolean flag = true; +// if (fieldList == null) +// return false; +// +// Object param = org.springframework.beans.BeanUtils.instantiate(TargetClass); +// for (int i = 0; i < fieldList.size(); ++i) { +// Field field = (Field) fieldList.get(i); +// String name = field.getName(); +// Object tempVal = BeanUtils.getProperty(o, name); +// if ((tempVal != null) && (!("".equals(tempVal)))) { +// flag = false; +// BeanUtils.setProperty(param, name, BeanUtils.getProperty(o, name)); +// } +// +// } +// +// if (flag) +// return false; +// +// List resultList = query((Serializable) param); +// if ((resultList != null) && (resultList.size() > 0)) { +// if ((id == null) || ("".equals(id))) +// return true; +// +// Object tempResult = resultList.get(0); +// String tempId = BeanUtils.getProperty(tempResult, "id"); +// +// return (!(tempId.equals(id))); +// } +// +// return false; +// } catch (Exception e) { +// e.printStackTrace(); +// } + return false; + } + +} diff --git a/common/src/main/java/com/hzya/frame/basedao/dao/RequestDisposeEntityMapper.java b/common/src/main/java/com/hzya/frame/basedao/dao/RequestDisposeEntityMapper.java new file mode 100644 index 00000000..d4ee2bf2 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/dao/RequestDisposeEntityMapper.java @@ -0,0 +1,33 @@ +package com.hzya.frame.basedao.dao; + + +import com.hzya.frame.basedao.entity.RequestDisposeEntity; +import org.apache.ibatis.annotations.Param; + +import java.util.HashMap; +import java.util.List; + +public interface RequestDisposeEntityMapper { + + //根据sql语句查询 + List> selectBySql(@Param("sql") String sql); + + //条件查询 + List> selectByExample(RequestDisposeEntity example); + + //查询数量 + Integer countByExample(RequestDisposeEntity example); + + //单个条件 + Integer insert(RequestDisposeEntity example); + + //批量添加 + Integer insertSelective(RequestDisposeEntity example); + + //修改 + Integer updateByExample(RequestDisposeEntity example); + + //删除 + Integer deleteByExample(RequestDisposeEntity example); + +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/ConditionType.java b/common/src/main/java/com/hzya/frame/basedao/entity/ConditionType.java new file mode 100644 index 00000000..4f5cf71b --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/ConditionType.java @@ -0,0 +1,67 @@ +package com.hzya.frame.basedao.entity; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * @Author lvleigang + * @Description 连接条件 + * @Date 10:40 上午 2022/12/9 + * @return + **/ +public enum ConditionType { + //数据库类型 + 等于( "="), + 不等于( "!="), + 小于( "<"), + 小于等于( "<="), + 大于( ">"), + 大于等于( ">="), + 包含( "like"), + 不包含( "not like"), + 开始以( "like"), + 开始不是以( "not like"), + 结束以( "like"), + 结束不是以( "not like"), + 是null( "is null"), + 不是null( "is not null"), + 是空的( "is ''"), + 不是空的( "is not ''"), + 介于( "between"), + 不介于( "not between"), + 在列表( "in"), + 不在列表( "not in"); + + private String value; + + private ConditionType(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + @Override + public String toString() { + return "ConditionType{" + + "value='" + value + '\'' + + '}'; + } + + /** + * 增加映射方法,并为方法添加@JsonCreator + */ + @JsonCreator + public static ConditionType getDataSourceTypeFromCodeName(String value) { + for (ConditionType dep : ConditionType.values()) { + if (dep.getValue().equals(value)) { + return dep; + } + } + return null; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/ConditionTypeBack.java b/common/src/main/java/com/hzya/frame/basedao/entity/ConditionTypeBack.java new file mode 100644 index 00000000..1114ad98 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/ConditionTypeBack.java @@ -0,0 +1,92 @@ +package com.hzya.frame.basedao.entity; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * @Author lvleigang + * @Description 连接条件 + * @Date 10:40 上午 2022/12/9 + * @return + **/ +public enum ConditionTypeBack { + //数据库类型 + 等于("等于", "="), + 不等于("不等于", "!="), + 小于("小于", "<"), + 小于等于("小于等于", "<="), + 大于("大于", ">"), + 大于等于("大于等于", ">="), + 包含("包含", "like"), + 不包含("不包含", "not like"), + 开始以("开始以", "like"), + 开始不是以("开始不是以", "not like"), + 结束以("结束以", "like"), + 结束不是以("结束不是以", "not like"), + 是null("是null", "is null"), + 不是null("不是null", "is not null"), + 是空的("是空的", "is ''"), + 不是空的("不是空的", "is not ''"), + 介于("介于", "between"), + 不介于("不介于", "not between"), + 在列表("在列表", "in"), + 不在列表("不在列表", "not in"); + + @JsonValue + private String name; + private String value; + + private ConditionTypeBack(String name, String value) { + this.name = name; + this.value = value; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + + + /** + * 增加映射方法,并为方法添加@JsonCreator + */ + @JsonCreator + public static ConditionTypeBack getConditionTypeFromCodeValue(String value) { + for (ConditionTypeBack dep : ConditionTypeBack.values()) { + if (dep.getValue().equals(value)) { + return dep; + } + } + return null; + } + /** + * 增加映射方法,并为方法添加@JsonCreator + */ + @JsonCreator + public static ConditionTypeBack getConditionTypeFromCodeName(String value) { + for (ConditionTypeBack dep : ConditionTypeBack.values()) { + if (dep.getName().equals(value)) { + return dep; + } + } + return null; + } + @Override + public String toString() { + return "ConditionType{" + + "name='" + name + '\'' + + ", value='" + value + '\'' + + '}'; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/ConnectType.java b/common/src/main/java/com/hzya/frame/basedao/entity/ConnectType.java new file mode 100644 index 00000000..b3c32cb2 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/ConnectType.java @@ -0,0 +1,53 @@ +package com.hzya.frame.basedao.entity; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * @Author lvleigang + * @Description 连接类型对象 + * @Date 11:30 上午 2022/12/9 + * @param + * @return + **/ +public enum ConnectType { + AND("AND", "AND"), + OR("OR", "OR"); + //类型 + private String type; + //值 + private String values; + + private ConnectType(String type, String values) { + this.type = type; + this.values = values; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValues() { + return values; + } + + public void setValues(String values) { + this.values = values; + } + + /** + * 增加映射方法,并为方法添加@JsonCreator + */ + @JsonCreator + public static ConnectType getConnectTypeFromCodeName(String value) { + for (ConnectType dep : ConnectType.values()) { + if (dep.getType().equals(value)) { + return dep; + } + } + return null; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/DataSourceType.java b/common/src/main/java/com/hzya/frame/basedao/entity/DataSourceType.java new file mode 100644 index 00000000..daaae90c --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/DataSourceType.java @@ -0,0 +1,50 @@ +package com.hzya.frame.basedao.entity; + +import com.fasterxml.jackson.annotation.JsonCreator; + +public enum DataSourceType { + + //数据库类型 + MYSQL("MYSQL", "MYSQL"), + ORACLE("ORACLE", "ORACLE"); + + + //类型 + private String type; + //描述 + private String desc; + + private DataSourceType(String type, String desc) { + this.type = type; + this.desc = desc; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + /** + * 增加映射方法,并为方法添加@JsonCreator + */ + @JsonCreator + public static DataSourceType getDataSourceTypeFromCodeName(String value) { + for (DataSourceType dep : DataSourceType.values()) { + if (dep.getType().equals(value)) { + return dep; + } + } + return null; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/HttpEntity.java b/common/src/main/java/com/hzya/frame/basedao/entity/HttpEntity.java new file mode 100644 index 00000000..8d756736 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/HttpEntity.java @@ -0,0 +1,32 @@ +package com.hzya.frame.basedao.entity; + +import java.util.Map; + +/** + * @Author lvleigang + * @Description http请求实体类 + * @Date 11:29 上午 2022/12/9 + * @return + **/ +public class HttpEntity { + //head参数 + private Map headers; + //bodys参数 + private Map bodys; + + public Map getHeaders() { + return headers; + } + + public void setHeaders(Map headers) { + this.headers = headers; + } + + public Map getBodys() { + return bodys; + } + + public void setBodys(Map bodys) { + this.bodys = bodys; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/ModifyCriterion.java b/common/src/main/java/com/hzya/frame/basedao/entity/ModifyCriterion.java new file mode 100644 index 00000000..e4e95819 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/ModifyCriterion.java @@ -0,0 +1,121 @@ +package com.hzya.frame.basedao.entity; + +import java.math.BigDecimal; +import java.util.Date; + +/** + * @ClassName ModifyCriterion + * @Description 修改对象 + * @Author llg + * Date 2022/12/3 1:55 下午 + */ +public class ModifyCriterion { + //字段名称 + private String filedName; + //字段值 + private Object filedValue; + //数字类型 + private boolean intValue; + //金额类型 + private boolean decimalValue; + //字符串类型 + private boolean stringValue; + //日期类型 + private boolean dateValue; + + public ModifyCriterion() { + } + + public ModifyCriterion(String filedName, String filedValue) { + this.filedName = filedName; + this.filedValue = filedValue; + this.stringValue = true; + } + public ModifyCriterion(String filedName, int filedValue) { + this.filedName = filedName; + this.filedValue = filedValue; + this.intValue = true; + } + + public ModifyCriterion(String filedName, BigDecimal filedValue) { + this.filedName = filedName; + this.filedValue = filedValue; + this.decimalValue = true; + } + + + + public ModifyCriterion(String filedName, Date filedValue) { + this.filedName = filedName; + this.filedValue = filedValue; + this.dateValue = true; + } + + public ModifyCriterion(int filedValue) { + this.filedValue = filedValue; + this.intValue = true; + } + + public ModifyCriterion(BigDecimal filedValue) { + this.filedValue = filedValue; + this.decimalValue = true; + } + + public ModifyCriterion(String filedValue) { + this.filedValue = filedValue; + this.stringValue = true; + } + + public ModifyCriterion(Date filedValue) { + this.filedValue = filedValue; + this.dateValue = true; + } + + public String getFiledName() { + return filedName; + } + + public void setFiledName(String filedName) { + this.filedName = filedName; + } + + public Object getFiledValue() { + return filedValue; + } + + public void setFiledValue(Object filedValue) { + this.filedValue = filedValue; + } + + public boolean isIntValue() { + return intValue; + } + + public void setIntValue(boolean intValue) { + this.intValue = intValue; + } + + public boolean isDecimalValue() { + return decimalValue; + } + + public void setDecimalValue(boolean decimalValue) { + this.decimalValue = decimalValue; + } + + public boolean isStringValue() { + return stringValue; + } + + public void setStringValue(boolean stringValue) { + this.stringValue = stringValue; + } + + public boolean isDateValue() { + return dateValue; + } + + public void setDateValue(boolean dateValue) { + this.dateValue = dateValue; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/OrderCriterion.java b/common/src/main/java/com/hzya/frame/basedao/entity/OrderCriterion.java new file mode 100644 index 00000000..dcdc5807 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/OrderCriterion.java @@ -0,0 +1,20 @@ +package com.hzya.frame.basedao.entity; + +/** + * @Author lvleigang + * @Description 排序 + * @Date 11:29 上午 2022/12/9 + * @return + **/ +public class OrderCriterion { + private String filed; + private String sortOrder; + + public OrderCriterion(String filed, String sortOrder) { + this.filed = filed; + this.sortOrder = sortOrder; + } + public String getOrderCriterionString() { + return this.filed +" "+this.sortOrder; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/RequestDisposeEntity.java b/common/src/main/java/com/hzya/frame/basedao/entity/RequestDisposeEntity.java new file mode 100644 index 00000000..8599444e --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/RequestDisposeEntity.java @@ -0,0 +1,639 @@ +package com.hzya.frame.basedao.entity; + +import java.util.List; + +/** + * @ClassName RequestEntity + * @Description 请求对象 + * @Author llg + * Date 2022/12/3 1:55 下午 + */ +public class RequestDisposeEntity { + + //查询返回字段 + private List returnCriterions; + //表名 + private String tablename; + //查询条件 + private List wheres; + + //添加/修改 对象 + private List modifys; + //批量修改的字段 + private List batchFileds; + //批量添加/修改 字段 + private List> batchModifys; + + + //排序 利用pageHelper + private List order; + //页数 利用pageHelper + private Integer pageNum; + //数量 利用pageHelper + private Integer pageSize; + + + //数据源类型--暂时没用 + private DataSourceType dataBaseType; + //数据源标识--暂时没用 + private String dataSourceCode; + + + //判断是否有返回字段 + public boolean isReturnValid() { + return this.returnCriterions != null && this.returnCriterions.size() > 0; + } + //判断是否有判断条件 + public boolean isOpinionWheres() { + return this.wheres != null && this.wheres.size() > 0; + } + //判断是否有排序 + public boolean isHavenOrder() { + return this.order != null && this.order.size() > 0; + } + //返回排序string + public String getOrderString() { + StringBuffer stringBuffer = new StringBuffer(); + if (this.order != null && this.order.size() > 0) { + for (int i = 0; i < this.order.size(); i++) { + if (i == 0) { + stringBuffer.append(this.order.get(i).getOrderCriterionString()); + } else { + stringBuffer.append(" , ").append(this.order.get(i).getOrderCriterionString()); + } + } + } + return stringBuffer.toString(); + } + + //判断是否有修改 + public boolean isHaveModifys() { + return this.modifys != null && this.modifys.size() > 0; + } + //判断是否有批量修改字段 + public boolean isHaveBatchFileds() { + return this.batchFileds != null && this.batchFileds.size() > 0; + } + //判断是否有批量修改字段 + public boolean isHaveBatchModifys() { + return this.batchModifys != null && this.batchModifys.size() > 0 + && this.batchModifys.get(0) != null && this.batchModifys.get(0).size() > 0; + } + //public class WheresCriteria { + // //左括号 + // private String leftBracket; + // //字段 + // private String field; + // //条件 + // private String condition; + // //值 + // private Object value; + // //第二个值 + // private Object secondValue; + // //右括号 + // private String rightBracket; + // //类型 + // private String type; + // //连接 + // private String connect; + // + // public String getField() { + // return field; + // } + // + // public void setField(String field) { + // this.field = field; + // } + // + // public String getCondition() { + // return condition; + // } + // + // public void setCondition(String condition) { + // this.condition = condition; + // } + // + // + // public String getType() { + // return type; + // } + // + // public void setType(String type) { + // this.type = type; + // } + // + // public Object getValue() { + // return value; + // } + // + // public void setValue(Object value) { + // this.value = value; + // } + // + // public Object getSecondValue() { + // return secondValue; + // } + // + // public void setSecondValue(Object secondValue) { + // this.secondValue = secondValue; + // } + // + // public String getLeftBracket() { + // return leftBracket; + // } + // + // public void setLeftBracket(String leftBracket) { + // this.leftBracket = leftBracket; + // } + // + // public String getRightBracket() { + // return rightBracket; + // } + // + // public void setRightBracket(String rightBracket) { + // this.rightBracket = rightBracket; + // } + // + // public String getConnect() { + // return connect; + // } + // + // public void setConnect(String connect) { + // this.connect = connect; + // } + //} + // + //public class ModifyCriteria { + // //字段 + // private String field; + // //值 + // private Object value; + // //类型 + // private String type; + // + // public String getField() { + // return field; + // } + // + // public void setField(String field) { + // this.field = field; + // } + // + // public String getType() { + // return type; + // } + // + // public void setType(String type) { + // this.type = type; + // } + // + // public Object getValue() { + // return value; + // } + // + // public void setValue(Object value) { + // this.value = value; + // } + // + //} + // + //public List> getBatchModify() { + // return batchModify; + //} + // + //public void setBatchModify(List> batchModify) { + // this.batchModify = batchModify; + //} + // + //public List getBatchFiled() { + // return batchFiled; + //} + // + //public void setBatchFiled(List batchFiled) { + // this.batchFiled = batchFiled; + //} + // + //public List getOrder() { + // return order; + //} + // + //public void setOrder(List order) { + // this.order = order; + //} + // + //public Integer getPageNum() { + // return pageNum; + //} + // + //public void setPageNum(Integer pageNum) { + // this.pageNum = pageNum; + //} + // + //public Integer getPageSize() { + // return pageSize; + //} + // + //public void setPageSize(Integer pageSize) { + // this.pageSize = pageSize; + //} + // + //public List getFileds() { + // return this.fileds; + //} + // + //public void setFileds(List fileds) { + // this.fileds = fileds; + //} + // + //public List getWheres() { + // return this.wheres; + //} + // + //public void setWheres(List wheres) { + // this.wheres = wheres; + //} + // + //public List getModify() { + // return this.modify; + //} + // + //public void setModify(List modify) { + // this.modify = modify; + //} + // + // + ///** + // * @return java.lang.String + // * @Author lvleigang + // * @Description + // * @Date 3:41 下午 2022/12/7 + // **/ + //public String getOrderString() { + // StringBuffer stringBuffer = new StringBuffer(); + // if (this.order != null && this.order.size() > 0) { + // for (int i = 0; i < this.order.size(); i++) { + // if (i == 0) { + // stringBuffer.append(this.order.get(i).getOrderSort()); + // } else { + // stringBuffer.append(" , ").append(this.order.get(i).getOrderSort()); + // } + // } + // } + // return stringBuffer.toString(); + //} + // + ///** + // * @return java.lang.String + // * @Author lvleigang + // * @Description + // * @Date 3:41 下午 2022/12/7 + // **/ + //public List getInsterModify() throws ParseException { + // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + // List modifyExamples = new ArrayList<>(); + // if (this.modify != null && this.modify.size() > 0) { + // for (int i = 0; i < this.modify.size(); i++) { + // switch (this.modify.get(i).getType()) { + // case "int": + // modifyExamples.add(new ModifyExample(this.modify.get(i).getField(),(Integer) this.modify.get(i).getValue())); + // break; + // case "decimal": + // modifyExamples.add(new ModifyExample(this.modify.get(i).getField(),new BigDecimal(this.modify.get(i).getValue().toString()))); + // break; + // case "string": + // modifyExamples.add(new ModifyExample(this.modify.get(i).getField(),this.modify.get(i).getValue().toString())); + // break; + // case "date": + // modifyExamples.add(new ModifyExample(this.modify.get(i).getField(),simpleDateFormat.parse(this.modify.get(i).getValue().toString()))); + // break; + // default: + // throw new BaseSystemException("type:undefined"); + // } + // } + // } + // return modifyExamples; + //} + //public List> getBatchInsterModify() throws ParseException { + // List> modifyExamples = new ArrayList<>(); + // if (this.batchModify != null && this.batchModify.size() > 0) { + // for (int i = 0; i < this.batchModify.size(); i++) { + // modifyExamples.add(getInsterModifyS(this.batchModify.get(i))); + // } + // } + // return modifyExamples; + //} + //private List getInsterModifyS(List modify) throws ParseException { + // SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + // List modifyExamples = new ArrayList<>(); + // if (modify != null && modify.size() > 0) { + // for (int i = 0; i < modify.size(); i++) { + // switch (modify.get(i).getType()) { + // case "int": + // modifyExamples.add(new ModifyExample(modify.get(i).getField(),(Integer) modify.get(i).getValue())); + // break; + // case "decimal": + // modifyExamples.add(new ModifyExample(modify.get(i).getField(),new BigDecimal(modify.get(i).getValue().toString()))); + // break; + // case "string": + // modifyExamples.add(new ModifyExample(modify.get(i).getField(),modify.get(i).getValue().toString())); + // break; + // case "date": + // modifyExamples.add(new ModifyExample(this.modify.get(i).getField(),simpleDateFormat.parse(modify.get(i).getValue().toString()))); + // break; + // default: + // throw new BaseSystemException("type:undefined"); + // } + // } + // } + // return modifyExamples; + //} + ///** + // * @param + // * @return java.util.List + // * @Author lvleigang + // * @Description 设置where条件 + // * @Date 3:58 下午 2022/12/7 + // **/ + //public List getWhereListds() { + // List criterionList = new ArrayList<>(); + // if (this.wheres != null && this.wheres.size() > 0) { + // for (int i = 0; i < this.wheres.size(); i++) { + // switch (this.wheres.get(i).getCondition()) { + // case "=": + // criterionList.add(andFieldEqualTo(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "!=": + // criterionList.add(andFieldNotEqualTo(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "<": + // criterionList.add(andFieldLessThan(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "<=": + // criterionList.add(andFieldLessThanOrEqualTo(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case ">": + // criterionList.add(andFieldGreaterThan(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case ">=": + // criterionList.add(andFieldGreaterThanOrEqualTo(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "包含": + // criterionList.add(andFieldLike(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), "%" + this.wheres.get(i).getValue() + "%", this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "不包含": + // criterionList.add(andFieldNotLike(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), "%" + this.wheres.get(i).getValue() + "%", this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "开始以": + // criterionList.add( andFieldLike(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue() + "%", this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "开始不是以": + // criterionList.add(andFieldNotLike(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue() + "%", this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "结束以": + // criterionList.add(andFieldLike(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), "%" + this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "结束不是以": + // criterionList.add(andFieldNotLike(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), "%" + this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "是null": + // criterionList.add(andFieldIsNull(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "不是 null": + // criterionList.add(andFieldIsNotNull(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "是空的": + // criterionList.add(andFieldEqualTo(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), "''", this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "不是空的": + // criterionList.add(andFieldNotEqualTo(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), "''", this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "介于": + // criterionList.add(andFieldBetween(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).getSecondValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "不介于": + // criterionList.add(andFieldNotBetween(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).getSecondValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "在列表": + // criterionList.add(andFieldIn(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // case "不在列表": + // criterionList.add(andFieldNotIn(this.wheres.get(i).getLeftBracket(), this.wheres.get(i).getField(), this.wheres.get(i).getValue(), this.wheres.get(i).rightBracket, i < (this.wheres.size()-1)? this.wheres.get(i).getConnect():"")); + // break; + // default: + // throw new BaseSystemException("condition:undefined"); + // } + // } + // } + // return criterionList; + //} + // + //public void checkNull(String field) { + // if (field == null || "".equals(field)) { + // throw new RuntimeException("field cannot be null"); + // } + //} + // + ////拼接sql + // + //public Criterion andFieldIsNull(String leftBracket, String field, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " is null", rightBracket, connect); + //} + // + //public Criterion andFieldIsNotNull(String leftBracket, String field, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " is not null", rightBracket, connect); + // + //} + // + //public Criterion andFieldEqualTo(String leftBracket, String field, Object value, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " =", value, rightBracket, connect, field); + //} + // + //public Criterion andFieldNotEqualTo(String leftBracket, String field, Object value, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " <>", value, rightBracket, connect, field); + //} + // + //public Criterion andFieldGreaterThan(String leftBracket, String field, Object value, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " >", value, rightBracket, connect, field); + //} + // + //public Criterion andFieldGreaterThanOrEqualTo(String leftBracket, String field, Object value, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " >=", value, rightBracket, connect, field); + //} + // + //public Criterion andFieldLessThan(String leftBracket, String field, Object value, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " <", value, rightBracket, connect, field); + //} + // + //public Criterion andFieldLessThanOrEqualTo(String leftBracket, String field, Object value, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " <=", value, rightBracket, connect, field); + //} + // + //public Criterion andFieldLike(String leftBracket, String field, Object value, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " like", value, rightBracket, connect, field); + //} + // + //public Criterion andFieldNotLike(String leftBracket, String field, Object value, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " not like", value, rightBracket, connect, field); + //} + // + //public Criterion andFieldIn(String leftBracket, String field, Object values, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " in", values, rightBracket, connect, field); + //} + // + //public Criterion andFieldOr(String leftBracket, String field, List values, String rightBracket, String connect) { + // checkNull(field); + // if (values == null || values.size() == 0) { + // throw new RuntimeException("Value for " + field + " cannot be null"); + // } + // StringBuffer stringBuffer = new StringBuffer(); + // stringBuffer.append("( "); + // for (int i = 0; i < values.size(); i++) { + // if (i != 0) { + // stringBuffer.append(" or "); + // } + // stringBuffer.append(field + " = '" + values.get(i) + "' "); + // } + // stringBuffer.append(" )"); + // return new Criterion(leftBracket, stringBuffer.toString(), rightBracket, connect); + //} + // + //public Criterion andFieldNotIn(String leftBracket, String field, Object values, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " not in", values, rightBracket, connect, field); + //} + // + //public Criterion andFieldBetween(String leftBracket, String field, Object value1, Object value2, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " between", value1, value2, rightBracket, connect, field); + //} + // + //public Criterion andFieldNotBetween(String leftBracket, String field, Object value1, Object value2, String rightBracket, String connect) { + // checkNull(field); + // return new Criterion(leftBracket, field + " not between", value1, value2, rightBracket, connect, field); + //} + + + private RequestDisposeEntity() { + } + + public RequestDisposeEntity(String tablename) { + this.tablename = tablename; + } + + public List getReturnCriterions() { + return returnCriterions; + } + + public void setReturnCriterions(List returnCriterions) { + this.returnCriterions = returnCriterions; + } + + public String getTablename() { + return tablename; + } + + public void setTablename(String tablename) { + this.tablename = tablename; + } + + public List getWheres() { + return wheres; + } + + public void setWheres(List wheres) { + this.wheres = wheres; + } + + public List getModifys() { + return modifys; + } + + public void setModifys(List modifys) { + this.modifys = modifys; + } + + public List getBatchFileds() { + return batchFileds; + } + + public void setBatchFileds(List batchFileds) { + this.batchFileds = batchFileds; + } + + public List> getBatchModifys() { + return batchModifys; + } + + public void setBatchModifys(List> batchModifys) { + this.batchModifys = batchModifys; + } + + public List getOrder() { + return order; + } + + public void setOrder(List order) { + this.order = order; + } + + public Integer getPageNum() { + return pageNum; + } + + public void setPageNum(Integer pageNum) { + this.pageNum = pageNum; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public DataSourceType getDataBaseType() { + return dataBaseType; + } + + public void setDataBaseType(DataSourceType dataBaseType) { + this.dataBaseType = dataBaseType; + } + + public String getDataSourceCode() { + return dataSourceCode; + } + + public void setDataSourceCode(String dataSourceCode) { + this.dataSourceCode = dataSourceCode; + } + + + @Override + public String toString() { + return "RequestDisposeEntity{" + + "returnCriterions=" + returnCriterions + + ", tablename='" + tablename + '\'' + + ", wheres=" + wheres + + ", modifys=" + modifys + + ", batchFileds=" + batchFileds + + ", batchModifys=" + batchModifys + + ", order=" + order + + ", pageNum=" + pageNum + + ", pageSize=" + pageSize + + ", dataBaseType=" + dataBaseType + + ", dataSourceCode='" + dataSourceCode + '\'' + + '}'; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/RequestDisposeEntityMapper.xml b/common/src/main/java/com/hzya/frame/basedao/entity/RequestDisposeEntityMapper.xml new file mode 100644 index 00000000..2e1db2ee --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/RequestDisposeEntityMapper.xml @@ -0,0 +1,208 @@ + + + + + + + + + + ${returnCriterions.sqlFiled} as ${returnCriterions.returnField} , + + + + + * + + + + + + + + + + + + ${wheresCriterion.leftBracket} ${wheresCriterion.filed} ${wheresCriterion.condition} ${wheresCriterion.rightBracket} + ${wheresCriterion.connect} + + + ${wheresCriterion.leftBracket} ${wheresCriterion.filed} ${wheresCriterion.condition} + + + + + + + + + + + + + + + + + + + + + #{wheresCriterion.value} + + + ${wheresCriterion.rightBracket} ${wheresCriterion.connect} + + + ${wheresCriterion.leftBracket} ${wheresCriterion.filed} ${wheresCriterion.condition} #{wheresCriterion.value} and + #{wheresCriterion.secondValue} ${wheresCriterion.rightBracket} ${wheresCriterion.connect} + + + ${wheresCriterion.leftBracket} ${wheresCriterion.filed} ${wheresCriterion.condition} + + #{listItem} + + ${wheresCriterion.rightBracket} ${wheresCriterion.connect} + + + + + + + + + + + + + + + + + + + + + + + insert into ${tablename} ( + + + ${items.filedName} , + + + ) + values ( + + + + + #{items.filedValue,jdbcType=INTEGER} , + + + #{items.filedValue,jdbcType=DECIMAL} , + + + #{items.filedValue,jdbcType=VARCHAR} , + + + #{items.filedValue,jdbcType=TIMESTAMP} , + + + + + ) + + + + + insert into ${tablename} + + + ${items} , + + + + + + + + + #{filedValue.filedValue,jdbcType=INTEGER} , + + + #{filedValue.filedValue,jdbcType=DECIMAL} , + + + #{filedValue.filedValue,jdbcType=VARCHAR} , + + + #{filedValue.filedValue,jdbcType=TIMESTAMP} , + + + + + + + + + update ${tablename} + + + + + + ${items.filedName} = #{items.filedValue,jdbcType=INTEGER} , + + + ${items.filedName} = #{items.filedValue,jdbcType=DECIMAL} , + + + ${items.filedName} = #{items.filedValue,jdbcType=VARCHAR} , + + + ${items.filedName} = #{items.filedValue,jdbcType=TIMESTAMP} , + + + + + + + + + + + + delete from ${tablename} + + + + + diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/ReturnCriterion.java b/common/src/main/java/com/hzya/frame/basedao/entity/ReturnCriterion.java new file mode 100644 index 00000000..b9044edf --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/ReturnCriterion.java @@ -0,0 +1,22 @@ +package com.hzya.frame.basedao.entity; + +/** + * @ClassName ReturnCriterion + * @Description 返回对象 + * @Author llg + * Date 2022/12/3 1:55 下午 + */ +public class ReturnCriterion { + private String sqlFiled; + private String returnField; + + public ReturnCriterion(String sqlFiled) { + this.sqlFiled = sqlFiled; + this.returnField = sqlFiled; + } + + public ReturnCriterion(String sqlFiled, String returnField) { + this.sqlFiled = sqlFiled; + this.returnField = returnField; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/SortOrderType.java b/common/src/main/java/com/hzya/frame/basedao/entity/SortOrderType.java new file mode 100644 index 00000000..66011195 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/SortOrderType.java @@ -0,0 +1,56 @@ +package com.hzya.frame.basedao.entity; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * @Author lvleigang + * @Description 排序对象 + * @Date 11:30 上午 2022/12/9 + * @param null + * @return + **/ +public enum SortOrderType { + DESC("DESC", "DESC"), + ASC("ASC", "ASC"); + //类型 + private String type; + //值 + private String values; + + SortOrderType() { + } + + SortOrderType(String type, String values) { + this.type = type; + this.values = values; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValues() { + return values; + } + + public void setValues(String values) { + this.values = values; + } + + /** + * 增加映射方法,并为方法添加@JsonCreator + */ + @JsonCreator + public static SortOrderType getSortOrderTypeFromCodeName(String value) { + for (SortOrderType dep : SortOrderType.values()) { + if (dep.getType().equals(value)) { + return dep; + } + } + return null; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/entity/WhereCriterion.java b/common/src/main/java/com/hzya/frame/basedao/entity/WhereCriterion.java new file mode 100644 index 00000000..3ec52ec0 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/entity/WhereCriterion.java @@ -0,0 +1,207 @@ +package com.hzya.frame.basedao.entity; + +import java.util.List; + +/** + * @ClassName WhereCriterion + * @Description 条件对象 + * @Author llg + * Date 2022/12/3 1:55 下午 + */ +public class WhereCriterion { + //左括号 + private String leftBracket; + //字段 + private String filed; + //条件 + private String condition; + private ConditionType conditions; + //值 + private Object value; + //第二个值 + private Object secondValue; + //右括号 + private String rightBracket; + //连接 + private ConnectType connect; + //没有值 + private boolean noValue; + //单值 + private boolean singleValue; + //之间值 + private boolean betweenValue; + //list值 + private boolean listValue; + //类型的处理程序 + private String typeHandler; + + private WhereCriterion() { + } + + public WhereCriterion(String leftBracket, String filed, String condition, String rightBracket, ConnectType connect) { + super(); + this.leftBracket = leftBracket; + this.filed = filed; + this.condition = condition; + this.typeHandler = null; + this.noValue = true; + this.rightBracket = rightBracket; + this.connect = connect; + } + public WhereCriterion(String leftBracket,String filed, String condition, Object value, String rightBracket, ConnectType connect, String typeHandler) { + super(); + this.leftBracket = leftBracket; + this.filed = filed; + this.condition = condition; + this.value = value; + this.rightBracket = rightBracket; + this.connect = connect; + this.typeHandler = typeHandler; + if (value instanceof List) { + this.listValue = true; + } else { + this.singleValue = true; + } + } + public WhereCriterion(String leftBracket,String filed, String condition, Object value, String rightBracket, ConnectType connect) { + this(leftBracket, filed, condition, value,rightBracket,connect, null); + } + public WhereCriterion(String leftBracket,String filed, String condition, Object value, Object secondValue, String rightBracket, ConnectType connect, String typeHandler) { + super(); + this.leftBracket = leftBracket; + this.filed = filed; + this.condition = condition; + this.value = value; + this.secondValue = secondValue; + this.rightBracket = rightBracket; + this.connect = connect; + this.typeHandler = typeHandler; + this.betweenValue = true; + } + public WhereCriterion(String leftBracket, String filed, String condition, Object value, Object secondValue, String rightBracket, ConnectType connect) { + this(leftBracket,filed,condition, value, secondValue,rightBracket,connect, null); + } + + public String getLeftBracket() { + return leftBracket; + } + + public void setLeftBracket(String leftBracket) { + this.leftBracket = leftBracket; + } + + public String getFiled() { + return filed; + } + + public void setFiled(String filed) { + this.filed = filed; + } + + public String getCondition() { + return condition; + } + + public void setCondition(String condition) { + this.condition = condition; + } + + public Object getValue() { + return value; + } + + public void setValue(Object value) { + this.value = value; + } + + public Object getSecondValue() { + return secondValue; + } + + public void setSecondValue(Object secondValue) { + this.secondValue = secondValue; + } + + public String getRightBracket() { + return rightBracket; + } + + public void setRightBracket(String rightBracket) { + this.rightBracket = rightBracket; + } + + public ConnectType getConnect() { + return connect; + } + + public void setConnect(ConnectType connect) { + this.connect = connect; + } + + public boolean isNoValue() { + return noValue; + } + + public void setNoValue(boolean noValue) { + this.noValue = noValue; + } + + public boolean isSingleValue() { + return singleValue; + } + + public void setSingleValue(boolean singleValue) { + this.singleValue = singleValue; + } + + public boolean isBetweenValue() { + return betweenValue; + } + + public void setBetweenValue(boolean betweenValue) { + this.betweenValue = betweenValue; + } + + public boolean isListValue() { + return listValue; + } + + public void setListValue(boolean listValue) { + this.listValue = listValue; + } + + public String getTypeHandler() { + return typeHandler; + } + + public void setTypeHandler(String typeHandler) { + this.typeHandler = typeHandler; + } + + public ConditionType getConditions() { + return conditions; + } + + public void setConditions(ConditionType conditions) { + this.conditions = conditions; + } + + @Override + public String toString() { + return "WhereCriterion{" + + "leftBracket='" + leftBracket + '\'' + + ", filed='" + filed + '\'' + + ", condition='" + condition + '\'' + + ", conditions=" + conditions + + ", value=" + value + + ", secondValue=" + secondValue + + ", rightBracket='" + rightBracket + '\'' + + ", connect=" + connect + + ", noValue=" + noValue + + ", singleValue=" + singleValue + + ", betweenValue=" + betweenValue + + ", listValue=" + listValue + + ", typeHandler='" + typeHandler + '\'' + + '}'; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/service/BaseDaoUtil.java b/common/src/main/java/com/hzya/frame/basedao/service/BaseDaoUtil.java new file mode 100644 index 00000000..b1aa8cf1 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/service/BaseDaoUtil.java @@ -0,0 +1,374 @@ +package com.hzya.frame.basedao.service; + +import com.github.pagehelper.PageInfo; +import com.hzya.frame.basedao.entity.ModifyCriterion; +import com.hzya.frame.basedao.entity.OrderCriterion; +import com.hzya.frame.basedao.entity.RequestDisposeEntity; +import com.hzya.frame.basedao.entity.ReturnCriterion; +import com.hzya.frame.basedao.entity.WhereCriterion; + +import java.util.HashMap; +import java.util.List; + +/** + * @Author lvleigang + * @Description 连接对外提供的查询类 + * @Date 1:45 下午 2022/12/3 + **/ +public interface BaseDaoUtil { + + /** + * @param tablename 表名称 + * @return java.lang.Integer + * @Author lvleigang + * @Description 查询数量 + * @Date 8:46 上午 2022/12/7 + **/ + Integer selectCount(String tablename); + + /** + * @param tablename 表名称 + * @param list 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 根据条件查询数量 + * @Date 9:06 上午 2022/12/7 + **/ + Integer selectCount(String tablename, List list); + + /** + * 查询一个对象 + * @param tablename 表名 + * @param whereList 条件列表 + * @return + */ + HashMap selectOne(String tablename, List whereList); + + /** + * 查询一个对象 + * @param tablename 表名 + * @param returnCriterionList 返回字段列表 + * @param whereList 查询条件列表 + * @return + */ + HashMap selectOne(String tablename, List returnCriterionList,List whereList); + /** + * 根据id查询 + * @param tablename + * @param id + * @return + */ + HashMap selectById(String tablename,String id); + + /** + * 根据id查询 + * @param tablename 表名 + * @param id + * @param returnCriterionList 返回字段列表 + * @return + */ + HashMap selectById(String tablename,String id,List returnCriterionList); + + /** + * @param tablename + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名查询数据 + * @Date 9:08 上午 2022/12/7 + **/ + List> selectList(String tablename); + /** + * @param tablename + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名查询数据 + * @Date 9:08 上午 2022/12/7 + **/ + List> selectList(String tablename,List returnCriterionList, List whereList); + + /** + * @param tablename 表名称 + * @param whereList 查询条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件查询数据 + * @Date 9:15 上午 2022/12/7 + **/ + List> selectWhereList(String tablename, List whereList); + + /** + * @param tablename 表名称 + * @param returnCriterionList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名查询数据,且设置返回字段 + * @Date 9:15 上午 2022/12/7 + **/ + List> selectReturnList(String tablename, List returnCriterionList); + + /** + * @param tablename 表名称 + * @param order 排序 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名排序查询数据 + * @Date 9:16 上午 2022/12/7 + **/ + List> selectList(String tablename, List order); + + /** + * @param tablename 表名称 + * @param order 排序 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + List> selectWhereList(String tablename, List order, List whereList); + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和返回字段,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + List> selectReturnList(String tablename, List order, List returnCriterionList); + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名称和条件,设置返回字段排序查询时间 + * @Date 9:18 上午 2022/12/7 + **/ + List> selectList(String tablename, List order, List returnCriterionListList, List whereList); + + + /** + * @param tablename + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名分页查询数据,使用默认分页 + * @Date 9:08 上午 2022/12/7 + **/ + PageInfo selectPage(String tablename); + + /** + * @param tablename + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名分页查询数据 + * @Date 9:08 上午 2022/12/7 + **/ + PageInfo selectPage(String tablename, Integer pageNum, Integer pageSize); + + /** + * @param tablename 表名称 + * @param whereList 查询条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件分页查询数据 + * @Date 9:15 上午 2022/12/7 + **/ + PageInfo selectWherePage(String tablename, List whereList); + + /** + * @param tablename 表名称 + * @param whereList 查询条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件分页查询数据 + * @Date 9:15 上午 2022/12/7 + **/ + PageInfo selectWherePage(String tablename, List whereList, Integer pageNum, Integer pageSize); + + /** + * @param tablename 表名称 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名分页查询数据,且设置返回字段 + * @Date 9:15 上午 2022/12/7 + **/ + PageInfo selectReturnPage(String tablename, List returnCriterionListList); + + /** + * @param tablename 表名称 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名分页查询数据,且设置返回字段 + * @Date 9:15 上午 2022/12/7 + **/ + PageInfo selectReturnPage(String tablename, List returnCriterionListList, Integer pageNum, Integer pageSize); + + /** + * @param tablename 表名称 + * @param order 排序 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名排序查询数据 + * @Date 9:16 上午 2022/12/7 + **/ + PageInfo selectPage(String tablename, List order); + + /** + * @param tablename 表名称 + * @param order 排序 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名排序查询数据 + * @Date 9:16 上午 2022/12/7 + **/ + PageInfo selectPage(String tablename,List order, Integer pageNum, Integer pageSize); + + /** + * @param tablename 表名称 + * @param order 排序 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + PageInfo selectWherePage(String tablename,List order, List whereList); + + /** + * @param tablename 表名称 + * @param order 排序 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + PageInfo selectWherePage(String tablename, List order, List whereList, Integer pageNum, Integer pageSize); + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和返回字段,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + PageInfo selectReturnPage(String tablename,List order, List returnCriterionListList); + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和返回字段,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + PageInfo selectReturnPage(String tablename,List order, List returnCriterionListList, Integer pageNum, Integer pageSize); + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名称和条件,设置返回字段排序查询时间 + * @Date 9:18 上午 2022/12/7 + **/ + PageInfo selectPage(String tablename,List order, List returnCriterionListList, List whereList); + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名称和条件,设置返回字段排序查询时间 + * @Date 9:18 上午 2022/12/7 + **/ + PageInfo selectPage(String tablename, List order, List returnCriterionListList, List whereList, Integer pageNum, Integer pageSize); + + /** + * @param tablename 表名称 + * @param modifyExamples 单个对象值 + * @return java.lang.Integer + * @Author lvleigang + * @Description 添加单条记录 + * @Date 9:27 上午 2022/12/7 + **/ + Integer insterOne(String tablename, List modifyExamples); + + /** + * @param tablename 表名称 + * @param filedExamples 字段名称 + * @param selectiveModifyExamples 多个对象值 + * @return java.lang.Integer + * @Author lvleigang + * @Description 添加多条记录 + * @Date 9:27 上午 2022/12/7 + **/ + Integer insterList(String tablename, List filedExamples, List> selectiveModifyExamples); + + /** + * @param tablename 表名称 + * @param modifyExamples 需要修改后的数据 + * @param whereList 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 修改数据 + * @Date 9:27 上午 2022/12/7 + **/ + Integer update(String tablename, List modifyExamples, List whereList); + + + /** + * @param tablename 表名称 + * @param whereList 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 逻辑删除数据 + * @Date 9:27 上午 2022/12/7 + **/ + Integer deleteLogic(String tablename, List modifyExamples, List whereList); + + /** + * @param tablename 表名称 + * @param id id + * @return java.lang.Integer + * @Author lvleigang + * @Description 删除数据 + * @Date 9:27 上午 2022/12/7 + **/ + Integer deleteLogic(String tablename, String id); + + /** + * @param tablename 表名称 + * @param whereList 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 删除数据 + * @Date 9:27 上午 2022/12/7 + **/ + Integer delete(String tablename, List whereList); + + /** + * @param tablename 表名称 + * @param id 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 删除数据 + * @Date 9:27 上午 2022/12/7 + **/ + Integer delete(String tablename, String id); + RequestDisposeEntity setJdbcExample(String tablename, List order, List returnCriterionListList, List whereList, Integer pageNum, Integer pageSize); + +} diff --git a/common/src/main/java/com/hzya/frame/basedao/service/GeneralService.java b/common/src/main/java/com/hzya/frame/basedao/service/GeneralService.java new file mode 100644 index 00000000..c71597ef --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/service/GeneralService.java @@ -0,0 +1,138 @@ +package com.hzya.frame.basedao.service; + +import com.alibaba.fastjson.JSONObject; +import com.hzya.frame.web.entity.JsonResultEntity; + +/** + * @Author lvleigang + * @Description 通用service + * @Date 9:34 上午 2022/12/7 + * @return + **/ +public interface GeneralService { + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询list + * @Date 9:40 上午 2022/12/7 + **/ + JsonResultEntity selectList(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询list + * @Date 9:40 上午 2022/12/7 + **/ + JsonResultEntity selectListSimple(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询page + * @Date 9:40 上午 2022/12/7 + **/ + JsonResultEntity selectPage(JSONObject jsonObject); + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询page + * @Date 9:40 上午 2022/12/7 + **/ + JsonResultEntity selectPageSimple(JSONObject jsonObject); + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 添加 + * @Date 9:40 上午 2022/12/7 + **/ + JsonResultEntity inster(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 添加list + * @Date 9:41 上午 2022/12/7 + **/ + JsonResultEntity insterList(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 修改 + * @Date 9:41 上午 2022/12/7 + **/ + JsonResultEntity update(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 删除 + * @Date 9:41 上午 2022/12/7 + **/ + JsonResultEntity delete(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询字段 // todo 暂时不对 + * @Date 9:41 上午 2022/12/7 + **/ + JsonResultEntity defaultField(JSONObject jsonObject); + + //******************************* + + /** + * @Author lvleigang + * @Description 查询树-配置通用接口 ok + * @Date 3:21 下午 2023/2/14 + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + **/ + JsonResultEntity queryTree(JSONObject jsonObject); + + /** + * @Author lvleigang + * @Description 删除树-配置通用接口 ok + * @Date 3:21 下午 2023/2/14 + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + **/ + JsonResultEntity delectTree(JSONObject jsonObject); + + /** + * @Author lvleigang + * @Description 查询树节点下级的节点数据 ok + * @Date 3:21 下午 2023/2/14 + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + **/ + JsonResultEntity selectTreeSubordinateList(JSONObject jsonObject); + /** + * @Author lvleigang + * @Description 查询树节点下面所有的递归节点数据 ok + * @Date 3:21 下午 2023/2/14 + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + **/ + JsonResultEntity selectTreeAllList(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询数据字典 + * @Date 9:40 上午 2022/12/7 + **/ + JsonResultEntity selectDictionaryshop(JSONObject jsonObject); + +} diff --git a/common/src/main/java/com/hzya/frame/basedao/service/IBaseService.java b/common/src/main/java/com/hzya/frame/basedao/service/IBaseService.java new file mode 100644 index 00000000..83cf34c1 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/service/IBaseService.java @@ -0,0 +1,54 @@ +package com.hzya.frame.basedao.service; + + +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.PageInfo; +import com.hzya.frame.page.PageAttribute; +import com.hzya.frame.web.entity.JsonResultEntity; + +import java.io.Serializable; +import java.util.List; + +public interface IBaseService { + E get(PK paramPK); + + int removeById(PK paramPK) throws Exception; + + int logicRemove(E e) throws Exception; + + int logicRemoveMultiCondition(E paramE) throws Exception; + + E saveOrUpdate(E paramE) throws Exception; + + E save(E paramE) throws Exception; + + E update(E paramE) throws Exception; + + E queryOne(E paramE); + + List getAll(); + + List query(E paramE); + + List queryByLike(E paramE); + + List queryByOr(E paramE); + + PageAttribute queryPaged(String paramString, E paramE); + + PageAttribute queryPaged(E paramE); + + boolean checkRepeated(E paramE); + + //***************前端分页************* + JsonResultEntity queryPagedJson(JSONObject jsonObject); + //***************前端list************* + JsonResultEntity queryListJson(JSONObject jsonObject); + //***************前端保存************* + JsonResultEntity saveJson(JSONObject jsonObject); + //***************前端修改************* + JsonResultEntity updateJson(JSONObject jsonObject); + //***************前端删除************* + JsonResultEntity deleteJson(JSONObject jsonObject); + +} diff --git a/common/src/main/java/com/hzya/frame/basedao/service/JdbcService.java b/common/src/main/java/com/hzya/frame/basedao/service/JdbcService.java new file mode 100644 index 00000000..26498056 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/service/JdbcService.java @@ -0,0 +1,100 @@ +package com.hzya.frame.basedao.service; + +import com.github.pagehelper.PageInfo; +import com.hzya.frame.basedao.entity.RequestDisposeEntity; + +import java.util.HashMap; +import java.util.List; + +/** + * @Author lvleigang + * @Description jdbd 连接对外提供的类 + * @Date 1:45 下午 2022/12/3 + **/ +public interface JdbcService { + + /** + * @param example + * @return int + * @Author lvleigang + * @Description 查询总数 + * @Date 2:51 下午 2022/12/3 + **/ + int countByExample(RequestDisposeEntity example); + + /** + * @param example + * @return java.util.List + * @Author lvleigang + * @Description 查询数据 + * @Date 2:53 下午 2022/12/3 + **/ + List> selectByExample(RequestDisposeEntity example); + + /** + * @param sql + * @return java.util.List + * @Author lvleigang + * @Description 自定义sql查询查询 + * @Date 2:53 下午 2022/12/3 + **/ + List> selectByExample(String sql); + + /** + * @param example + * @return PageInfo + * @Author lvleigang + * @Description 分页查询数据 + * @Date 2:53 下午 2022/12/3 + **/ + PageInfo queryPageByExample(RequestDisposeEntity example); + + /** + * @param sql + * @return PageInfo + * @Author lvleigang + * @Description 分页查询数据 + * @Date 2:53 下午 2022/12/3 + **/ + PageInfo queryPageByExample(String sql); + + /** + * @param example + * @return int + * @Author lvleigang + * @Description 添加数据 + * @Date 2:52 下午 2022/12/3 + **/ + Integer insert(RequestDisposeEntity example); + + + /** + * @param example + * @return int + * @Author lvleigang + * @Description 批量添加数据 + * @Date 2:53 下午 2022/12/3 + **/ + int insertSelective(RequestDisposeEntity example); + + /** + * @param example + * @return int + * @Author lvleigang + * @Description 删除 + * @Date 2:52 下午 2022/12/3 + **/ + int deleteByExample(RequestDisposeEntity example); + + + /** + * @param example + * @return int + * @Author lvleigang + * @Description 根据条件修改 + * @Date 2:54 下午 2022/12/3 + **/ + int updateByExample(RequestDisposeEntity example); + + +} diff --git a/common/src/main/java/com/hzya/frame/basedao/service/impl/BaseDaoUtilImpl.java b/common/src/main/java/com/hzya/frame/basedao/service/impl/BaseDaoUtilImpl.java new file mode 100644 index 00000000..2744d558 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/service/impl/BaseDaoUtilImpl.java @@ -0,0 +1,881 @@ +package com.hzya.frame.basedao.service.impl; + +import com.github.pagehelper.PageInfo; +import com.hzya.frame.basedao.entity.ConditionType; +import com.hzya.frame.basedao.entity.ConnectType; +import com.hzya.frame.basedao.entity.ModifyCriterion; +import com.hzya.frame.basedao.entity.OrderCriterion; +import com.hzya.frame.basedao.entity.RequestDisposeEntity; +import com.hzya.frame.basedao.entity.ReturnCriterion; +import com.hzya.frame.basedao.entity.WhereCriterion; +import com.hzya.frame.basedao.service.BaseDaoUtil; +import com.hzya.frame.basedao.service.JdbcService; +import org.apache.commons.collections.CollectionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * @Author lvleigang + * @Description 连接对外提供的类 + * @Date 1:45 下午 2022/12/3 + **/ +@Service +public class BaseDaoUtilImpl implements BaseDaoUtil { + + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + private static HashMap> filedMap; + private static List orderCriterionList; + static { + filedMap = new HashMap<>(); + List returnCriteria = new ArrayList<>(); + ReturnCriterion id = new ReturnCriterion("id"); + returnCriteria.add(id); + ReturnCriterion age = new ReturnCriterion("age"); + returnCriteria.add(age); + ReturnCriterion name = new ReturnCriterion("name"); + returnCriteria.add(name); + ReturnCriterion updateDate = new ReturnCriterion("update_date", "updateDate"); + returnCriteria.add(updateDate); + ReturnCriterion hireDate = new ReturnCriterion("hire_date", "hireDate"); + returnCriteria.add(hireDate); + ReturnCriterion price = new ReturnCriterion("price"); + returnCriteria.add(price); + filedMap.put("sys_testjdbc", returnCriteria); + } + static { + orderCriterionList = new ArrayList<>(); + orderCriterionList.add(new OrderCriterion("id", "ASC")); + } + + @Resource + JdbcService jdbcService; + + /** + * @param tablename 表名称 + * @return java.lang.Integer + * @Author lvleigang + * @Description 查询数量 + * @Date 8:46 上午 2022/12/7 + **/ + @Override + public Integer selectCount(String tablename) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, null, null, null); + //调用方法 + Integer counts = jdbcService.countByExample(example); + return counts; + } + + + + /** + * @param tablename 表名称 + * @param whereList 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 根据条件查询数量 + * @Date 9:06 上午 2022/12/7 + **/ + @Override + public Integer selectCount(String tablename, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, whereList, null, null); + //调用方法 + Integer counts = jdbcService.countByExample(example); + return counts; + } + + /** + * 查询一个对象 + * + * @param tablename 表名 + * @param whereList 条件列表 + * @return + */ + @Override + public HashMap selectOne(String tablename, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, whereList, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + if (CollectionUtils.isNotEmpty(list)) { + if (list.size() == 1){ + return list.get(0); + }else { + throw new RuntimeException("select one but found"+list.size()); + } + } + return null; + } + + /** + * 查询一个对象 + * + * @param tablename 表名 + * @param returnCriterionList 返回字段列表 + * @param whereList 查询条件列表 + * @return + */ + @Override + public HashMap selectOne(String tablename, List returnCriterionList, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, returnCriterionList, whereList, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + if (CollectionUtils.isNotEmpty(list)) { + if (list.size() == 1){ + return list.get(0); + }else { + throw new RuntimeException("select one but found"+list.size()); + } + } + return null; + } + + /** + * 根据id查询 + * + * @param tablename + * @param id + * @return + */ + @Override + public HashMap selectById(String tablename, String id) { + List whereList = new ArrayList<>(); + WhereCriterion whereCriterion = new WhereCriterion("","id", ConditionType.等于.getValue(), id,"", ConnectType.AND); + whereList.add(whereCriterion); + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, whereList, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + if (CollectionUtils.isNotEmpty(list)) { + if (list.size() == 1){ + return list.get(0); + }else { + throw new RuntimeException("select one but found"+list.size()); + } + } + return null; + } + + /** + * 根据id查询 + * + * @param tablename 表名 + * @param id + * @param returnCriterionList 返回字段列表 + * @return + */ + @Override + public HashMap selectById(String tablename, String id, List returnCriterionList) { + List whereList = new ArrayList<>(); + WhereCriterion whereCriterion = new WhereCriterion("","id", ConditionType.等于.getValue(), id,"", ConnectType.AND); + whereList.add(whereCriterion); + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, returnCriterionList, whereList, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + if (CollectionUtils.isNotEmpty(list)) { + if (list.size() == 1){ + return list.get(0); + }else { + throw new RuntimeException("select one but found"+list.size()); + } + } + return null; + } + + /** + * @param tablename + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名查询数据 + * @Date 9:08 上午 2022/12/7 + **/ + @Override + public List> selectList(String tablename) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, null, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + return list; + } + + /** + * @param tablename 表名称 + * @param whereList 查询条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件查询数据 + * @Date 9:15 上午 2022/12/7 + **/ + @Override + public List> selectWhereList(String tablename, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, whereList, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + return list; + } + + /** + * @param tablename 表名称 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名查询数据,且设置返回字段 + * @Date 9:15 上午 2022/12/7 + **/ + @Override + public List> selectReturnList(String tablename, List returnCriterionListList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, returnCriterionListList, null, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + return list; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名排序查询数据 + * @Date 9:16 上午 2022/12/7 + **/ + @Override + public List> selectList(String tablename, List order) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, null, null, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + return list; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + @Override + public List> selectWhereList(String tablename, List order, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, null, whereList, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + return list; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和返回字段,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + @Override + public List> selectReturnList(String tablename, List order, List returnCriterionListList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, returnCriterionListList, null, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + return list; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名称和条件,设置返回字段排序查询时间 + * @Date 9:18 上午 2022/12/7 + **/ + @Override + public List> selectList(String tablename, List order, List returnCriterionListList, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, returnCriterionListList, whereList, null, null); + //调用方法 + logger.info("getWheres:"+example.toString()); + List> list = jdbcService.selectByExample(example); + return list; + } + /** + * @param tablename 表名称 + * @param returnCriterionListList 返回 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名称和条件,设置返回字段排序查询时间 + * @Date 9:18 上午 2022/12/7 + **/ + @Override + public List> selectList(String tablename, List returnCriterionListList, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, returnCriterionListList, whereList, null, null); + //调用方法 + List> list = jdbcService.selectByExample(example); + return list; + } + + /** + * @param tablename + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名分页查询数据,使用默认分页 + * @Date 9:08 上午 2022/12/7 + **/ + @Override + public PageInfo selectPage(String tablename) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, null, null, null); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名分页查询数据 + * @Date 9:08 上午 2022/12/7 + **/ + @Override + public PageInfo selectPage(String tablename, Integer pageNum, Integer pageSize) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, null, pageNum, pageSize); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param whereList 查询条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件分页查询数据 + * @Date 9:15 上午 2022/12/7 + **/ + @Override + public PageInfo selectWherePage(String tablename, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, whereList, null, null); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param whereList 查询条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件分页查询数据 + * @Date 9:15 上午 2022/12/7 + **/ + @Override + public PageInfo selectWherePage(String tablename, List whereList, Integer pageNum, Integer pageSize) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, null, whereList, pageNum, pageSize); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名分页查询数据,且设置返回字段 + * @Date 9:15 上午 2022/12/7 + **/ + @Override + public PageInfo selectReturnPage(String tablename, List returnCriterionListList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, returnCriterionListList, null, null, null); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名分页查询数据,且设置返回字段 + * @Date 9:15 上午 2022/12/7 + **/ + @Override + public PageInfo selectReturnPage(String tablename, List returnCriterionListList, Integer pageNum, Integer pageSize) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, null, returnCriterionListList, null, pageNum, pageSize); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名排序查询数据 + * @Date 9:16 上午 2022/12/7 + **/ + @Override + public PageInfo selectPage(String tablename, List order) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, null, null, null, null); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名排序查询数据 + * @Date 9:16 上午 2022/12/7 + **/ + @Override + public PageInfo selectPage(String tablename, List order, Integer pageNum, Integer pageSize) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, null, null, pageNum, pageSize); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + @Override + public PageInfo selectWherePage(String tablename, List order, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, null, whereList, null, null); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和条件,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + @Override + public PageInfo selectWherePage(String tablename, List order, List whereList, Integer pageNum, Integer pageSize) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, null, whereList, pageNum, pageSize); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和返回字段,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + @Override + public PageInfo selectReturnPage(String tablename, List order, List returnCriterionListList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, returnCriterionListList, null, null, null); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回字段 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名和返回字段,排序查询数据 + * @Date 9:17 上午 2022/12/7 + **/ + @Override + public PageInfo selectReturnPage(String tablename, List order, List returnCriterionListList, Integer pageNum, Integer pageSize) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, returnCriterionListList, null, pageNum, pageSize); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名称和条件,设置返回字段排序查询时间 + * @Date 9:18 上午 2022/12/7 + **/ + @Override + public PageInfo selectPage(String tablename, List order, List returnCriterionListList, List whereList) { + //设置对象 + RequestDisposeEntity example = setJdbcExample(tablename, order, returnCriterionListList, whereList, null, null); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + /** + * @param tablename 表名称 + * @param order 排序 + * @param returnCriterionListList 返回 + * @param whereList 条件 + * @return java.util.List> + * @Author lvleigang + * @Description 根据表名称和条件,设置返回字段排序查询时间 + * @Date 9:18 上午 2022/12/7 + **/ + @Override + public PageInfo selectPage(String tablename, List order, List returnCriterionListList, List whereList, Integer pageNum, Integer pageSize) { + RequestDisposeEntity example = setJdbcExample(tablename, order, returnCriterionListList, whereList, pageNum, pageSize); + //调用方法 + PageInfo pageInfo = jdbcService.queryPageByExample(example); + return pageInfo; + } + + + /** + * @param tablename 表名称 + * @param modifyExamples 单个对象值 + * @return java.lang.Integer + * @Author lvleigang + * @Description 添加单条记录 + * @Date 9:27 上午 2022/12/7 + **/ + @Override + public Integer insterOne(String tablename, List modifyExamples) { + checkTableName(tablename); + checklist(modifyExamples); + //设置表 + RequestDisposeEntity example = new RequestDisposeEntity(tablename); + example.setModifys(modifyExamples); + //调用方法 + Integer counts = jdbcService.insert(example); + return counts; + } + + + + /** + * @param tablename 表名称 + * @param filedExamples 字段名称 + * @param selectiveModifyExamples 多个对象值 + * @return java.lang.Integer + * @Author lvleigang + * @Description 添加多条记录 + * @Date 9:27 上午 2022/12/7 + **/ + @Override + public Integer insterList(String tablename, List filedExamples, List> selectiveModifyExamples) { + checkTableName(tablename); + checklist(filedExamples); + checklist(selectiveModifyExamples); + //设置表 + RequestDisposeEntity example = new RequestDisposeEntity(tablename); + example.setBatchFileds(filedExamples); + example.setBatchModifys(selectiveModifyExamples); + //调用查询 + Integer counts = jdbcService.insertSelective(example); + return counts; + } + + /** + * @param tablename 表名称 + * @param modifyExamples 需要修改后的数据 + * @param whereList 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 修改数据 + * @Date 9:27 上午 2022/12/7 + **/ + @Override + public Integer update(String tablename, List modifyExamples, List whereList) { + checkTableName(tablename); + checklist(modifyExamples); + checklist(whereList); + //设置表 + RequestDisposeEntity example = new RequestDisposeEntity(tablename); + example.setModifys(modifyExamples); + //设置条件 + example.setWheres(whereList); + //调用方法 + Integer counts = jdbcService.updateByExample(example); + return counts; + } + + /** + * @param tablename 表名称 + * @param whereList 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 逻辑删除数据 + * @Date 9:27 上午 2022/12/7 + **/ + @Override + public Integer deleteLogic(String tablename, List modifyExamples, List whereList) { + checkTableName(tablename); + checklist(modifyExamples); + checklist(whereList); + //设置表 + RequestDisposeEntity example = new RequestDisposeEntity(tablename); + example.setModifys(modifyExamples); + //设置条件 + example.setWheres(whereList); + //调用方法 + Integer counts = jdbcService.updateByExample(example); + return counts; + } + + /** + * @param tablename 表名称 + * @param id id + * @return java.lang.Integer + * @Author lvleigang + * @Description 删除数据 + * @Date 9:27 上午 2022/12/7 + **/ + @Override + public Integer deleteLogic(String tablename, String id) { + checkTableName(tablename); + //设置表 + RequestDisposeEntity example = new RequestDisposeEntity(tablename); + //设置修改后的数据 + List modifyExamples = new ArrayList<>(); + modifyExamples.add(new ModifyCriterion("sts", "N")); + example.setModifys(modifyExamples); + List wheres = new ArrayList<>(); + WhereCriterion whereCriterion = new WhereCriterion("(","id", ConditionType.等于.getValue(), id,")", ConnectType.AND); + wheres.add(whereCriterion); + example.setWheres(wheres); + //调用方法 + Integer counts = jdbcService.updateByExample(example); + return counts; + + } + + /** + * @param tablename 表名称 + * @param whereList 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 删除数据 + * @Date 9:27 上午 2022/12/7 + **/ + @Override + public Integer delete(String tablename, List whereList) { + checkTableName(tablename); + //设置表 + RequestDisposeEntity example = new RequestDisposeEntity(tablename); + if(whereList != null && whereList.size() >0 ){ + //设置条件 + example.setWheres(whereList); + } + //调用方法 + Integer counts = jdbcService.deleteByExample(example); + return counts; + } + + /** + * @param tablename 表名称 + * @param id 条件 + * @return java.lang.Integer + * @Author lvleigang + * @Description 删除数据 + * @Date 9:27 上午 2022/12/7 + **/ + @Override + public Integer delete(String tablename, String id) { + checkTableName(tablename); + //设置表 + RequestDisposeEntity example = new RequestDisposeEntity(tablename); + + //设置条件 + List wheres = new ArrayList<>(); + WhereCriterion whereCriterion = new WhereCriterion("(","id", ConditionType.等于.getValue(), id,")",ConnectType.AND); + wheres.add(whereCriterion); + example.setWheres(wheres); + //调用方法 + Integer counts = jdbcService.deleteByExample(example); + return counts; + } + + /** + * @param tablename + * @return java.util.List + * @Author lvleigang + * @Description 根据表名获取缓存中的字段 + * @Date 11:10 上午 2022/12/7 + **/ + private List getReturnByTablename(String tablename) { + List returnCriteria = null; + if (tablename != null && !"".equals(tablename)) { + returnCriteria = filedMap.get(tablename); + } + return returnCriteria; + } + + /** + * @param tablename + * @return void + * @Author lvleigang + * @Description 校验表名称 + * @Date 11:41 上午 2022/12/7 + **/ + private void checkTableName(String tablename) { + if (tablename == null || "".equals(tablename)) { + throw new RuntimeException("The tablename cannot be empty"); + } + } + + /** + * @param example + * @param order + * @return void + * @Author lvleigang + * @Description 设置排序 + * @Date 11:41 上午 2022/12/7 + **/ + private void setOrder(RequestDisposeEntity example, List order) { + if (order != null && order.size() > 0) { + example.setOrder(order); + } else { + example.setOrder(orderCriterionList); + } + } + + /** + * @param example + * @param tablename + * @param returnCriterionListList + * @return void + * @Author lvleigang + * @Description 设置查询字段 + * @Date 11:42 上午 2022/12/7 + **/ + private void setReturnFiled(RequestDisposeEntity example, String tablename, List returnCriterionListList) { + if (returnCriterionListList != null && returnCriterionListList.size() > 0) { + example.setReturnCriterions(returnCriterionListList); + } else { + //获取缓存中表字段 + List returnCriterionList = getReturnByTablename(tablename); + //如果还没有就 查询 * + if (returnCriterionList != null && returnCriterionList.size() > 0) { + //设置返回字段 + example.setReturnCriterions(returnCriterionListList); + } + } + } + + /** + * @param example + * @param whereList + * @return void + * @Author lvleigang + * @Description 设置where条件 + * @Date 11:43 上午 2022/12/7 + **/ + private void setWhere(RequestDisposeEntity example, List whereList) { + if (whereList != null && whereList.size() > 0) { + example.setWheres(whereList); + } + } + + /** + * @param tablename + * @param order + * @param returnCriterionListList + * @param whereList + * @param pageNum + * @param pageSize + * @return com.hzya.frame.jdbcUtil.entity.JdbcExample + * @Author lvleigang + * @Description 设置查询对象 + * @Date 11:48 上午 2022/12/7 + **/ + @Override + public RequestDisposeEntity setJdbcExample(String tablename, List order, List returnCriterionListList, List whereList, Integer pageNum, Integer pageSize) { + //校验表名 + checkTableName(tablename); + //设置表 + RequestDisposeEntity example = new RequestDisposeEntity(tablename); + //设置排序 + setOrder(example, order); + //设置查询字段 + setReturnFiled(example, tablename, returnCriterionListList); + //设置where条件 + setWhere(example, whereList); + //设置分页 + setPage(example, pageNum, pageSize); + return example; + } + + + /** + * @param example + * @param pageNum + * @param pageSize + * @return void + * @Author lvleigang + * @Description 设置分页 + * @Date 11:46 上午 2022/12/7 + **/ + private void setPage(RequestDisposeEntity example, Integer pageNum, Integer pageSize) { + example.setPageNum(pageNum); + example.setPageSize(pageSize); + } + + /** + * @Author lvleigang + * @Description 校验list + * @Date 1:45 下午 2022/12/7 + * @param list + * @return void + **/ + private void checklist(List list) { + if(list == null || list.size() == 0 ){ + throw new RuntimeException("The list cannot be empty"); + } + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/service/impl/BaseService.java b/common/src/main/java/com/hzya/frame/basedao/service/impl/BaseService.java new file mode 100644 index 00000000..a47efaae --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/service/impl/BaseService.java @@ -0,0 +1,277 @@ +package com.hzya.frame.basedao.service.impl; +import cn.dev33.satoken.stp.StpUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.dynamic.datasource.annotation.DS; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.hzya.frame.basedao.dao.IBaseDao; +import com.hzya.frame.basedao.service.IBaseService; +import com.hzya.frame.page.PageAttribute; +import com.hzya.frame.web.entity.BaseResult; +import com.hzya.frame.web.entity.JsonResultEntity; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import java.io.Serializable; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.List; +import java.util.Map; + +/** + * @author Administrator + */ +public abstract class BaseService implements IBaseService { + + protected Logger logger = LogManager.getLogger(super.getClass()); + protected IBaseDao dao; + private Class entityClass; + private E entity; + public BaseService() { + Class c = super.getClass(); + Type t = c.getGenericSuperclass(); + if (t instanceof ParameterizedType) { + this.entityClass = ((Class) ((ParameterizedType) t).getActualTypeArguments()[0]); + //this.logger.info("enityClass : " + this.entityClass.toString()); + } + } + + @Override + public E get(PK id) { + return this.dao.get(id); + } + + @Override + public int removeById(PK id) throws Exception { + return this.dao.delete(id); + } + + @Override + public int logicRemove(E e) throws Exception { + return this.dao.logicRemove(e); + } + @Override + public int logicRemoveMultiCondition(E e) { + return this.dao.logicRemoveMultiCondition(e); + } + @Override + public List getAll() { + return this.dao.getAll(); + } + + @Override + @DS("#o.dataSourceCode") + public List query(E o) { + return this.dao.query(o); + } + + @Override + public E queryOne(E o) { + List tempList = this.dao.query(o); + if ((tempList != null) && (tempList.size() > 0)) { + return (E) tempList.get(0); + } + + return null; + } + + @Override + public List queryByLike(E o) { + return this.dao.queryByLike(o); + } + /** + * @Author lvleigang + * @Description 获取对象转换成jsonobj + * @Date 11:51 下午 2023/7/10 + * @param key + * @param object + * @return com.alibaba.fastjson.JSONObject + **/ + public JSONObject getstrObj(String key, JSONObject object) { + if (checkStr(object.getString(key)) ) { + return object.getJSONObject(key); + } + return new JSONObject(); + } + @Override + public List queryByOr(E o) { + return this.dao.queryByOr(o); + } + + @Override + public E saveOrUpdate(E o) { + Serializable result = this.dao.saveOrUpdate(o); + return (E) result; + } + + @Override + public E save(E o) throws Exception { + Serializable result = this.dao.save(o); + return (E) result; + } + + @Override + public E update(E o) throws Exception { + Serializable result = this.dao.update(o); + return (E) result; + } + + public PageAttribute queryPaged(String statement, Map parameterMap) { + return this.dao.queryPaged(statement, parameterMap); + } + + @Override + public PageAttribute queryPaged(String statement, E baseEntity) { + return this.dao.queryPaged(statement, baseEntity); + } + + @Override + public PageAttribute queryPaged(E baseEntity) { + return this.dao.queryPaged(baseEntity); + } + + @Override + public JsonResultEntity queryPagedJson(JSONObject object) { + E entity = (E)getData("jsonStr", object,this.entityClass); + Class entityClass = entity.getClass(); + Method[] methods = entityClass.getMethods(); + int pageNum = 1; + int pageSize = 10; + for (Method f : methods) { + String fieldName = f.getName(); + if("getPageSize".equals(fieldName)){ + f.setAccessible(true); + try { + pageSize = (int)f.invoke(entity); + } catch (IllegalAccessException | InvocationTargetException e) { + return BaseResult.getFailureMessageEntity("分页参数错误"); + } + } + if("getPageNum".equals(fieldName)){ + f.setAccessible(true); + try { + pageNum = (int)f.invoke(entity); + } catch (IllegalAccessException | InvocationTargetException e) { + return BaseResult.getFailureMessageEntity("分页参数错误"); + } + } + } + PageHelper.startPage(pageNum, pageSize); + List queryByLike = this.dao.queryByLike(entity); + PageInfo pageInfo = new PageInfo(queryByLike); + return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo); + } + protected T getData(String key, JSONObject jsonObject, Class clz) { + if (checkStr(jsonObject.getString(key)) ) { + return jsonObject.getJSONObject(key).toJavaObject(clz); + } + return null; + } + + protected T getData(String str, Class clz) { + if (checkStr(str) ) { + return JSONObject.parseObject(str).toJavaObject(clz); + } + return null; + } + /** + * @param str + * @return void + * @Author lvleigang + * @Description 校验字符串 + * @Date 11:41 上午 2022/12/7 + **/ + protected Boolean checkStr(String str) { + Boolean flag = true; + if (str == null || "".equals(str)) { + flag = false; + } + return flag; + } + + /** + * @param str + * @return void + * @Author lvleigang + * @Description 校验字符串 + * @Date 11:41 上午 2022/12/7 + **/ + protected Boolean checkInt(Integer str) { + Boolean flag = true; + if (str == null) { + flag = false; + } + return flag; + } + @Override + public boolean checkRepeated(E o) { +// Class TargetClass; +// try { +// TargetClass = o.getClass(); +// List fieldList = UtilHelper.getPrimaryNameList(TargetClass); +// String id = BeanUtils.getProperty(o, "id"); +// if (fieldList == null) +// return false; +// +// Object param = org.springframework.beans.BeanUtils.instantiate(TargetClass); +// for (int i = 0; i < fieldList.size(); ++i) { +// Field field = (Field) fieldList.get(i); +// String name = field.getName(); +// BeanUtils.setProperty(param, name, BeanUtils.getProperty(o, name)); +// } +// List resultList = query((E) param); +// if ((resultList != null) && (resultList.size() > 0)) { +// if ((id == null) || ("".equals(id))) +// return true; +// +// Object tempResult = resultList.get(0); +// String tempId = BeanUtils.getProperty(tempResult, "id"); +// +// return (!(tempId.equals(id))); +// } +// +// return false; +// } catch (Exception e) { +// e.printStackTrace(); +// } + return false; + } + + + @Override + public JsonResultEntity queryListJson(JSONObject object) { + E entity = (E)getData("jsonStr", object,this.entityClass); + List queryByLike = this.dao.queryByLike(entity); + return BaseResult.getSuccessMessageEntity("查询数据成功", queryByLike); + } + + @Override + public JsonResultEntity saveJson(JSONObject object) { + E entity = (E)getData("jsonStr", object,this.entityClass); + E returnEntity = this.dao.save(entity); + return BaseResult.getSuccessMessageEntity("保存数据成功", returnEntity); + } + + @Override + public JsonResultEntity updateJson(JSONObject object) { + E entity = (E)getData("jsonStr", object,this.entityClass); + E returnEntity = this.dao.update(entity); + return BaseResult.getSuccessMessageEntity("修改数据成功", returnEntity); + } + @Override + public JsonResultEntity deleteJson(JSONObject object) { + E entity = (E)getData("jsonStr", object,this.entityClass); + Class entityClass = entity.getClass(); + try { + Method methods = entityClass.getMethod("setModify_user_id",String.class); + methods.invoke(entity, StpUtil.getLoginIdAsString()); + } catch (NoSuchMethodException |IllegalAccessException | InvocationTargetException e) { + return BaseResult.getFailureMessageEntity("设置修改人错误"); + } + int returnEntity = this.dao.logicRemoveMultiCondition(entity); + return BaseResult.getSuccessMessageEntity("删除数据成功", returnEntity); + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/service/impl/GeneralServiceImpl.java b/common/src/main/java/com/hzya/frame/basedao/service/impl/GeneralServiceImpl.java new file mode 100644 index 00000000..c6d6c6f9 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/service/impl/GeneralServiceImpl.java @@ -0,0 +1,905 @@ +package com.hzya.frame.basedao.service.impl; + + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.PageInfo; +import com.hzya.frame.basedao.entity.*; +import com.hzya.frame.basedao.service.GeneralService; +import com.hzya.frame.uuid.UUIDUtils; +import com.hzya.frame.web.entity.BaseResult; +import com.hzya.frame.web.entity.JsonResultEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.*; + +/** + * @Author lvleigang + * @Description 通用service + * @Date 9:34 上午 2022/12/7 + * @return + **/ +@Service(value = "generalServiceImpl") +public class GeneralServiceImpl implements GeneralService { + + public final static Logger log = LoggerFactory.getLogger(GeneralServiceImpl.class); + private static final List defaultWhereCriteria = new ArrayList<>(); + private static final List defaultOrder = new ArrayList<>(); + private static final List defaultFileds = new ArrayList<>(); + private static final List defaultModify = new ArrayList<>(); + + static { + defaultWhereCriteria.add(new WhereCriterion("(", "lvl", ConditionType.等于.getValue(), "0", ")", ConnectType.AND)); + defaultWhereCriteria.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND)); + defaultOrder.add(new OrderCriterion("sorts", "ASC")); + defaultFileds.add(new ReturnCriterion("id", "id")); + defaultFileds.add(new ReturnCriterion("up_id", "up_id")); + defaultModify.add(new ModifyCriterion("sts", "N")); + } + + @Autowired + private BaseDaoUtilImpl baseDaoUtilImpl; + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询list + * @Date 9:40 上午 2022/12/7 + **/ + @Override + public JsonResultEntity selectList(JSONObject jsonObject) { + //校验表名 + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + if (!checkStr(jsonObject.getString("jsonStr"))) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + String jsonStr = jsonObject.getString("jsonStr"); + RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class); + if (requestDisposeEntity == null) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + List fileds = requestDisposeEntity.getReturnCriterions(); + List wheres = requestDisposeEntity.getWheres(); + if (wheres == null) { + wheres = new ArrayList<>(); + } + wheres.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND)); + List order = requestDisposeEntity.getOrder(); + List> list = null; + try { + list = baseDaoUtilImpl.selectList(tablename, order, fileds, wheres); + return BaseResult.getSuccessMessageEntity("查询成功", list); + } catch (Exception e) { + log.error("default:selectList{}", e.getMessage()); + return BaseResult.getFailureMessageEntity("查询失败"); + } + } + + @Override + public JsonResultEntity selectListSimple(JSONObject jsonObject) { + //校验表名 + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + if (!checkStr(jsonObject.getString("jsonStr"))) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + JSONObject queryJson = jsonObject.getJSONObject("jsonStr"); + List wheres = new ArrayList<>(); + wheres.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND)); + List order = new ArrayList<>(); + order.add(new OrderCriterion("sorts", "ASC")); + if (queryJson != null) { + JSONObject stringsJson = queryJson.getJSONObject("strings"); + JSONObject dateJson = queryJson.getJSONObject("date"); + if (stringsJson != null) { + Map stringsMap = stringsJson.getInnerMap(); + if (!stringsMap.isEmpty()) { + for (Map.Entry stringObjectEntry : stringsMap.entrySet()) { + wheres.add(new WhereCriterion("(", stringObjectEntry.getKey(), ConditionType.包含.getValue(), stringObjectEntry.getValue(), ")", ConnectType.AND)); + } + } + } + if (dateJson != null) { + Map dateMap = dateJson.getInnerMap(); + if (!dateMap.isEmpty()) { + for (Map.Entry dateObjectEntry : dateMap.entrySet()) { + JSONObject json = (JSONObject) dateObjectEntry.getValue(); + if (json.getString("start") != null + && !"".equals(json.getString("start")) + && json.getString("end") != null + && !"".equals(json.getString("end"))) { + wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.介于.getValue(), json.getString("start"), json.getString("end"), ")", ConnectType.AND)); + } else if (json.getString("end") != null + && !"".equals(json.getString("end"))) { + wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.小于等于.getValue(), json.getString("end"), ")", ConnectType.AND)); + } else if (json.getString("start") != null + && !"".equals(json.getString("start"))) { + wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.大于等于.getValue(), json.getString("start"), ")", ConnectType.AND)); + } + } + } + } + } + List> list = null; + try { + list = baseDaoUtilImpl.selectWhereList(tablename, order, wheres); + return BaseResult.getSuccessMessageEntity("查询成功", list); + } catch (Exception e) { + log.error("default:selectListSimple{}", e.getMessage()); + return BaseResult.getFailureMessageEntity("查询失败"); + } + } + + @Override + public JsonResultEntity selectPageSimple(JSONObject jsonObject) { + //校验表名 + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + if (!checkStr(jsonObject.getString("jsonStr"))) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + JSONObject queryJson = jsonObject.getJSONObject("jsonStr"); + Integer pageNum = queryJson.getInteger("pageNum"); + Integer pageSize = queryJson.getInteger("pageSize"); + if (pageNum == null || pageSize == null) { + return BaseResult.getFailureMessageEntity("查询请求参数不存在"); + } + List wheres = new ArrayList<>(); + wheres.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND)); + List order = new ArrayList<>(); + order.add(new OrderCriterion("sorts", "ASC")); + if (queryJson != null) { + JSONObject stringsJson = queryJson.getJSONObject("strings"); + JSONObject dateJson = queryJson.getJSONObject("date"); + if (stringsJson != null) { + Map stringsMap = stringsJson.getInnerMap(); + if (!stringsMap.isEmpty()) { + for (Map.Entry stringObjectEntry : stringsMap.entrySet()) { + wheres.add(new WhereCriterion("(", stringObjectEntry.getKey(), ConditionType.包含.getValue(), stringObjectEntry.getValue(), ")", ConnectType.AND)); + } + } + } + if (dateJson != null) { + Map dateMap = dateJson.getInnerMap(); + if (!dateMap.isEmpty()) { + for (Map.Entry dateObjectEntry : dateMap.entrySet()) { + JSONObject json = (JSONObject) dateObjectEntry.getValue(); + if (json.getString("start") != null + && !"".equals(json.getString("start")) + && json.getString("end") != null + && !"".equals(json.getString("end"))) { + wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.介于.getValue(), json.getString("start"), json.getString("end"), ")", ConnectType.AND)); + } else if (json.getString("end") != null + && !"".equals(json.getString("end"))) { + wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.小于等于.getValue(), json.getString("end"), ")", ConnectType.AND)); + } else if (json.getString("start") != null + && !"".equals(json.getString("start"))) { + wheres.add(new WhereCriterion("(", dateObjectEntry.getKey(), ConditionType.大于等于.getValue(), json.getString("start"), ")", ConnectType.AND)); + } + } + } + } + } + PageInfo pageInfo = null; + try { + pageInfo = baseDaoUtilImpl.selectWherePage(tablename, order, wheres, pageNum, pageSize); + return BaseResult.getSuccessMessageEntity("查询成功", pageInfo); + } catch (Exception e) { + log.error("default:selectPageSimple{}", e.getMessage()); + return BaseResult.getFailureMessageEntity("查询失败"); + } + } + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询page + * @Date 9:40 上午 2022/12/7 + **/ + @Override + public JsonResultEntity selectPage(JSONObject jsonObject) { + //校验表名 + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + if (!checkStr(jsonObject.getString("jsonStr"))) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + String jsonStr = jsonObject.getString("jsonStr"); + RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class); + if (requestDisposeEntity == null) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + List fileds = requestDisposeEntity.getReturnCriterions(); + List wheres = requestDisposeEntity.getWheres(); + List order = requestDisposeEntity.getOrder(); + PageInfo pageInfo = null; + try { + pageInfo = baseDaoUtilImpl.selectPage(tablename, order, fileds, wheres, requestDisposeEntity.getPageNum(), requestDisposeEntity.getPageSize()); + return BaseResult.getSuccessMessageEntity("查询成功", pageInfo); + } catch (Exception e) { + log.error("default:selectPage{}", e.getMessage()); + return BaseResult.getFailureMessageEntity("查询失败"); + } + } + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 添加 + * @Date 9:40 上午 2022/12/7 + **/ + @Override + public JsonResultEntity inster(JSONObject jsonObject) { + //校验表名 + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + if (!checkStr(jsonObject.getString("jsonStr"))) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + String jsonStr = jsonObject.getString("jsonStr"); + RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class); + RequestDisposeEntity requestDisposeEntity1 = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class); + if (requestDisposeEntity == null) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + List modifyExamples = requestDisposeEntity.getModifys(); + modifyExamples.add(new ModifyCriterion("id", UUIDUtils.getUUID())); + if (modifyExamples != null && modifyExamples.size() > 0) { + try { + Integer i = baseDaoUtilImpl.insterOne(tablename, modifyExamples); + return BaseResult.getSuccessMessageEntity("保存成功"); + } catch (Exception e) { + log.error("default:inster{}", e.getMessage()); + return BaseResult.getFailureMessageEntity("保存失败"); + } + } else { + return BaseResult.getFailureMessageEntity("保存字段为空"); + } + } + + //public static void main(String[] args) { + // String a = ""; + // + //} + + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 添加list + * @Date 9:41 上午 2022/12/7 + **/ + @Override + public JsonResultEntity insterList(JSONObject jsonObject) { + //校验表名 + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + if (!checkStr(jsonObject.getString("jsonStr"))) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + String jsonStr = jsonObject.getString("jsonStr"); + RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class); + if (requestDisposeEntity == null) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + List> modifyExamples = requestDisposeEntity.getBatchModifys(); + List batchFiled = requestDisposeEntity.getBatchFileds(); + List sqlbatchFiled = new ArrayList<>(); + sqlbatchFiled.add("id"); + sqlbatchFiled.addAll(batchFiled); + if (modifyExamples != null && modifyExamples.size() > 0 && batchFiled != null && batchFiled.size() > 0) { + List> sqlmodifyExamples = new ArrayList<>(); + for (int i = 0; i < modifyExamples.size(); i++) { + List modifyCriteria = new ArrayList<>(); + modifyCriteria.add(new ModifyCriterion("id", UUIDUtils.getUUID())); + modifyCriteria.addAll(modifyExamples.get(i)); + sqlmodifyExamples.add(modifyCriteria); + } + try { + Integer i = baseDaoUtilImpl.insterList(tablename, sqlbatchFiled, sqlmodifyExamples); + return BaseResult.getSuccessMessageEntity("保存成功"); + } catch (Exception e) { + log.error("default:insterList{}", e.getMessage()); + return BaseResult.getFailureMessageEntity("保存失败"); + } + } else { + return BaseResult.getFailureMessageEntity("批量保存字段或值为空"); + } + } + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 修改 + * @Date 9:41 上午 2022/12/7 + **/ + @Override + public JsonResultEntity update(JSONObject jsonObject) { + //校验表名 + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + if (!checkStr(jsonObject.getString("jsonStr"))) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + String jsonStr = jsonObject.getString("jsonStr"); + RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class); + if (requestDisposeEntity == null) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + List wheres = requestDisposeEntity.getWheres(); + List modifyExamples = requestDisposeEntity.getModifys(); + if (modifyExamples != null && modifyExamples.size() > 0) { + try { + Integer i = baseDaoUtilImpl.update(tablename, modifyExamples, wheres); + return BaseResult.getSuccessMessageEntity("修改成功"); + } catch (Exception e) { + log.error("default:update{}", e.getMessage()); + return BaseResult.getFailureMessageEntity("修改失败"); + } + } else { + return BaseResult.getFailureMessageEntity("字段为空"); + } + + } + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 删除 + * @Date 9:41 上午 2022/12/7 + **/ + @Override + public JsonResultEntity delete(JSONObject jsonObject) { + //校验表名 + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + if (!checkStr(jsonObject.getString("jsonStr"))) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + String jsonStr = jsonObject.getString("jsonStr"); + RequestDisposeEntity requestDisposeEntity = JSONObject.parseObject(jsonStr, RequestDisposeEntity.class); + if (requestDisposeEntity == null) { + return BaseResult.getFailureMessageEntity("请求数据不存在"); + } + List wheres = requestDisposeEntity.getWheres(); + try { + Integer i = baseDaoUtilImpl.delete(tablename, wheres); + return BaseResult.getSuccessMessageEntity("删除成功"); + } catch (Exception e) { + log.error("default:delete{}", e.getMessage()); + return BaseResult.getFailureMessageEntity("删除失败"); + } + } + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询字段 + * @Date 9:41 上午 2022/12/7 + **/ + @Override + public JsonResultEntity defaultField(JSONObject jsonObject) { + //校验表名 + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + JSONObject jsonStr = jsonObject.getJSONObject("jsonStr"); + String serverName = jsonStr.getString("serverName"); + if (serverName == null || "".equals(serverName)) { + return BaseResult.getFailureMessageEntity("请求serverName为空"); + } + //根据服务名称查询表缓存表 + List> mapList = querytableCacheByService(tablename, serverName); + if (mapList != null && mapList.size() == 1) { + HashMap map = mapList.get(0); + if (map.get("enable_status") != null) { + if ("1".equals(map.get("enable_status"))) { + List returnCriterionListList1 = setReturnFiled(Arrays.asList("id", "view_name", "view_filed", "datebase_name", "value_type", "show_type", "sorts")); + //获取返回条件,前端可以根据菜单id查询获取下级菜单,或者根据一级菜单等级获取菜单 + List whereList1 = new ArrayList<>(); + WhereCriterion upIdWhereCriterion1 = new WhereCriterion("(", "table_cache_id", ConditionType.等于.getValue(), map.get("id"), "", ConnectType.AND); + WhereCriterion stsWhereCriterion1 = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND); + whereList1.add(upIdWhereCriterion1); + whereList1.add(stsWhereCriterion1); + List order = new ArrayList<>(); + order.add(new OrderCriterion("sorts", "ASC")); + List> mapList1 = baseDaoUtilImpl.selectList("sys_view_filed", order, returnCriterionListList1, whereList1); + if (mapList1 != null && mapList1.size() > 0) { + return BaseResult.getSuccessMessageEntity("查询字段成功", mapList1); + } else { + return BaseResult.getFailureMessageEntity("字段配置表为空"); + } + } else { + return BaseResult.getFailureMessageEntity("该服务已停用"); + } + } else { + return BaseResult.getFailureMessageEntity("表缓存表启停配置错误"); + } + } else { + return BaseResult.getFailureMessageEntity("表缓存表配置错误"); + } + } + + + /** + * @param serverName + * @return java.util.List> + * @Author lvleigang + * @Description 根据服务名称查询表缓存表 + * @Date 2:59 下午 2022/12/15 + **/ + private List> querytableCacheByService(String tablename, String serverName) { + List> mapList = new ArrayList<>(); + //设置只返回id,减少数据库压力 + List returnCriterionListList = setReturnFiled(Arrays.asList("id", "table_service", "table_comment", "table_name", "enable_status")); + //获取返回条件,前端可以根据菜单id查询获取下级菜单,或者根据一级菜单等级获取菜单 + List whereList = new ArrayList<>(); + WhereCriterion upIdWhereCriterion = new WhereCriterion("(", "table_service", ConditionType.等于.getValue(), serverName, "", ConnectType.AND); + WhereCriterion stsWhereCriterion = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND); + whereList.add(upIdWhereCriterion); + whereList.add(stsWhereCriterion); + //查询需要删除的树 + //调用数据查询工具类 + mapList = baseDaoUtilImpl.selectList(tablename, returnCriterionListList, whereList); + return mapList; + } + + private List setReturnFiled(List asList) { + if (asList != null && asList.size() > 0) { + List returnCriterionListList = new ArrayList<>(); + for (int i = 0; i < asList.size(); i++) { + ReturnCriterion criterion = new ReturnCriterion(asList.get(i)); + returnCriterionListList.add(criterion); + } + return returnCriterionListList; + } else { + return null; + } + } + + /** + * @param str + * @return void + * @Author lvleigang + * @Description 校验字符串 + * @Date 11:41 上午 2022/12/7 + **/ + private Boolean checkStr(String str) { + Boolean flag = true; + if (str == null || "".equals(str)) { + flag = false; + } + return flag; + } + + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询树-配置通用接口 + * 需要传入参数 + * 上级ID字段(可以没有,没有查询字段为 up_id ) + * 查询条件(可以没有,如果没有默认两个查询条件 lvl 等于0 sts = Y)(注:这个条件只代入第一次查询,后续查询子集仅根据上下级关联关系) + * 返回字段(可以没有,如果没有返回全部字段 TODO 后续可能会去查询缓存,获取缓存中的返回字段) + * 排序条件(可以没有,如果没有 默认 sorts 正序) + * @Date 3:21 下午 2023/2/14 + **/ + @Override + public JsonResultEntity queryTree(JSONObject jsonObject) { + //校验数据(只校验表名称) + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + JSONObject jsonObject1 = jsonObject.getJSONObject("jsonStr"); + //拼接查询 + //上级字段 + String upID = getStringDataIfNullSetDefault("up_id", "upID", jsonObject1); + //查询条件 + List whereCriteria = getListDataIfNullSetDefault(defaultWhereCriteria, "wheres", jsonObject1, WhereCriterion.class); + //返回字段 + List fileds = getListDataIfNullSetNull("returnCriterions", jsonObject1, ReturnCriterion.class); + //排序条件 + List order = getListDataIfNullSetDefault(defaultOrder, "order", jsonObject1, OrderCriterion.class); + //根据条件查询第一级数据 + //查询数据 + List> mapList = baseDaoUtilImpl.selectList(tablename, order, fileds, whereCriteria); + if (mapList != null && mapList.size() > 0) { + //递归查询子集 + recursiveQueryTree(mapList, tablename, fileds, order, upID); + } + //设置返回对象 + return BaseResult.getSuccessMessageEntity("获取树成功", mapList); + } + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 删除树-配置通用接口-逻辑删除 + * 需要传入参数 + * 上级ID字段(可以没有,没有查询字段为 up_id ) + * 查询条件(可以没有,如果没有默认两个查询条件 lvl 等于0 sts = Y)(注:这个条件只代入第一次查询,后续查询子集仅根据上下级关联关系) + * @Date 3:21 下午 2023/2/14 + **/ + @Override + public JsonResultEntity delectTree(JSONObject jsonObject) { + //校验数据(只校验表名称) + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + JSONObject jsonObject1 = jsonObject.getJSONObject("jsonStr"); + //拼接查询 + //上级字段 + String upID = getStringDataIfNullSetDefault("up_id", "upID", jsonObject1); + List returnCriteria = chectDefaultReturn(upID); + //查询条件 + List whereCriteria = getListDataIfNullSetDefault(defaultWhereCriteria, "wheres", jsonObject1, WhereCriterion.class); + //根据条件查询第一级数据 + //查询数据 + List> mapList = baseDaoUtilImpl.selectList(tablename, returnCriteria, whereCriteria); + if (mapList != null && mapList.size() > 0) { + //递归删除子集 + recursiveDeleteTree(mapList, tablename, upID, returnCriteria); + } + //删除当前主节点 + baseDaoUtilImpl.update(tablename, defaultModify, whereCriteria); + + //设置返回对象 + return BaseResult.getSuccessMessageEntity("删除树成功"); + } + + //判断是否是默认 + private List chectDefaultReturn(String upID) { + if (upID != null && !"up_id".equals(upID.toLowerCase())) { + List returnCriteria = new ArrayList<>(); + returnCriteria.add(new ReturnCriterion("id", "id")); + returnCriteria.add(new ReturnCriterion(upID, upID)); + return returnCriteria; + } else { + return defaultFileds; + } + } + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询树节点下级的节点数据 + * 需要传入参数 + * 上级ID字段(可以没有,没有查询字段为 up_id ) + * 查询条件(必须存在)(注:这个条件只代入第一次查询,后续查询子集仅根据上下级关联关系) + * 返回字段(可以没有,如果没有返回全部字段 TODO 后续可能会去查询缓存,获取缓存中的返回字段) + * 排序条件(可以没有,如果没有 默认 sorts 正序) + * @Date 3:21 下午 2023/2/14 + **/ + @Override + public JsonResultEntity selectTreeSubordinateList(JSONObject jsonObject) { + Integer level = 1; + return selectTreeList(jsonObject, level); + } + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询树节点下面所有的递归节点数据 + * 需要传入参数 + * 上级ID字段(可以没有,没有查询字段为 up_id ) + * 查询条件(必须存在)(注:这个条件只代入第一次查询,后续查询子集仅根据上下级关联关系) + * 返回字段(可以没有,如果没有返回全部字段 TODO 后续可能会去查询缓存,获取缓存中的返回字段) + * 排序条件(可以没有,如果没有 默认 sorts 正序) + * @Date 3:21 下午 2023/2/14 + **/ + @Override + public JsonResultEntity selectTreeAllList(JSONObject jsonObject) { + Integer level = -1; + return selectTreeList(jsonObject, level); + } + + /** + * @param object + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询数据字典 + * @Date 9:25 上午 2023/3/6 + **/ + @Override + public JsonResultEntity selectDictionaryshop(JSONObject object) { + //校验数据(只校验表名称) + if (!checkStr(object.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = object.getString("tableName"); + JSONObject jsonObject = object.getJSONObject("jsonStr"); + List whereCriteria = new ArrayList<>(); + whereCriteria.add(new WhereCriterion("(", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND)); + whereCriteria.add(new WhereCriterion("(", "used_sts", ConditionType.等于.getValue(), "1", ")", ConnectType.AND)); + if (jsonObject != null) { + String tabName = getStringDataIfNullSetDefault(null, "tab_name", jsonObject); + if (tabName != null && !"".equals(tabName)) { + whereCriteria.add(new WhereCriterion("(", "tab_name", ConditionType.等于.getValue(), tabName, ")", ConnectType.AND)); + } + String columnName = getStringDataIfNullSetDefault(null, "column_name", jsonObject); + if (columnName != null && !"".equals(columnName)) { + whereCriteria.add(new WhereCriterion("(", "column_name", ConditionType.等于.getValue(), columnName, ")", ConnectType.AND)); + } + } + List> list = null; + try { + list = baseDaoUtilImpl.selectWhereList(tablename, defaultOrder, whereCriteria); + return BaseResult.getSuccessMessageEntity("查询成功", list); + } catch (Exception e) { + log.error("default:selectList{}", e.getMessage()); + return BaseResult.getFailureMessageEntity("查询失败"); + } + } + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询树节点下面的递归节点数据 + * 需要传入参数 + * 上级ID字段(可以没有,没有查询字段为 up_id ) + * 查询条件(必须存在)(注:这个条件只查当前级别,可以是id 可也以是别的限定条件,查询数据库只能查出一条否则返回错误) + * 返回字段(可以没有,如果没有返回全部字段 TODO 后续可能会去查询缓存,获取缓存中的返回字段) + * 排序条件(可以没有,如果没有 默认 sorts 正序) + * 分页信息(可以没有,如果没有 默认 第一页 10条 ) + * @Date 3:21 下午 2023/2/14 + **/ + private JsonResultEntity selectTreeList(JSONObject jsonObject, Integer level) { + //校验数据(只校验表名称) + if (!checkStr(jsonObject.getString("tableName"))) { + return BaseResult.getFailureMessageEntity("表名不存在"); + } + String tablename = jsonObject.getString("tableName"); + JSONObject jsonObject1 = jsonObject.getJSONObject("jsonStr"); + //拼接查询 + //上级字段 + String upID = getStringDataIfNullSetDefault("up_id", "upID", jsonObject1); + List returnCriteria = chectDefaultReturn(upID); + + //查询条件 + List nodeWheres = getListDataIfNullSetNull("nodeWheres", jsonObject1, WhereCriterion.class); + if (nodeWheres == null && nodeWheres.size() == 0) { + return BaseResult.getFailureMessageEntity("查询条件不存在"); + } + List whereCriteria = getListDataIfNullSetNull("wheres", jsonObject1, WhereCriterion.class); + //返回字段 + List fileds = getListDataIfNullSetNull("returnCriterions", jsonObject1, ReturnCriterion.class); + //排序条件 + List order = getListDataIfNullSetDefault(defaultOrder, "order", jsonObject1, OrderCriterion.class); + + Integer pageNum = getIntegerDataIfNullSetDefault(1, "pageNum", jsonObject1); + Integer pageSize = getIntegerDataIfNullSetDefault(10, "pageSize", jsonObject1); + + //根据条件查询第一级数据 + //查询数据 + List> mapList = baseDaoUtilImpl.selectList(tablename, returnCriteria, nodeWheres); + List ids = null; + if (mapList != null && mapList.size() == 1) { + //递归查询子集 + ids = recursiveQueryTreeListId(mapList, tablename, returnCriteria, upID, level); + } else { + return BaseResult.getFailureMessageEntity("查询当前节点错误"); + } + if (ids != null && ids.size() > 0) { + whereCriteria = whereCriteria == null ? new ArrayList() : whereCriteria; + whereCriteria.add(new WhereCriterion("(", "id", ConditionType.在列表.getValue(), ids, ")", ConnectType.AND)); + PageInfo pageInfo = baseDaoUtilImpl.selectPage(tablename, order, fileds, whereCriteria, pageNum, pageSize); + //设置返回对象 + return BaseResult.getSuccessMessageEntity("获取树列表成功", pageInfo); + } else { + //设置一个空的分页对象返回 + return BaseResult.getSuccessMessageEntity("获取树列表成功", new PageInfo()); + } + } + + /** + * @param mapList 上级数据 + * @param tablename 表名 + * @param defaultFileds 查询字段 + * @param upID 上级id字段 + * @param level 查询级别 + * @return java.util.List + * @Author lvleigang + * @Description 递归查询下级所有的id + * @Date 4:59 下午 2023/2/16 + **/ + private List recursiveQueryTreeListId(List> mapList, String tablename, List defaultFileds, String upID, Integer level) { + //判断是否有数据 + List ids = new ArrayList<>(); + if (level != 0) { + if (mapList != null && mapList.size() > 0) { + for (int i = 0; i < mapList.size(); i++) { + //设置条件,此处递归查询只要设置上级id和状态就行 + List whereList = new ArrayList<>(); + WhereCriterion upIdWhereCriterion = new WhereCriterion("(", upID, ConditionType.等于.getValue(), mapList.get(i).get("id"), "", ConnectType.AND); + WhereCriterion stsWhereCriterion = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND); + whereList.add(upIdWhereCriterion); + whereList.add(stsWhereCriterion); + //查询数据 + List> childList = baseDaoUtilImpl.selectList(tablename, defaultFileds, whereList); + if (childList != null && childList.size() > 0) { + //递归调用 + ids.addAll(recursiveQueryTreeListId(childList, tablename, defaultFileds, upID, --level)); + //设置下级菜单 + childList.stream().forEach(s -> ids.add((String) s.get("id"))); + } + } + } + } + return ids; + } + + private Integer getIntegerDataIfNullSetDefault(Integer defaultValue, String key, JSONObject jsonObject) { + if (checkInt(jsonObject.getInteger(key))) { + return jsonObject.getInteger(key); + } + return defaultValue; + } + + private boolean checkInt(Integer integer) { + Boolean flag = true; + if (integer == null) { + flag = false; + } + return flag; + } + + /** + * @param mapList 数据 + * @param tablename 表明 + * @param upID 上级id字段 + * @return void + * @Author lvleigang + * @Description 递归查询删除数据 + * @Date 2:33 下午 2023/2/15 + **/ + private void recursiveDeleteTree(List> mapList, String tablename, String upID, List returnCriteria) { + //判断是否有数据 + if (mapList != null && mapList.size() > 0) { + for (int i = 0; i < mapList.size(); i++) { + //设置条件,此处递归查询只要设置上级id和状态就行 + List whereList = new ArrayList<>(); + WhereCriterion upIdWhereCriterion = new WhereCriterion("(", upID, ConditionType.等于.getValue(), mapList.get(i).get("id"), "", ConnectType.AND); + WhereCriterion stsWhereCriterion = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND); + whereList.add(upIdWhereCriterion); + whereList.add(stsWhereCriterion); + //查询数据 + List> childList = baseDaoUtilImpl.selectList(tablename, returnCriteria, whereList); + if (childList != null && childList.size() > 0) { + //递归调用 + recursiveDeleteTree(childList, tablename, upID, returnCriteria); + } + //删除当前节点 + baseDaoUtilImpl.update(tablename, defaultModify, whereList); + } + } + } + + /** + * @param mapList + * @param tablename + * @param fileds + * @param order + * @param upID + * @return void + * @Author lvleigang + * @Description 递归查询子集 + * @Date 4:47 下午 2023/2/14 + **/ + private void recursiveQueryTree(List> mapList, String tablename, List fileds, List order, String upID) { + //判断是否有数据 + if (mapList != null && mapList.size() > 0) { + for (int i = 0; i < mapList.size(); i++) { + //设置条件,此处递归查询只要设置上级id和状态就行 + List whereList = new ArrayList<>(); + WhereCriterion upIdWhereCriterion = new WhereCriterion("(", upID, ConditionType.等于.getValue(), mapList.get(i).get("id"), "", ConnectType.AND); + WhereCriterion stsWhereCriterion = new WhereCriterion("", "sts", ConditionType.等于.getValue(), "Y", ")", ConnectType.AND); + whereList.add(upIdWhereCriterion); + whereList.add(stsWhereCriterion); + //查询数据 + List> childList = baseDaoUtilImpl.selectList(tablename, order, fileds, whereList); + if (childList != null && childList.size() > 0) { + //递归调用 + recursiveQueryTree(childList, tablename, fileds, order, upID); + //设置下级菜单 + mapList.get(i).put("childMenu", childList); + } + } + } + } + + /** + * @param key 健 + * @param jsonObject json数据 + * @return java.lang.String + * @Author lvleigang + * @Description 根据key获取数据jsonObject中的数据,如果没有返回null + * @Date 3:41 下午 2023/2/14 + **/ + private List getListDataIfNullSetNull(String key, JSONObject jsonObject, Class clz) { + return getListDataIfNullSetDefault(null, key, jsonObject, clz); + } + + /** + * @param defaultList 默认值 + * @param key 健 + * @param jsonObject json数据 + * @return java.lang.String + * @Author lvleigang + * @Description 根据key获取数据jsonObject中的数据,如果没有设置默认值 + * @Date 3:41 下午 2023/2/14 + **/ + private List getListDataIfNullSetDefault(List defaultList, String key, JSONObject jsonObject, Class clz) { + //checkList 方法可能有漏洞,需要后续测试 + if (checkStr(jsonObject.getString(key)) && checkList(jsonObject.getJSONArray(key))) { + JSONArray jsonArray = jsonObject.getJSONArray(key); + return jsonArray.toJavaList(clz); + } + return defaultList; + } + + /** + * @param jsonArray + * @return boolean + * @Author lvleigang + * @Description 校验数据是否为空 + * @Date 4:18 下午 2023/2/14 + **/ + private boolean checkList(JSONArray jsonArray) { + Boolean flag = true; + if (jsonArray == null || jsonArray.size() == 0) { + flag = false; + } + return flag; + } + + /** + * @param defaultValue 默认值 + * @param key 健 + * @param jsonObject json数据 + * @return java.lang.String + * @Author lvleigang + * @Description 根据key获取数据jsonObject中的数据,如果没有设置默认值 + * @Date 3:41 下午 2023/2/14 + **/ + private String getStringDataIfNullSetDefault(String defaultValue, String key, JSONObject jsonObject) { + if (checkStr(jsonObject.getString(key))) { + return jsonObject.getString(key); + } + return defaultValue; + } +} diff --git a/common/src/main/java/com/hzya/frame/basedao/service/impl/JdbcServiceImpl.java b/common/src/main/java/com/hzya/frame/basedao/service/impl/JdbcServiceImpl.java new file mode 100644 index 00000000..6e10d6bd --- /dev/null +++ b/common/src/main/java/com/hzya/frame/basedao/service/impl/JdbcServiceImpl.java @@ -0,0 +1,223 @@ +package com.hzya.frame.basedao.service.impl; + + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.hzya.frame.basedao.entity.RequestDisposeEntity; +import com.hzya.frame.basedao.service.JdbcService; +import com.hzya.frame.datasource.DataSourceUtil; +import com.hzya.frame.web.exception.BaseSystemException; +import org.apache.ibatis.session.SqlSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.HashMap; +import java.util.List; + +/** + * @Author lvleigang + * @Description jdbd 连接对外提供的类 + * @Date 1:45 下午 2022/12/3 + **/ +@Service +public class JdbcServiceImpl implements JdbcService { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + //默认每页查询数量 + private final Integer pageSize = 10; + + + @Resource + private SqlSession sqlSession; + /** + * @param example + * @return int + * @Author lvleigang + * @Description 查询总数 + * @Date 2:51 下午 2022/12/3 + **/ + @Override + public int countByExample(RequestDisposeEntity example) throws BaseSystemException { + if (example == null) { + throw new RuntimeException("The Example cannot be empty"); + } + //try(SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();) { + int counts = sqlSession.selectOne("countByExample", example); + return counts; + //} + } + + /** + * @param example + * @return java.util.List + * @Author lvleigang + * @Description 查询数据 + * @Date 2:53 下午 2022/12/3 + **/ + @Override + public List> selectByExample(RequestDisposeEntity example) throws BaseSystemException { + if (example == null) { + throw new RuntimeException("The Example cannot be empty"); + } + if (example.isHavenOrder()) { + PageHelper.orderBy(example.getOrderString()); + } + //try(SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();) { + List> list = sqlSession.selectList("selectByExample", example); + return list; + //} + } + /** + * @param sql + * @return java.util.List + * @Author lvleigang + * @Description 自定义sql查询查询 + * @Date 2:53 下午 2022/12/3 + **/ + @Override + public List> selectByExample(String sql) throws BaseSystemException { + if (sql == null || "".equals(sql)) { + throw new RuntimeException("The sql cannot be empty"); + } + //try(SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();) { + List> list = sqlSession.selectList("selectBySql", sql); + return list; + //} + } + /** + * @param example + * @return PageInfo + * @Author lvleigang + * @Description 分页查询数据 + * @Date 2:53 下午 2022/12/3 + **/ + @Override + public PageInfo queryPageByExample(RequestDisposeEntity example) throws BaseSystemException { + if (example == null) { + throw new RuntimeException("The Example cannot be empty"); + } + if (example.isHavenOrder()) { + PageHelper.startPage(example.getPageNum() != null ? example.getPageNum() : 1, example.getPageSize() != null ? example.getPageSize() : pageSize, example.getOrderString()); + } else { + PageHelper.startPage(example.getPageNum() != null ? example.getPageNum() : 1, example.getPageSize() != null ? example.getPageSize() : pageSize); + } + PageInfo pageInfo = null; + long timeMillis1 = System.currentTimeMillis(); + //try(SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();) { + long timeMillis2 = System.currentTimeMillis(); + List> list = sqlSession.selectList("selectByExample", example); + long timeMillis3 = System.currentTimeMillis(); + String sql ="select * from sys_module WHERE ( lvl = '0' ) AND ( sts = 'Y' )"; + List> list1 = sqlSession.selectList("selectBySql", sql); + long timeMillis4 = System.currentTimeMillis(); + logger.error("获取session时间:{}", timeMillis2 - timeMillis1); + logger.error("拼接查询时间:{}", timeMillis3 - timeMillis2); + logger.error("sql查询时间:{}", timeMillis4 - timeMillis3); + pageInfo = new PageInfo(list); + //} + long timeMillis5 = System.currentTimeMillis(); + logger.error("总体执行时间:{}", timeMillis5 - timeMillis1); + + return pageInfo; + } + + @Override + public PageInfo queryPageByExample(String sql) { + if (sql == null || "".equals(sql)) { + throw new RuntimeException("The sql cannot be empty"); + } + PageHelper.startPage( 1,pageSize); + //try(SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();) { + List> list = sqlSession.selectList("selectByExample", sql); + PageInfo pageInfo = new PageInfo(list); + return pageInfo; + //} + } + + /** + * @param example + * @return int + * @Author lvleigang + * @Description 添加数据 + * @Date 2:52 下午 2022/12/3 + **/ + @Override + public Integer insert(RequestDisposeEntity example) throws BaseSystemException { + if (example == null) { + throw new RuntimeException("The Example cannot be empty"); + } + if (!example.isHaveModifys()) { + throw new RuntimeException("The ModifyExamples cannot be empty"); + } + //try(SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();) { + int insertCount = sqlSession.insert("insert", example); + return insertCount; + //} + } + + /** + * @param example + * @return int + * @Author lvleigang + * @Description 批量添加数据 + * @Date 2:53 下午 2022/12/3 + **/ + @Override + public int insertSelective(RequestDisposeEntity example) throws BaseSystemException { + if (example == null) { + throw new RuntimeException("The Example cannot be empty"); + } + if (!example.isHaveBatchFileds()) { + throw new RuntimeException("The BatchFileds cannot be empty"); + } + if (!example.isHaveBatchModifys()) { + throw new RuntimeException("The BatchModifys cannot be empty"); + } + //try(SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();) { + int insertCount = sqlSession.insert("insertSelective", example); + return insertCount; + //} + } + + /** + * @param example + * @return int + * @Author lvleigang + * @Description 删除 + * @Date 2:52 下午 2022/12/3 + **/ + @Override + public int deleteByExample(RequestDisposeEntity example) throws BaseSystemException { + if (example == null) { + throw new RuntimeException("The Example cannot be empty"); + } + //try(SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();) { + int deleteCount = sqlSession.insert("deleteByExample", example); + return deleteCount; + //} + } + + /** + * @param example + * @return int + * @Author lvleigang + * @Description 根据条件修改 + * @Date 2:54 下午 2022/12/3 + **/ + @Override + public int updateByExample(RequestDisposeEntity example) throws BaseSystemException { + if (example == null) { + throw new RuntimeException("The Example cannot be empty"); + } + if (!example.isHaveModifys()) { + throw new RuntimeException("The ModifyExamples cannot be empty"); + } + //try(SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession();) { + int updateCount = sqlSession.insert("updateByExample", example); + return updateCount; + //} + } + + +} diff --git a/common/src/main/java/com/hzya/frame/beanutil/BeanUtil.java b/common/src/main/java/com/hzya/frame/beanutil/BeanUtil.java new file mode 100644 index 00000000..12d83d25 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/beanutil/BeanUtil.java @@ -0,0 +1,14 @@ +package com.hzya.frame.beanutil; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-11-28 10:27 + * @Version 1.0 + */ +public class BeanUtil { + + public static String getBean(){ + return "232"; + } +} diff --git a/common/src/main/java/com/hzya/frame/datasource/DataSourceConfig.java b/common/src/main/java/com/hzya/frame/datasource/DataSourceConfig.java new file mode 100644 index 00000000..7ca9015f --- /dev/null +++ b/common/src/main/java/com/hzya/frame/datasource/DataSourceConfig.java @@ -0,0 +1,197 @@ +package com.hzya.frame.datasource; + +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; +import com.baomidou.dynamic.datasource.processor.DsSpelExpressionProcessor; +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.expression.StandardBeanExpressionResolver; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; + +import javax.annotation.Resource; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.HashMap; +import java.util.Map; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2023-06-13 17:56 + * @Version 1.0 + */ +@Configuration +public class DataSourceConfig { + private static final Logger logger = LoggerFactory.getLogger(DataSourceConfig.class); + //dataSource容器 + private static final Map DATASOURCEMAP = new HashMap<>(); + private SqlSessionFactory sqlSessionFactory; + @Resource + private DataSource dataSource; + + + + public DruidDataSource dataSource2() { + DruidDataSource dataSource = createDefaultDataSource(getDataSourceJsonObject()); + return dataSource; + } + + + public DynamicRoutingDataSource dynamicRoutingDataSource(DruidDataSource dataSource1, DruidDataSource dataSource2) { + DynamicRoutingDataSource dynamicDataSource = (DynamicRoutingDataSource) dataSource; + dynamicDataSource.addDataSource("dataSource1", dataSource1); + dynamicDataSource.addDataSource("dataSource2", dataSource2); + return dynamicDataSource; + } + + + + + + /**** + * @Content:根据数据源管理器DynamicRoutingDataSource 创建SqlSessionFactory + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-06-14 9:16 + * @Param [dynamicRoutingDataSource] + * @return org.apache.ibatis.session.SqlSessionFactory + **/ +// @Bean + public static SqlSessionFactory mySqlSessionFactory(DataSource dataSource) throws RuntimeException { + try { + if (null != dataSource) { +// StandardBeanExpressionResolver +// DsSpelExpressionProcessor; + SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); + //数据源 + sqlSessionFactoryBean.setDataSource(dataSource); + //mybatis的config文件 + PathMatchingResourcePatternResolver configLocationResolver = new PathMatchingResourcePatternResolver(); + sqlSessionFactoryBean.setConfigLocation(configLocationResolver.getResource("classpath:mybatis/mybatis-config.xml")); + //xml + PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); + sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:com/hzya/**/*.xml")); + + return sqlSessionFactoryBean.getObject(); + } else { + logger.info("======================创建sqlSessionFactory失败==========================="); + throw new RuntimeException("创建sqlSessionFactory失败"); + } + } catch (Exception e) { + logger.info("======================创建sqlSessionFactory失败==========================="); + throw new RuntimeException("创建sqlSessionFactory失败"+e.getMessage()); + } + } + + + +// @Bean + public DataSourceTransactionManager transactionManager(DynamicRoutingDataSource dynamicRoutingDataSource) { + return new DataSourceTransactionManager(dynamicRoutingDataSource); + } + + + /**** + * @Content:创建数据源,返回DruidDataSource + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-06-14 9:11 + * @Param [defaultDataSourceProperties] + * @return com.alibaba.druid.pool.DruidDataSource + **/ + private static DruidDataSource createDefaultDataSource(JSONObject defaultDataSourceProperties) throws RuntimeException { + //根据datasource_code查询数据源配置信息 + String datasource_code = String.valueOf(defaultDataSourceProperties.get("datasource_code")); + String source_url = String.valueOf(defaultDataSourceProperties.get("source_url")); + String login_name = String.valueOf(defaultDataSourceProperties.get("login_name")); + String password = String.valueOf(defaultDataSourceProperties.get("password")); + String db_name = String.valueOf(defaultDataSourceProperties.get("db_name")); + String source_type = String.valueOf(defaultDataSourceProperties.get("source_type")); + if (defaultDataSourceProperties != null) { + String driveClass = ""; + if ("mysql".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.MYSQLDRIVER_6; + } else if ("oracle".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.ORACLEDRIVER; + } else if ("sqlserver2000".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.SQL2000DRIVER; + } else if ("sqlServer".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.SQL2005DRIVER; + } + try { + //测试连接 + Class.forName(driveClass); + Connection connection = DriverManager.getConnection(source_url, login_name, password);// 相当于连接数据库 + if (connection != null) { + //初始化数据源信息 + DruidDataSource druidDataSource = new DruidDataSource(); + druidDataSource.setUrl(source_url); + druidDataSource.setUsername(login_name); + druidDataSource.setPassword(password); + druidDataSource.setName(db_name); + druidDataSource.setDriverClassName(driveClass); + druidDataSource.setInitialSize(5); + druidDataSource.setMinIdle(5); + druidDataSource.setMaxActive(100); + druidDataSource.setMaxWait(60000); + druidDataSource.setTimeBetweenEvictionRunsMillis(60000); + druidDataSource.setMinEvictableIdleTimeMillis(300000); + druidDataSource.setMaxEvictableIdleTimeMillis(600000); + if ("oracle".equals(source_type)) { + druidDataSource.setValidationQuery("select 1 from dual"); + } else { + druidDataSource.setValidationQuery("SELECT 1"); + } + druidDataSource.setTestWhileIdle(true); + druidDataSource.setTestOnBorrow(false); + druidDataSource.setTestOnReturn(false); + druidDataSource.setPoolPreparedStatements(true); + druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20); + druidDataSource.setRemoveAbandoned(true); + druidDataSource.setRemoveAbandonedTimeout(999999); + druidDataSource.init(); + //放到缓存里 + DATASOURCEMAP.put(datasource_code, druidDataSource); + return druidDataSource; + } else { + throw new RuntimeException("测试默认数据库连接失败"); + } + } + catch (Exception e) { + logger.info("==================创建数据源失败==================="); + throw new RuntimeException("创建数据源失败"+e.getMessage()); + } + + + } else { + throw new RuntimeException("source_code:" + datasource_code + "不存在"); + } + } + + + + /**** + * @Content:创建第二数据源配置 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-06-14 9:09 + * @Param [] + * @return com.alibaba.fastjson.JSONObject + **/ + private static JSONObject getDataSourceJsonObject() { + JSONObject defaultDataSourceProperties = new JSONObject(); + defaultDataSourceProperties.put("datasource_code", "ya237"); + defaultDataSourceProperties.put("source_url", "jdbc:mysql://hzya.ufyct.com:9022/hut_exchange?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false"); + defaultDataSourceProperties.put("source_type", "mysql"); + defaultDataSourceProperties.put("login_name", "root"); + defaultDataSourceProperties.put("password", "hzya1314"); + defaultDataSourceProperties.put("db_name", "hut_exchange"); + return defaultDataSourceProperties; + } + +} + diff --git a/common/src/main/java/com/hzya/frame/datasource/DataSourceUtil.java b/common/src/main/java/com/hzya/frame/datasource/DataSourceUtil.java new file mode 100644 index 00000000..6691730b --- /dev/null +++ b/common/src/main/java/com/hzya/frame/datasource/DataSourceUtil.java @@ -0,0 +1,152 @@ +package com.hzya.frame.datasource; + +import com.alibaba.druid.pool.DruidDataSource; +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; +import com.hzya.frame.web.entity.BaseEntity; +import com.hzya.frame.web.exception.BaseSystemException; +import org.apache.ibatis.mapping.DatabaseIdProvider; +import org.apache.ibatis.mapping.VendorDatabaseIdProvider; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.mybatis.spring.SqlSessionFactoryBean; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Lazy; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * @Auther: xiang2lin + * @Date: 2020/3/31 10:25 + * 数据源工具类 + */ +@Component +@Lazy(value = false) +public class DataSourceUtil { + //DATASOURCECODE + public static final ThreadLocal myContextThreadLocal = new ThreadLocal<>(); + private static final Logger logger = LoggerFactory.getLogger(DataSourceUtil.class); + //SqlSessionFactory容器 + private static final Map SQLSESSIONFACTORYMAP = new HashMap<>(); + //dataSource容器 + private final Map DATASOURCEMAP = new HashMap<>(); + // 通过依赖注入获取 DynamicRoutingDataSource 对象 + @Resource + private DynamicRoutingDataSource ds; + /**** + * 根据dataSourceKey 打开 SqlSession ,如果获取不到SqlSessionFactory 会抛出异常 + * @content: + * @author 👻👻👻👻👻👻👻👻 gjh + * @date 2024-02-22 14:50 + * @param + * @return org.apache.ibatis.session.SqlSession + **/ + + public synchronized static SqlSession getSqlSession() { + String dsKey = "master"; // 根据业务逻辑确定要使用的数据源名称 + BaseEntity entity = DataSourceUtil.myContextThreadLocal.get(); + if(null != entity ){ + dsKey = entity.getDataSourceCode(); + } + // 通过 DynamicRoutingDataSource 获取当前数据源 +// ds.getDataSource(dsKey); + + SqlSessionFactory factory = getSqlSessionFactoryByCache(dsKey); + if (null == factory) { + throw new BaseSystemException("根据dataSourceKey获取SqlSessionFactory 失败!请联系管理员"); + } else { + return factory.openSession(); + } + } + + + /**** + * 根据dataSourceKey获取缓存内的SqlSessionFactory,如果获取不到会抛出异常信息 + * @content: + * @author 👻👻👻👻👻👻👻👻 gjh + * @date 2024-02-22 14:44 + * @param + * @return org.apache.ibatis.session.SqlSessionFactory + **/ + public static SqlSessionFactory getSqlSessionFactoryByCache(String dataSourceKey) { + SqlSessionFactory sqlSessionFactory = SQLSESSIONFACTORYMAP.get(dataSourceKey); + if (null == sqlSessionFactory) { + throw new BaseSystemException("根据当前dataSourceKey获取SqlSessionFactory失败,请联系系统管理员!dataSourceKey:" + dataSourceKey); + } + return sqlSessionFactory; + } + + /**** + * 根据 dataSource 创建SqlSessionFactory,并放入map缓存 dataSourceKey + * @content: + * @author 👻👻👻👻👻👻👻👻 gjh + * @date 2024-02-22 14:38 + * @param + * @return org.apache.ibatis.session.SqlSessionFactory + **/ + public static SqlSessionFactory createSqlSessionFactoryToCache(String dataSourceKey, DataSource dataSource) { + SqlSessionFactory sqlSessionFactory = createSqlSessionFactory(dataSource); + SQLSESSIONFACTORYMAP.put(dataSourceKey, sqlSessionFactory); + return sqlSessionFactory; + } + + //创建sqlSessionFactory + public static SqlSessionFactory createSqlSessionFactory(DataSource dataSource) throws BaseSystemException { + try { + if (null != dataSource) { + SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); + //数据源 + sqlSessionFactoryBean.setDataSource(dataSource); + //mybatis的config文件 + PathMatchingResourcePatternResolver configLocationResolver = new PathMatchingResourcePatternResolver(); + sqlSessionFactoryBean.setConfigLocation(configLocationResolver.getResource("classpath:mybatis/mybatis-config.xml")); + //xml + PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); + sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources("classpath*:com/hzya/**/*.xml")); + sqlSessionFactoryBean.setDatabaseIdProvider(getDatabaseIdProvider()); + + return sqlSessionFactoryBean.getObject(); + } else { + logger.info("======================创建sqlSessionFactory失败==========================="); + throw new BaseSystemException("创建sqlSessionFactory失败"); + } + } catch (Exception e) { + logger.info("======================创建sqlSessionFactory失败==========================="); + throw new BaseSystemException("创建sqlSessionFactory失败" + e.getMessage()); + } + } + + public static DatabaseIdProvider getDatabaseIdProvider() { + //DBMS 后缀 + //Oracle oracle + //DB2 db2 + //MSSQLServer mssql + //MySQL mysql + //PostgreSQL postgre + //Firebird firebird + //MaxDB maxdb + //HSQL hsql + //Derby derby + //H2 h2 + //Sybase(1.0.43以后) sybase + VendorDatabaseIdProvider dbProvider = new VendorDatabaseIdProvider(); + Properties setPro = new Properties(); + //此处可以添加其他的数据库型号.如MySQL这类厂商标识一定不要写错!! + setPro.setProperty("MySQL", "mysql"); //MySQL必须这样写,但是mysql可以随意写,后面代码同此处. + setPro.setProperty("Oracle", "oracle"); + setPro.setProperty("DM DBMS", "dm"); + dbProvider.setProperties(setPro); + return dbProvider; + } + + public Map getDataSourceMap() { + return DATASOURCEMAP; + } + +} diff --git a/common/src/main/java/com/hzya/frame/datasource/DataSourceUtilProperties.java b/common/src/main/java/com/hzya/frame/datasource/DataSourceUtilProperties.java new file mode 100644 index 00000000..b034c049 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/datasource/DataSourceUtilProperties.java @@ -0,0 +1,22 @@ +package com.hzya.frame.datasource; + +/** + * @Auther: xiang2lin + * @Date: 2020/3/31 14:11 + * + */ + +public class DataSourceUtilProperties { + + + public static final String MYSQLDRIVER_6 = "com.mysql.jdbc.Driver"; // mysql数据库的驱动类 + public static final String MYSQLDRIVER = "com.mysql.jdbc.Driver"; // mysql数据库的驱动类 + public static final String ORACLEDRIVER = "oracle.jdbc.OracleDriver"; // oracles数据库的驱动类 + public static final String SQL2005DRIVER = "net.sourceforge.jtds.jdbc.Driver"; // sqlserver数据库的驱动类 + public static final String SQL2000DRIVER = "net.sourceforge.jtds.jdbc.Driver"; // sqlserver数据库的驱动类 + public static final String dm = "dm.jdbc.driver.DmDriver"; // 达梦数据库的驱动类 + + public static final String MYSQL = "mysql"; + public static final String ORACLE = "oracle"; + public static final String SQLSERVER = "sqlServer"; +} diff --git a/common/src/main/java/com/hzya/frame/dateutil/DateUtil.java b/common/src/main/java/com/hzya/frame/dateutil/DateUtil.java new file mode 100644 index 00000000..3eacc807 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/dateutil/DateUtil.java @@ -0,0 +1,732 @@ +package com.hzya.frame.dateutil; +import cn.hutool.core.util.StrUtil; + +import java.math.BigDecimal; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.*; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-11-28 10:27 + * @Version 1.0 + */ +public class DateUtil { + public static final int FIRST_DAY_OF_WEEK = Calendar.MONDAY; // 中国周一是一周的第一天 + + /** + * 设置时间格式 + */ + private static final String COMMON_DATE = "yyyy-MM-dd"; + /** + * 设置东八区 + **/ + private static final String UTC8 = "GMT+08:00"; + + /** + * 锁对象 + */ + private static final Object LOCKOBJ = new Object(); + + /** + * 存放不同的日期模板格式的sdf的Map + */ + private static Map> simpleDateFormatThreadLocalHashMap = new HashMap>(); + + /** + * 存放不同的 时区的Calendar Map + */ + private static Map> calendarThreadLocalMap = new HashMap>(); + + + /*** + * 根据模版获取 SimpleDateFormat + * @param pattern + * @return + */ + private static SimpleDateFormat getSimpleDateFormat(final String pattern) { + + ThreadLocal tl = simpleDateFormatThreadLocalHashMap.get(pattern); + // 此处的双重判断和同步是为了防止sdfMap这个单例被多次put重复的sdf + if (tl == null) { + synchronized (LOCKOBJ) { + tl = simpleDateFormatThreadLocalHashMap.get(pattern); + if (tl == null) { + // 只有Map中还没有这个pattern的sdf才会生成新的sdf并放入map + // 这里是关键,使用ThreadLocal替代原来直接new SimpleDateFormat + tl = new ThreadLocal() { + + @Override + protected SimpleDateFormat initialValue() { + + return new SimpleDateFormat(pattern); + } + }; + simpleDateFormatThreadLocalHashMap.put(pattern, tl); + } + } + } + return tl.get(); + } + + /*** + * 根据模版获取 Calendar + * @param pattern + * @return + */ + private static Calendar getCalendar(final String pattern) { + ThreadLocal tl = calendarThreadLocalMap.get(pattern); + // 此处的双重判断和同步是为了防止sdfMap这个单例被多次put重复的sdf + if (tl == null) { + synchronized (LOCKOBJ) { + tl = calendarThreadLocalMap.get(pattern); + if (tl == null) { + // 只有Map中还没有这个pattern的sdf才会生成新的sdf并放入map + //System.out.println("put new sdf of pattern " + pattern + " to map"); + // 这里是关键,使用ThreadLocal替代原来直接new Calendar + tl = new ThreadLocal() { + @Override + protected Calendar initialValue() { + //System.out.println("thread: " + Thread.currentThread() + " init pattern: " + pattern); + // new GregorianCalendar(pattern); + return Calendar.getInstance( TimeZone.getTimeZone(pattern)) ; + } + }; + calendarThreadLocalMap.put(pattern, tl); + } + } + } + return tl.get(); + + + } + + + /** + * 获得某一月的天数集合 + * + * @param year + * @param month + * @return + * @throws ParseException + */ + public static List getDateAry(int year, int month) throws ParseException { + Calendar calendar = getCalendar(UTC8); + calendar.setTime(getSimpleDateFormat(COMMON_DATE).parse("" + year + "-" + month + "-01")); + int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + List dateList = new ArrayList(); + for (int i = 0; i < maxDays; i++) { + dateList.add(calendar.getTime()); + calendar.add(Calendar.DAY_OF_MONTH, 1); + } + return dateList; + } + + /** + * 日期转字符 + * + * @param date + * @param pattern + * @return + */ + public static String dateToString(Date date, String pattern) { + SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); + return dateFormat.format(date); + } + /** + * 日期转字符 + * + * @param date + * @param pattern + * @return + */ + public static String dateToString(Long date, String pattern) { + SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); + return dateFormat.format(date); + } + + /** + * 字符转日期 + * + * @param date + * @param pattern + * @return + * @throws ParseException + */ + public static Date stringToDate(String date, String pattern) throws ParseException { + SimpleDateFormat dateFormat = new SimpleDateFormat(pattern); + return dateFormat.parse(date); + } + + + /** + * 传入一个事件,计算加减法,单位年 + * @param date 时间 + * @param num 加减的数量 + * @param type 增加,还是减少,请传入值:add subtract + * @return + * @throws ParseException + */ + public static Date getYearAddAndSubtract(Date date, BigDecimal num , String type) throws Exception { + + if(type == null ){ + throw new RuntimeException("请传入运算类型"); + } + Calendar calendar = getCalendar(UTC8); + calendar.setTime(date); + int nu =0; + if("add".equalsIgnoreCase(type)){ + nu = num.intValue(); + }else{ + nu = num.negate().intValue(); + } + calendar.add(Calendar.YEAR, nu); + return calendar.getTime(); + } + + + + /** + * 传入一个事件,计算加减法,单位月 + * @param date 时间 + * @param num 加减的数量 + * @param type 增加,还是减少,请传入值:add subtract + * @return + * @throws ParseException + */ + public static Date getMonthAddAndSubtract(Date date, BigDecimal num , String type) throws Exception { + + if(type == null ){ + throw new RuntimeException("请传入运算类型"); + } + Calendar calendar = getCalendar(UTC8); + calendar.setTime(date); + int nu =0; + if("add".equalsIgnoreCase(type)){ + nu = num.intValue(); + }else{ + nu = num.negate().intValue(); + } + calendar.add(Calendar.MONTH, nu); + return calendar.getTime(); + } + + + /** + * 传入一个事件,计算加减法,单位根据 calendarType传入 + * @param date 时间 + * @param num 加减的数量 + * @param type 增加,还是减少,请传入值:add subtract + * @param calendarType YEAR 1 MONTH 2 DATE 5 + * @return + * @throws ParseException + */ + public static Date getDateAddAndSubtract(Date date, BigDecimal num , String type,Integer calendarType) throws Exception { + + if(type == null ){ + throw new RuntimeException("请传入运算类型"); + } + Calendar calendar = getCalendar(UTC8); + calendar.setTime(date); + int nu =0; + if("add".equalsIgnoreCase(type)){ + nu = num.intValue(); + }else{ + nu = num.negate().intValue(); + } + calendar.add(calendarType, nu); + return calendar.getTime(); + } + + /** + * 传入年月 获取这个月的第一天 + * + * @param year + * @param month + * @return + */ + public static String getStartTime(Integer year, Integer month) { + Calendar calendar = getCalendar(UTC8); + //设置年份 + calendar.set(Calendar.YEAR, year); + //设置月份 + calendar.set(Calendar.MONTH, month - 1); + //设置日历中月份的第1天 + calendar.set(Calendar.DAY_OF_MONTH, 1); + //格式化日期 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String firstDayOfMonth = sdf.format(calendar.getTime()); + return firstDayOfMonth; + } + + /** + * 传入年月 获取这个月的最后 一天 + * + * @param year + * @param month + * @return + */ + public static String getEndTime(Integer year, Integer month) { + Calendar calendar = getCalendar(UTC8); + //设置年份 + calendar.set(Calendar.YEAR, year); + //设置月份 + calendar.set(Calendar.MONTH, month - 1); + int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + calendar.set(Calendar.DAY_OF_MONTH, lastDay); + //格式化日期 + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + String firstDayOfMonth = sdf.format(calendar.getTime()); + return firstDayOfMonth; + } + + /** + * 传入时间所在月份得到第一天 + * + * @param tempDate + * @return + */ + public static Date getStartTime(Date tempDate) { + Calendar calendar = getCalendar(UTC8); + calendar.setTime(tempDate); + //设置日历中月份的第1天 + calendar.set(Calendar.DAY_OF_MONTH, 1); + return calendar.getTime(); + } + + /** + * 传入时间所在月份的最后 一天 + * + * @param tempDate + * @return + */ + public static Date getEndTime(Date tempDate) { + Calendar calendar = getCalendar(UTC8); + calendar.setTime(tempDate); + int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); + calendar.set(Calendar.DAY_OF_MONTH, lastDay); + return calendar.getTime(); + } + + /** + * 传入date 获取这个时间年的第一个月的第一天 + * + * @param tempDate + * @return + */ + public static Date getStartMonth(Date tempDate) { + Calendar cal = getCalendar(UTC8); + cal.setTime(tempDate); + //设置日历中月份的第1天 + cal.set(Calendar.DAY_OF_YEAR, 1); + return cal.getTime(); + } + + /** + * 传入date 获取这个时间年的最后一个月的最后一天 + * + * @param tempDate + * @return + */ + public static Date getEndMonth(Date tempDate) { + Calendar cal = getCalendar(UTC8); + cal.setTime(tempDate); + int lastDay = cal.getActualMaximum(Calendar.DAY_OF_YEAR); + cal.set(Calendar.DAY_OF_YEAR, lastDay); + return cal.getTime(); + } + + public static Date getYearFirstDate(Date tempDate) { + Calendar calendar = getCalendar(UTC8); + calendar.setTime(tempDate); + calendar.set(Calendar.DAY_OF_YEAR, 1); + return calendar.getTime(); + } + + /** + * 时间类型的运算 + * + * @param date 要运算的时间 + * @param num 加一天 1 减一天 -1 + * @return + */ + public static Date getDateoperation(Date date, Integer num) { + /** 初始化日期格式工具*/ + Calendar calendar = getCalendar(UTC8); + calendar.setTime(date); + /** 设置预警时间*/ + calendar.add(Calendar.DATE, num); + return calendar.getTime(); + } + + /** + * 取得日期:年 + * + * @param date + * @return + */ + public static int getYear(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + int year = c.get(Calendar.YEAR); + return year; + } + + /** + * 取得日期:年 + * + * @param date + * @return + */ + public static String getYearStr(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + int year = c.get(Calendar.YEAR); + return String.valueOf(year); + } + /** + * 取得日期:年 + * + * @param date + * @return + */ + public static int getMonth(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + int month = c.get(Calendar.MONTH); + return month + 1; + } + /** + * 取得日期:年 + * + * @param date + * @return + */ + public static String getMonthStr(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + int month = c.get(Calendar.MONTH); + return String.valueOf(month); + } + + /** + * 取得日期:年 + * + * @param date + * @return + */ + public static int getDay(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + int da = c.get(Calendar.DAY_OF_MONTH); + return da; + } + + /** + * 取得当天日期是周几 + * + * @param date + * @return + */ + public static int getWeekDay(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + int week_of_year = c.get(Calendar.DAY_OF_WEEK); + return week_of_year - 1; + } + + /** + * 取得一年的第几周 + * + * @param date + * @return + */ + public static int getWeekOfYear(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + int week_of_year = c.get(Calendar.WEEK_OF_YEAR); + return week_of_year; + } + + + /** + * 根据日期取得对应周周一日期 + * + * @param date + * @return + */ + public static Date getMondayOfWeek(Date date) { + Calendar monday = getCalendar(UTC8); + monday.setTime(date); + monday.setFirstDayOfWeek(FIRST_DAY_OF_WEEK); + monday.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + return monday.getTime(); + } + + /** + * 根据日期取得对应周周日日期 + * + * @param date + * @return + */ + public static Date getSundayOfWeek(Date date) { + Calendar sunday = getCalendar(UTC8); + sunday.setTime(date); + sunday.setFirstDayOfWeek(FIRST_DAY_OF_WEEK); + sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); + return sunday.getTime(); + } + + /** + * 取得月的剩余天数 + * + * @param date + * @return + */ + public static int getRemainDayOfMonth(Date date) { + int dayOfMonth = getDayOfMonth(date); + int day = getPassDayOfMonth(date); + return dayOfMonth - day; + } + + /** + * 取得月已经过的天数 + * + * @param date + * @return + */ + public static int getPassDayOfMonth(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + return c.get(Calendar.DAY_OF_MONTH); + } + + /** + * 取得月天数 + * + * @param date + * @return + */ + public static int getDayOfMonth(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + return c.getActualMaximum(Calendar.DAY_OF_MONTH); + } + + /** + * 取得月第一天 + * + * @param date + * @return + */ + public static Date getFirstDateOfMonth(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH)); + return c.getTime(); + } + + /** + * 取得月最后一天 + * + * @param date + * @return + */ + public static Date getLastDateOfMonth(Date date) { + Calendar c = getCalendar(UTC8); + c.setTime(date); + c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); + return c.getTime(); + } + + /** + * 取得季度第一天 + * + * @param date + * @return + */ + public static Date getFirstDateOfSeason(Date date) { + return getFirstDateOfMonth(getSeasonDate(date)[0]); + } + + /** + * 取得季度最后一天 + * + * @param date + * @return + */ + public static Date getLastDateOfSeason(Date date) { + return getLastDateOfMonth(getSeasonDate(date)[2]); + } + + /** + * 取得季度天数 + * + * @param date + * @return + */ + public static int getDayOfSeason(Date date) { + int day = 0; + Date[] seasonDates = getSeasonDate(date); + for (Date date2 : seasonDates) { + day += getDayOfMonth(date2); + } + return day; + } + + /** + * 取得季度剩余天数 + * + * @param date + * @return + */ + public static int getRemainDayOfSeason(Date date) { + return getDayOfSeason(date) - getPassDayOfSeason(date); + } + + /** + * 取得季度已过天数 + * + * @param date + * @return + */ + public static int getPassDayOfSeason(Date date) { + int day = 0; + + Date[] seasonDates = getSeasonDate(date); + + Calendar c = getCalendar(UTC8); + c.setTime(date); + int month = c.get(Calendar.MONTH); + + if (month == Calendar.JANUARY || month == Calendar.APRIL + || month == Calendar.JULY || month == Calendar.OCTOBER) {// 季度第一个月 + day = getPassDayOfMonth(seasonDates[0]); + } else if (month == Calendar.FEBRUARY || month == Calendar.MAY + || month == Calendar.AUGUST || month == Calendar.NOVEMBER) {// 季度第二个月 + day = getDayOfMonth(seasonDates[0]) + + getPassDayOfMonth(seasonDates[1]); + } else if (month == Calendar.MARCH || month == Calendar.JUNE + || month == Calendar.SEPTEMBER || month == Calendar.DECEMBER) {// 季度第三个月 + day = getDayOfMonth(seasonDates[0]) + getDayOfMonth(seasonDates[1]) + + getPassDayOfMonth(seasonDates[2]); + } + return day; + } + + /** + * 取得季度月 + * + * @param date + * @return + */ + public static Date[] getSeasonDate(Date date) { + Date[] season = new Date[3]; + + Calendar c = getCalendar(UTC8); + c.setTime(date); + + int nSeason = getSeason(date); + if (nSeason == 1) {// 第一季度 + c.set(Calendar.MONTH, Calendar.JANUARY); + season[0] = c.getTime(); + c.set(Calendar.MONTH, Calendar.FEBRUARY); + season[1] = c.getTime(); + c.set(Calendar.MONTH, Calendar.MARCH); + season[2] = c.getTime(); + } else if (nSeason == 2) {// 第二季度 + c.set(Calendar.MONTH, Calendar.APRIL); + season[0] = c.getTime(); + c.set(Calendar.MONTH, Calendar.MAY); + season[1] = c.getTime(); + c.set(Calendar.MONTH, Calendar.JUNE); + season[2] = c.getTime(); + } else if (nSeason == 3) {// 第三季度 + c.set(Calendar.MONTH, Calendar.JULY); + season[0] = c.getTime(); + c.set(Calendar.MONTH, Calendar.AUGUST); + season[1] = c.getTime(); + c.set(Calendar.MONTH, Calendar.SEPTEMBER); + season[2] = c.getTime(); + } else if (nSeason == 4) {// 第四季度 + c.set(Calendar.MONTH, Calendar.OCTOBER); + season[0] = c.getTime(); + c.set(Calendar.MONTH, Calendar.NOVEMBER); + season[1] = c.getTime(); + c.set(Calendar.MONTH, Calendar.DECEMBER); + season[2] = c.getTime(); + } + return season; + } + + //字符串日期转毫秒 + public static Long dateStrToLong(String dateStr){ + if(StrUtil.isNotEmpty(dateStr) && !"null".equals(dateStr)){ + return cn.hutool.core.date.DateUtil.parse(dateStr).getTime(); + } + return null; + } + /** + * 1 第一季度 2 第二季度 3 第三季度 4 第四季度 + * + * @param date + * @return + */ + public static int getSeason(Date date) { + + int season = 0; + + Calendar c = getCalendar(UTC8); + c.setTime(date); + int month = c.get(Calendar.MONTH); + switch (month) { + case Calendar.JANUARY: + case Calendar.FEBRUARY: + case Calendar.MARCH: + season = 1; + break; + case Calendar.APRIL: + case Calendar.MAY: + case Calendar.JUNE: + season = 2; + break; + case Calendar.JULY: + case Calendar.AUGUST: + case Calendar.SEPTEMBER: + season = 3; + break; + case Calendar.OCTOBER: + case Calendar.NOVEMBER: + case Calendar.DECEMBER: + season = 4; + break; + default: + break; + } + return season; + } + + + + + public static void main1(String[] args) { + try { + /** 初始化日期格式工具*/ + Calendar calendar = getCalendar(UTC8); + /** 设置保质期时间*/ + calendar.setTime(stringToDate("2015-05-26", "yyyy-MM-dd")); + /** 设置预警时间*/ + calendar.add(Calendar.DATE, 1); + /** 得到预警日期*/ + //System.out.println("保质期:2015-05-26"); + //System.out.println("预警日期:" + dateToString(calendar.getTime(), "yyyy-MM-dd")); + + //System.out.println(dateToString(getDateoperation(new Date(), 1), "yyyy-MM-dd")); + } catch (ParseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + +} diff --git a/common/src/main/java/com/hzya/frame/execsql/controller/ExecSqlController.java b/common/src/main/java/com/hzya/frame/execsql/controller/ExecSqlController.java new file mode 100644 index 00000000..eb9cb2f8 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/execsql/controller/ExecSqlController.java @@ -0,0 +1,39 @@ +package com.hzya.frame.execsql.controller; +import com.hzya.frame.execsql.entity.ExecSqlEntity; +import com.hzya.frame.execsql.service.IExecSqlService; +import com.hzya.frame.web.action.DefaultController; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * @Description 执行前端传过来的sql,只允许执行select + * @Author xiang2lin + * @Date 2021/4/28 14:19 + **/ +@RestController +@RequestMapping(value = "/execsql") +public class ExecSqlController extends DefaultController { + + @Autowired + @Resource(name = "ya_ExecSqlService") + private IExecSqlService execSqlService; + + @RequestMapping("/select") + @ResponseBody + public List> execSelectSql(ExecSqlEntity entity){ + List> list = new ArrayList<>(); + try { + list = execSqlService.execSelectSql(entity); + }catch (Exception e){ + e.printStackTrace(); + } + return list; + } +} diff --git a/common/src/main/java/com/hzya/frame/execsql/entity/ExecSqlEntity.java b/common/src/main/java/com/hzya/frame/execsql/entity/ExecSqlEntity.java new file mode 100644 index 00000000..8081c48f --- /dev/null +++ b/common/src/main/java/com/hzya/frame/execsql/entity/ExecSqlEntity.java @@ -0,0 +1,29 @@ +package com.hzya.frame.execsql.entity; + +/** + * @Description 执行sql + * @Author xiang2lin + * @Date 2021/4/28 14:20 + **/ +public class ExecSqlEntity { + + //要执行的sql语句,只支持select + String sql; + //数据源 + String datasource_code; + public String getSql() { + return sql; + } + + public void setSql(String sql) { + this.sql = sql; + } + + public String getDatasource_code() { + return datasource_code; + } + + public void setDatasource_code(String datasource_code) { + this.datasource_code = datasource_code; + } +} diff --git a/common/src/main/java/com/hzya/frame/execsql/entity/ExecSqlEntity.xml b/common/src/main/java/com/hzya/frame/execsql/entity/ExecSqlEntity.xml new file mode 100644 index 00000000..aec829e5 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/execsql/entity/ExecSqlEntity.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + ${sql} + + + + + + ${sql} + + + diff --git a/common/src/main/java/com/hzya/frame/execsql/service/ExecSqlServiceImpl.java b/common/src/main/java/com/hzya/frame/execsql/service/ExecSqlServiceImpl.java new file mode 100644 index 00000000..83ad0318 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/execsql/service/ExecSqlServiceImpl.java @@ -0,0 +1,150 @@ +package com.hzya.frame.execsql.service; + +import com.hzya.frame.datasource.DataSourceUtil; +import com.hzya.frame.execsql.entity.ExecSqlEntity; +import org.apache.ibatis.session.SqlSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Service; +import org.springframework.util.ObjectUtils; +import org.springframework.util.StringUtils; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +/** + * @Description 描述 + * @Author xiang2lin + * @Date 2021/4/28 14:27 + **/ +@Service(value = "ya_ExecSqlService") +@Lazy(value = false) +public class ExecSqlServiceImpl implements IExecSqlService { + Logger logger = LoggerFactory.getLogger(ExecSqlServiceImpl.class); + @Resource + private SqlSession sqlSession; + /** + * 执行select语句 + * + * @param sql 要执行的sql语句 + * @param data_source_code 数据源编号 + * @return + * @throws Exception + */ + @Override + public List> execSelectSql(String sql, String data_source_code) throws Exception { + ExecSqlEntity entity = new ExecSqlEntity(); + entity.setSql(sql); + entity.setDatasource_code(data_source_code); + return execSelectSql(entity); + } + + /** + * 执行select语句 + * + * @param entity + * @return + * @throws Exception + */ + @Override + public List> execSelectSql(ExecSqlEntity entity) throws RuntimeException { + List> list = new ArrayList<>(); + logger.info("=============进入execSelectSql方法============"); + if (null != entity && ObjectUtils.isEmpty(entity.getSql())) { + //sqlsession +// SqlSession sqlSession = getSqlSession(entity.getDatasource_code()); +// SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession(); + String select_sql = entity.getSql(); + logger.info("=============execSelectSql方法要执行的sql:============" + select_sql); + if (!select_sql.contains("update") && !select_sql.contains("delete") + && !select_sql.contains("insert") && !select_sql.contains("create")) { + list = sqlSession.selectList("com.hzya.frame.sys.execsql.entity.ExecSqlEntity.ExecSqlEntity_execsql", entity); + logger.info("===========execSelectSql方法返回的结果条数=============" + list.size()); + } + //sqlSession.close(); + } + return list; + } + + /** + * 执行update语句 + * + * @param sql + * @param data_source_code + * @return + * @throws Exception + */ + @Override + public int execUpdateSql(String sql, String data_source_code) throws Exception { + logger.info("=============进入execUpdateSql方法============"); + if (ObjectUtils.isEmpty(sql)) { + if (sql.contains("where") || sql.contains("WHERE")) { +// SqlSession sqlSession = getSqlSession(data_source_code); +// SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession(); + logger.info("=============execUpdateSql方法要执行的sql:============" + sql); + ExecSqlEntity entity = new ExecSqlEntity(); + entity.setSql(sql); + int result = sqlSession.update("com.hzya.frame.sys.execsql.entity.ExecSqlEntity.ExecSqlEntity_execsql_update", entity); + logger.info("update受影响行数:" + result); + //sqlSession.close(); + return result; + } else { + logger.info("=============sql语句不包含where条件============" + sql); + } + } else { + logger.info("=============sql为null============"); + } + return 0; + } + + /** + * 执行insert语句 + * + * @param sql + * @param data_source_code + * @return + * @throws Exception + */ + @Override + public int execInsertSql(String sql, String data_source_code) throws Exception { + logger.info("=============进入execInsertSql方法============"); + if (ObjectUtils.isEmpty(sql)) { +// SqlSession sqlSession = getSqlSession(data_source_code); +// SqlSession sqlSession = new DataSourceUtil().getDefaultSqlSession(); + logger.info("=============execInsertSql方法要执行的sql:============" + sql); + ExecSqlEntity entity = new ExecSqlEntity(); + entity.setSql(sql); + int result = sqlSession.insert("com.hzya.frame.sys.execsql.entity.ExecSqlEntity.ExecSqlEntity_execsql_insert", entity); + logger.info("insert受影响行数:" + result); + //sqlSession.close(); + return result; + } else { + logger.info("=============sql为null============"); + } + return 0; + } + + +// private SqlSession getSqlSession(String data_source_code){ +// //sqlsession默认值 +// SqlSession sqlSession = null; +// if (StrUtil.isNotEmpty(data_source_code)){ +// try { +// sqlSession = DataSourceUtil.getSqlSession(data_source_code); +// }catch (Exception e){ +// e.printStackTrace(); +// logger.info("根据数据源编号:"+data_source_code+",取sqlSession时出现异常"); +// //如果取数据源时出异常,则用默认数据源 +// sqlSession = default_sqlSession; +// } +// } +// //如果取不到,用默认数据源 +// if (null == sqlSession){ +// sqlSession = default_sqlSession; +// } +// return sqlSession; +// } +} diff --git a/common/src/main/java/com/hzya/frame/execsql/service/IExecSqlService.java b/common/src/main/java/com/hzya/frame/execsql/service/IExecSqlService.java new file mode 100644 index 00000000..e238c067 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/execsql/service/IExecSqlService.java @@ -0,0 +1,53 @@ +package com.hzya.frame.execsql.service; + +import com.hzya.frame.execsql.entity.ExecSqlEntity; + +import java.util.HashMap; +import java.util.List; + +/** + * @Description 描述 + * @Author xiang2lin + * @Date 2021/4/28 14:26 + **/ +public interface IExecSqlService { + + + /** + * 执行select语句 + * @param entity + * @return + * @throws Exception + */ + List> execSelectSql(ExecSqlEntity entity)throws RuntimeException; + + /** + * 执行update语句 + * @param sql + * @param data_source_code + * @return + * @throws Exception + */ + int execUpdateSql(String sql,String data_source_code)throws Exception; + + + /** + * 执行insert语句 + * @param sql + * @param data_source_code + * @return + * @throws Exception + */ + int execInsertSql(String sql,String data_source_code)throws Exception; + + /** + * 执行select语句 + * @param sql 要执行的sql语句 + * @param data_source_code 数据源编号 + * @return + * @throws Exception + */ + List> execSelectSql(String sql,String data_source_code)throws Exception; + + +} diff --git a/common/src/main/java/com/hzya/frame/iputil/IPUtil.java b/common/src/main/java/com/hzya/frame/iputil/IPUtil.java new file mode 100644 index 00000000..c691f8aa --- /dev/null +++ b/common/src/main/java/com/hzya/frame/iputil/IPUtil.java @@ -0,0 +1,49 @@ +package com.hzya.frame.iputil; + +import javax.servlet.http.HttpServletRequest; + +/** + * @Description 根据request获取IP + * @Author xiang2lin + * @Date 2021/3/31 18:13 + **/ +public class IPUtil { + + public static String getIpAddress(HttpServletRequest request){ + String ip = null; + //X-Forwarded-For:Squid 服务代理 + String ipAddresses = request.getHeader("X-Forwarded-For"); + + if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) { + //Proxy-Client-IP:apache 服务代理 + ipAddresses = request.getHeader("Proxy-Client-IP"); + } + + if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) { + //WL-Proxy-Client-IP:weblogic 服务代理 + ipAddresses = request.getHeader("WL-Proxy-Client-IP"); + } + + if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) { + //HTTP_CLIENT_IP:有些代理服务器 + ipAddresses = request.getHeader("HTTP_CLIENT_IP"); + } + + if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) { + //X-Real-IP:nginx服务代理 + ipAddresses = request.getHeader("X-Real-IP"); + } + + //有些网络通过多层代理,那么获取到的ip就会有多个,一般都是通过逗号(,)分割开来,并且第一个ip为客户端的真实IP + if (ipAddresses != null && ipAddresses.length() != 0) { + ip = ipAddresses.split(",")[0]; + } + + //还是不能获取到,最后再通过request.getRemoteAddr();获取 + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) { + ip = request.getRemoteAddr(); + } + + return ip; + } +} diff --git a/common/src/main/java/com/hzya/frame/jdbcUtil/service/SqlExecuteTimeCountInterceptor.java b/common/src/main/java/com/hzya/frame/jdbcUtil/service/SqlExecuteTimeCountInterceptor.java new file mode 100644 index 00000000..7b5d0853 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/jdbcUtil/service/SqlExecuteTimeCountInterceptor.java @@ -0,0 +1,138 @@ +package com.hzya.frame.jdbcUtil.service; + +import cn.hutool.json.JSONUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.dynamic.datasource.annotation.DS; +import org.apache.ibatis.executor.statement.StatementHandler; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.mapping.ParameterMapping; +import org.apache.ibatis.plugin.*; +import org.apache.ibatis.session.ResultHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import java.sql.Statement; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Properties; + + +@Intercepts({@Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class}), + @Signature(type = StatementHandler.class, method = "update", args = {Statement.class}), + @Signature(type = StatementHandler.class, method = "batch", args = {Statement.class})}) +//@Component +public class SqlExecuteTimeCountInterceptor implements Interceptor { + + private static final Logger logger = LoggerFactory.getLogger(SqlExecuteTimeCountInterceptor.class); + + /** + * 打印的参数字符串的最大长度 + */ + private final static int MAX_PARAM_LENGTH = 50; + + /** + * 记录的最大SQL长度 + */ + private final static int MAX_SQL_LENGTH = 500; + + @Override + public Object intercept(Invocation invocation) throws Throwable { + Object target = invocation.getTarget(); + long startTime = System.currentTimeMillis(); + StatementHandler statementHandler = (StatementHandler) target; + try { + return invocation.proceed(); + } finally { + long endTime = System.currentTimeMillis(); + long timeCount = endTime - startTime; + + BoundSql boundSql = statementHandler.getBoundSql(); + String sql = boundSql.getSql(); + Object parameterObject = boundSql.getParameterObject(); + List parameterMappingList = boundSql.getParameterMappings(); + + // 格式化Sql语句,去除换行符,替换参数 + sql = formatSQL(sql, parameterObject, parameterMappingList); + + logger.info("执行 SQL:[{}]执行耗时[ {} ms])", sql, timeCount); + } + } + + /** + * 格式化/美化 SQL语句 + * + * @param sql sql 语句 + * @param parameterObject 参数的Map + * @param parameterMappingList 参数的List + * @return 格式化之后的SQL + */ + private String formatSQL(String sql, Object parameterObject, List parameterMappingList) { + // 输入sql字符串空判断 + if (sql == null || sql.length() == 0) { + return ""; + } + // 美化sql + sql = beautifySql(sql); + // 不传参数的场景,直接把sql美化一下返回出去 + if (parameterObject == null || parameterMappingList == null || parameterMappingList.size() == 0) { + return sql; + } + return limitSQLLength(sql, parameterObject, parameterMappingList); + } + + /** + * 返回限制长度之后的SQL语句 + * + * @param sql 原始SQL语句 + * @param parameterObject + * @param parameterMappingList + */ + @DS("test") + private String limitSQLLength(String sql, Object parameterObject, List parameterMappingList) { + if (sql == null || sql.length() == 0) { + return ""; + } + Map map = JSONUtil.parseObj(parameterObject); + + Map parameterMap =map; + StringBuilder paramsBuilder = new StringBuilder("\n参数列表:"); + parameterMap.forEach((key, value) -> { + parameterMappingList.forEach(parameterMapping -> { + if (parameterMapping.getProperty().equals(key)) { + String detail = "[" + key + ":" + value + "];"; + paramsBuilder.append(detail); + } + }); + }); + sql += paramsBuilder.toString(); + if (sql.length() > MAX_SQL_LENGTH) { + return sql.substring(0, MAX_SQL_LENGTH); + } else { + return sql; + } + } + + @Override + public Object plugin(Object target) { + return Plugin.wrap(target, this); + } + + @Override + public void setProperties(Properties properties) { + + } + + /** + * 美化sql + * + * @param sql sql语句 + */ + private String beautifySql(String sql) { + sql = sql.replaceAll("[\\s\n ]+", " "); + return sql; + } +} + diff --git a/common/src/main/java/com/hzya/frame/jdbcUtil/service/SqlLogInterceptor.java b/common/src/main/java/com/hzya/frame/jdbcUtil/service/SqlLogInterceptor.java new file mode 100644 index 00000000..48418f40 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/jdbcUtil/service/SqlLogInterceptor.java @@ -0,0 +1,175 @@ +package com.hzya.frame.jdbcUtil.service; + +import org.apache.ibatis.executor.Executor; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.mapping.ParameterMapping; +import org.apache.ibatis.plugin.Interceptor; +import org.apache.ibatis.plugin.Intercepts; +import org.apache.ibatis.plugin.Invocation; +import org.apache.ibatis.plugin.Plugin; +import org.apache.ibatis.plugin.Signature; +import org.apache.ibatis.reflection.MetaObject; +import org.apache.ibatis.session.Configuration; +import org.apache.ibatis.session.ResultHandler; +import org.apache.ibatis.session.RowBounds; +import org.apache.ibatis.type.TypeHandlerRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.annotation.Order; + +import java.text.DateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +/** + * @ClassName: SqlLogInterceptor + * @Description: TODO + * @Author: youchao + * @Date: 2019/10/29 18:31 + * @Version: 1.0 + */ +@Intercepts({ + @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}), + @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})}) + +@Order(1) +public class SqlLogInterceptor implements Interceptor { + Logger log = LoggerFactory.getLogger(SqlLogInterceptor.class); + private Boolean enableSqlLogInterceptor = true; + /** + * 关注时间 单位秒,默认值 5 + * 如果 执行SQL 超过时间 就会打印error 日志 + */ + private Integer noticeTime = 5; + @Override + public Object intercept(Invocation invocation) throws Throwable { + long start = System.currentTimeMillis(); + + MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0]; + String sqlName = mappedStatement.getId(); + Object parameter = null; + if (invocation.getArgs().length > 1) { + parameter = invocation.getArgs()[1]; + } + BoundSql boundSql = mappedStatement.getBoundSql(parameter); + Configuration configuration = mappedStatement.getConfiguration(); + String sql = boundSql.getSql().replaceAll("[\\s]+", " "); + List paramList = getParamList(configuration, boundSql); + if(sql.split("\\?").length > 1 && paramList.size() > 0){ + StringBuffer stringBuffer = new StringBuffer(); + String[] sqls = sql.split("\\?"); + for (int i = 0; i < sqls.length; i++) { + stringBuffer.append(sqls[i]); + if(i < paramList.size()){ + stringBuffer.append(paramList.get(i)); + } + } + log.info("completeSql:"+stringBuffer.toString()); + }else { + log.info("completeSql:"+sql); + } + Object proceed = invocation.proceed(); + int result = 0; + if (proceed instanceof ArrayList) { + ArrayList resultList = (ArrayList) proceed; + result = resultList.size(); + } + if (proceed instanceof Integer) { + result = (Integer) proceed; + } + if (enableSqlLogInterceptor) { + long end = System.currentTimeMillis(); + long time = end - start; + if (time >= noticeTime * 1000) { + log.info("执行超过"+noticeTime+"秒,sql="+sql ); + log.info("result={}, 执行时间time={}ms, params={} ,sqlNamw={}", result, time, paramList,sqlName); + return proceed; + }else { + log.info("result={}, 执行时间time={}ms, params={} ,sqlNamw={}", result, time, paramList,sqlName); + } + } + return proceed; + } + + /** + * Instantiates a new Sql log interceptor. + */ + public SqlLogInterceptor() { + //log.info("[打印SQL拦截器创建]noticeTime={}秒", noticeTime); + } + + /** + * 设置执行sql + * + * @param noticeTime 关注时间 ,如果执行sql超过关注时间,打印error日志. + */ + public SqlLogInterceptor(Integer noticeTime) { + this.noticeTime = noticeTime; + //log.info("[打印SQL拦截器创建]noticeTime={}秒", noticeTime); + } + + /** + * Plugin object. + * + * @param target the target + * + * @return the object + */ + @Override + public Object plugin(Object target) { + return Plugin.wrap(target, this); + } + + /** + * 获取sql参数集合。 + * + * @param configuration the configuration + * @param boundSql the bound sql + * + * @return the param list + */ + private List getParamList(Configuration configuration, BoundSql boundSql) { + Object parameterObject = boundSql.getParameterObject(); + List parameterMappings = boundSql.getParameterMappings(); + List params = new ArrayList<>(); + if (parameterMappings.size() > 0 && parameterObject != null) { + TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); + if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { + params.add(getParameterValue(parameterObject)); + } else { + MetaObject metaObject = configuration.newMetaObject(parameterObject); + for (ParameterMapping parameterMapping : parameterMappings) { + String propertyName = parameterMapping.getProperty(); + if (metaObject.hasGetter(propertyName)) { + Object obj = metaObject.getValue(propertyName); + params.add(getParameterValue(obj)); + } else if (boundSql.hasAdditionalParameter(propertyName)) { + Object obj = boundSql.getAdditionalParameter(propertyName); + params.add(getParameterValue(obj)); + } + } + } + } + return params; + } + + private String getParameterValue(Object obj) { + String value; + if (obj instanceof String) { + value = "'" + obj.toString() + "'"; + } else if (obj instanceof Date) { + DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA); + value = "'" + formatter.format(obj) + "'"; + } else { + if (obj != null) { + value = obj.toString(); + } else { + value = ""; + } + } + return value; + } +} diff --git a/common/src/main/java/com/hzya/frame/page/Page.java b/common/src/main/java/com/hzya/frame/page/Page.java new file mode 100644 index 00000000..257c4936 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/page/Page.java @@ -0,0 +1,117 @@ +package com.hzya.frame.page; + +import org.apache.ibatis.session.RowBounds; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +public class Page extends ArrayList implements Serializable { + + + @SuppressWarnings("unused") + private static final int NO_SQL_COUNT = -1; + @SuppressWarnings("unused") + private static final int SQL_COUNT = 0; + private int pageNum; + private int pageSize; + private int startRow; + private int endRow; + private long total; + private int pages; + + public Page(int pageNum, int pageSize) { + this(pageNum, pageSize, 0); + } + + public Page(int pageNum, int pageSize, boolean count) { + this(pageNum, pageSize, count?0:-1); + } + + public Page(int pageNum, int pageSize, int total) { + super(pageSize > -1?pageSize:0); + this.pageNum = pageNum; + this.pageSize = pageSize; + this.total = (long)total; + this.startRow = pageNum > 0?(pageNum - 1) * pageSize:0; + this.endRow = pageNum * pageSize; + } + + public Page(RowBounds rowBounds, boolean count) { + this(rowBounds, count?0:-1); + } + + public Page(RowBounds rowBounds, int total) { + super(rowBounds.getLimit() > -1?rowBounds.getLimit():0); + this.pageSize = rowBounds.getLimit(); + this.startRow = rowBounds.getOffset(); + this.total = (long)total; + this.endRow = this.startRow + this.pageSize; + } + + public List getResult() { + return this; + } + + public int getPages() { + return this.pages; + } + + public void setPages(int pages) { + this.pages = pages; + } + + public int getEndRow() { + return this.endRow; + } + + public void setEndRow(int endRow) { + this.endRow = endRow; + } + + public int getPageNum() { + return this.pageNum; + } + + public void setPageNum(int pageNum) { + this.pageNum = pageNum; + } + + public int getPageSize() { + return this.pageSize; + } + + public void setPageSize(int pageSize) { + this.pageSize = pageSize; + } + + public int getStartRow() { + return this.startRow; + } + + public void setStartRow(int startRow) { + this.startRow = startRow; + } + + public long getTotal() { + return this.total; + } + + public void setTotal(long total) { + this.total = total; + if(this.pageSize > 0) { + this.pages = (int)(total / (long)this.pageSize + (long)(total % (long)this.pageSize == 0L?0:1)); + } else { + this.pages = (int)total; + } + + } + + public boolean isCount() { + return this.total > -1L; + } + + public String toString() { + return "Page{pageNum=" + this.pageNum + ", pageSize=" + this.pageSize + ", startRow=" + this.startRow + ", endRow=" + this.endRow + ", total=" + this.total + ", pages=" + this.pages + '}'; + } +} diff --git a/common/src/main/java/com/hzya/frame/page/PageAttribute.java b/common/src/main/java/com/hzya/frame/page/PageAttribute.java new file mode 100644 index 00000000..9855a9b1 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/page/PageAttribute.java @@ -0,0 +1,227 @@ +package com.hzya.frame.page; + +import java.io.Serializable; +import java.util.List; + +/*** + * @Content: + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-07-18 16:52 + * @Param + * @return + **/ +public class PageAttribute implements Serializable { + private int pageNum; + private int pageSize; + private int size; + private int startRow; + private int endRow; + private long total; + private int pages; + private int page; + private List rows; + private int firstPage; + private int prePage; + private int nextPage; + + public void setRows(List rows) { + this.rows = rows; + } + + private int lastPage; + private boolean isFirstPage; + private boolean isLastPage; + private boolean hasPreviousPage; + private boolean hasNextPage; + private int navigatePages; + private int[] navigatepageNums; + + public PageAttribute(List list) { + this(list, 8); + } + + public PageAttribute(List list, int navigatePages) { + this.isFirstPage = false; + this.isLastPage = false; + this.hasPreviousPage = false; + this.hasNextPage = false; + + if (list instanceof Page) { + Page page = (Page) list; + this.pageNum = page.getPageNum(); + this.pageSize = page.getPageSize(); + this.total = page.getTotal(); + this.pages = page.getPages(); + this.page = page.getPages(); + this.rows = page; + this.size = page.size(); + this.startRow = (page.getStartRow() + 1); + this.endRow = (this.startRow - 1 + this.size); + this.navigatePages = navigatePages; + calcNavigatepageNums(); + calcPage(); + judgePageBoudary(); + } + } + + private void calcNavigatepageNums() { + if (this.pages <= this.navigatePages) { + this.navigatepageNums = new int[this.pages]; + for (int i = 0; i < this.pages; ++i) { + this.navigatepageNums[i] = (i + 1); + } + } else { + int i; + this.navigatepageNums = new int[this.navigatePages]; + int startNum = this.pageNum - this.navigatePages / 2; + int endNum = this.pageNum + this.navigatePages / 2; + if (startNum < 1) { + startNum = 1; + for (i = 0; i < this.navigatePages; ++i) { + this.navigatepageNums[i] = (startNum++); + } + } else if (endNum > this.pages) { + endNum = this.pages; + + for (i = this.navigatePages - 1; i >= 0; --i) { + this.navigatepageNums[i] = (endNum--); + } + } else { + for (i = 0; i < this.navigatePages; ++i) { + this.navigatepageNums[i] = (startNum++); + } + } + } + } + + public int getPage() { + return this.page; + } + + public void setPage(int page) { + this.page = page; + } + + private void calcPage() { + if ((this.navigatepageNums != null) && (this.navigatepageNums.length > 0)) { + this.firstPage = this.navigatepageNums[0]; + this.lastPage = this.navigatepageNums[(this.navigatepageNums.length - 1)]; + if (this.pageNum > 1) { + this.prePage = (this.pageNum - 1); + } + + if (this.pageNum < this.pages) { + this.nextPage = (this.pageNum + 1); + } + } + } + + private void judgePageBoudary() { + this.isFirstPage = (this.pageNum == 1); + this.isLastPage = ((this.pageNum == this.pages) && (this.pageNum != 1)); + this.hasPreviousPage = (this.pageNum > 1); + this.hasNextPage = (this.pageNum < this.pages); + } + + public int getPageNum() { + return this.pageNum; + } + + public int getPageSize() { + return this.pageSize; + } + + public int getStartRow() { + return this.startRow; + } + + public int getEndRow() { + return this.endRow; + } + + public long getTotal() { + return this.total; + } + + public int getPages() { + return this.pages; + } + + public List getRows() { + return this.rows; + } + + public int getFirstPage() { + return this.firstPage; + } + + public int getPrePage() { + return this.prePage; + } + + public int getNextPage() { + return this.nextPage; + } + + public int getLastPage() { + return this.lastPage; + } + + public boolean isFirstPage() { + return this.isFirstPage; + } + + public boolean isLastPage() { + return this.isLastPage; + } + + public boolean isHasPreviousPage() { + return this.hasPreviousPage; + } + + public boolean isHasNextPage() { + return this.hasNextPage; + } + + public int getNavigatePages() { + return this.navigatePages; + } + + public int[] getNavigatepageNums() { + return this.navigatepageNums; + } + + @Override + public String toString() { + StringBuffer sb = new StringBuffer("PageInfo{"); + sb.append("pageNum=").append(this.pageNum); + sb.append(", pageSize=").append(this.pageSize); + sb.append(", size=").append(this.size); + sb.append(", startRow=").append(this.startRow); + sb.append(", endRow=").append(this.endRow); + sb.append(", total=").append(this.total); + sb.append(", pages=").append(this.pages); + sb.append(", rows=").append(this.rows); + sb.append(", firstPage=").append(this.firstPage); + sb.append(", prePage=").append(this.prePage); + sb.append(", nextPage=").append(this.nextPage); + sb.append(", lastPage=").append(this.lastPage); + sb.append(", isFirstPage=").append(this.isFirstPage); + sb.append(", isLastPage=").append(this.isLastPage); + sb.append(", hasPreviousPage=").append(this.hasPreviousPage); + sb.append(", hasNextPage=").append(this.hasNextPage); + sb.append(", navigatePages=").append(this.navigatePages); + sb.append(", navigatepageNums="); + if (this.navigatepageNums == null) { + sb.append("null"); + } else { + sb.append('['); + for (int i = 0; i < this.navigatepageNums.length; ++i) { + sb.append((i == 0) ? "" : ", ").append(this.navigatepageNums[i]); + } + sb.append(']'); + } + sb.append('}'); + return sb.toString(); + } +} diff --git a/common/src/main/java/com/hzya/frame/page/PageHelper.java b/common/src/main/java/com/hzya/frame/page/PageHelper.java new file mode 100644 index 00000000..181395d3 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/page/PageHelper.java @@ -0,0 +1,285 @@ +package com.hzya.frame.page; + +import com.hzya.frame.web.exception.BaseSystemException; +import org.apache.ibatis.executor.Executor; +import org.apache.ibatis.mapping.*; +import org.apache.ibatis.mapping.MappedStatement.Builder; +import org.apache.ibatis.plugin.Interceptor; +import org.apache.ibatis.plugin.Intercepts; +import org.apache.ibatis.plugin.Invocation; +import org.apache.ibatis.plugin.Plugin; +import org.apache.ibatis.reflection.DefaultReflectorFactory; +import org.apache.ibatis.reflection.MetaObject; +import org.apache.ibatis.reflection.ReflectorFactory; +import org.apache.ibatis.reflection.factory.DefaultObjectFactory; +import org.apache.ibatis.reflection.factory.ObjectFactory; +import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory; +import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory; +import org.apache.ibatis.session.RowBounds; + +import java.util.*; + +@Intercepts({ @org.apache.ibatis.plugin.Signature(type = Executor.class, method = "query", args = { + MappedStatement.class, Object.class, RowBounds.class, org.apache.ibatis.session.ResultHandler.class }) }) +public class PageHelper implements Interceptor { + public static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory(); + public static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory(); + private static final ReflectorFactory DEFAULT_REFLECTOR_FACTORY = new DefaultReflectorFactory(); + public static final MetaObject NULL_META_OBJECT; + private static final String BOUND_SQL = "sqlSource.boundSql.sql"; + private static final ThreadLocal LOCAL_PAGE; + private static final List EMPTY_RESULTMAPPING; + private static String dialect; + private static boolean offsetAsPageNum; + private static boolean rowBoundsWithCount; + private static boolean pageSizeZero; + public static ThreadLocal dialect_type; + public static final String MYSQL = "mysql"; + public static final String SQLSERVER = "sqlServer"; + public static final String ORACLE = "oracle"; + static { + NULL_META_OBJECT = MetaObject.forObject(NullObject.class, DEFAULT_OBJECT_FACTORY,DEFAULT_OBJECT_WRAPPER_FACTORY,DEFAULT_REFLECTOR_FACTORY); + LOCAL_PAGE = new ThreadLocal(); + EMPTY_RESULTMAPPING = new ArrayList(0); + dialect = ""; + offsetAsPageNum = false; + rowBoundsWithCount = false; + pageSizeZero = false; + dialect_type = new ThreadLocal<>(); + } + + public PageHelper() { + } + + public static MetaObject forObject(Object object) { + return MetaObject.forObject(object, DEFAULT_OBJECT_FACTORY, DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTOR_FACTORY); + } + + public static void startPage(int pageNum, int pageSize) { + startPage(pageNum, pageSize, true); + } + + public static void startPage(int pageNum, int pageSize, boolean count) { + LOCAL_PAGE.set(new Page(pageNum, pageSize, count)); + } + + private Page getPage(RowBounds rowBounds) { + Page page = LOCAL_PAGE.get(); + LOCAL_PAGE.remove(); + if (page == null) { + if (offsetAsPageNum) { + page = new Page(rowBounds.getOffset(), rowBounds.getLimit(), rowBoundsWithCount); + } else { + page = new Page(rowBounds, rowBoundsWithCount); + } + } + + return page; + } + + public Object intercept(Invocation invocation) throws Throwable { + /*if(!"mysql".equals(dialect)){ + return invocation.proceed(); + }*/ + Object[] args = invocation.getArgs(); + RowBounds rowBounds = (RowBounds) args[2]; + if (LOCAL_PAGE.get() == null && rowBounds == RowBounds.DEFAULT) { + return invocation.proceed(); + } else { + args[2] = RowBounds.DEFAULT; + MappedStatement ms = (MappedStatement) args[0]; + Object parameterObject = args[1]; + BoundSql boundSql = ms.getBoundSql(parameterObject); + Page page = this.getPage(rowBounds); + if (pageSizeZero && page.getPageSize() == 0) { + Object qs1 = invocation.proceed(); + page.addAll((List) qs1); + page.setPageSize(page.size()); + page.setTotal((long) page.size()); + return page; + } else { + MappedStatement qs = this.newMappedStatement(ms, new BoundSqlSqlSource(boundSql)); + args[0] = qs; + MetaObject msObject = forObject(qs); + String sql = (String) msObject.getValue("sqlSource.boundSql.sql"); + Object result; + if (page.isCount()) { + msObject.setValue("sqlSource.boundSql.sql", this.getCountSql(sql)); + result = invocation.proceed(); + page.setTotal((long) ((Integer) ((List) result).get(0)).intValue()); + if (page.getTotal() == 0L) { + return page; + } + } + + if (page.getPageSize() > 0) { + msObject.setValue("sqlSource.boundSql.sql", this.getPageSql(sql, page)); + msObject.setValue("resultMaps", ms.getResultMaps()); + result = invocation.proceed(); + page.addAll((List) result); + } + + return page; + } + } + } + + private String getCountSql(String sql) { + sql = formatterSql( sql).get("resultSql"); + return "select count(0) from (" + sql + ") tmp_count"; + } + + private String getPageSql(String sql, Page page) { + StringBuilder pageSql = new StringBuilder(200); + if (MYSQL.equals(dialect_type.get())) { + pageSql.append("select * from ("); + pageSql.append(sql); + pageSql.append(") as tmp_page limit " + page.getStartRow() + "," + page.getPageSize()); + } else if ("hsqldb".equals(dialect)) { + pageSql.append(sql); + pageSql.append(" LIMIT " + page.getPageSize() + " OFFSET " + page.getStartRow()); + } else if (ORACLE.equals(dialect)) { + pageSql.append("select * from ( select temp.*, rownum row_id from ( "); + pageSql.append(sql); + pageSql.append(" ) temp where rownum <= ").append(page.getEndRow()); + pageSql.append(") where row_id > ").append(page.getStartRow()); + } else if (SQLSERVER.equals(dialect_type.get())) { + /* pageSql.append("select top ").append(page.getPageSize()).append(" * from("); + pageSql.append(sql); + pageSql.append(" ) temp where temp.id not in ("); + pageSql.append("select top ").append(page.getStartRow()).append(" id from("); + pageSql.append(sql); + pageSql.append(") temp_result "); + pageSql.append(")");*/ + pageSql.append("SELECT * from ("); + pageSql.append("select ROW_NUMBER () OVER (ORDER BY (select 0)) AS row_id_t, * from("); + /** 判断sql 内是否有排序,如果有,把排序截取出来,然后放到最后 ORDER BY*/ + String resultOrderBy = null; + if(sql.indexOf("order by") == -1){ + pageSql.append(sql); + }else{ + resultOrderBy = formatterSql(sql).get("resultOrderBy"); + pageSql.append(formatterSql(sql).get("resultSql")); + } + + pageSql.append(" ) temp "); + pageSql.append(")as temp_t"); + /** 找到temp最后的位置,截取到最后,如果存在where 拼接AND 否则拼接where*/ + int lastIndex = pageSql.toString().lastIndexOf("temp"); + String tempSql = pageSql.toString().substring(lastIndex,pageSql.toString().length()); + /** 根据当前页码计算 开始的row_number 和结束 row_number 第一页 start =(1-1)*20 end = 1*20 */ + /** 开始行号*/ + int start =(page.getPageNum()-1) * page.getPageSize(); + /** 结束行号*/ + int end = page.getPageNum() *page.getPageSize(); + + + if (!tempSql.contains("where")){//这里这样写有问题,不能这样写 + pageSql.append(" where temp_t.row_id_t >"+ start +" and temp_t.row_id_t <= "+end); + }else{ + pageSql.append(" and temp_t.row_id_t > "+ start +" and temp_t.row_id_t <= "+end); + } + if(null != resultOrderBy){ + pageSql.append(" "+resultOrderBy+" "); + } + } + + return pageSql.toString(); + } + + /** 根据sql 判断sql内是否有 orderby语句,如果有,截取出来*/ + private Map formatterSql(String sql){ + Map result = new HashMap<>(); + int index = sql.indexOf("order by"); + String resultOrderBy; + String resultSql; + if (index > 0){ + resultSql = sql.substring(0,sql.indexOf("order by")); + resultOrderBy = sql.substring(sql.indexOf("order by"),sql.length()); + }else { + resultSql = sql; + resultOrderBy = sql.substring(0,sql.length()); + } + + result.put("resultSql",resultSql); + result.put("resultOrderBy",resultOrderBy); + return result; + } + + private MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) { + Builder builder = new Builder(ms.getConfiguration(), ms.getId() + "_PageHelper", newSqlSource,ms.getSqlCommandType()); + builder.resource(ms.getResource()); + builder.fetchSize(ms.getFetchSize()); + builder.statementType(ms.getStatementType()); + builder.keyGenerator(ms.getKeyGenerator()); + if (ms.getKeyProperties() != null && ms.getKeyProperties().length != 0) { + StringBuilder resultMaps = new StringBuilder(); + String[] var8; + int var7 = (var8 = ms.getKeyProperties()).length; + + for (int var6 = 0; var6 < var7; ++var6) { + String resultMap = var8[var6]; + resultMaps.append(resultMap).append(","); + } + + resultMaps.delete(resultMaps.length() - 1, resultMaps.length()); + builder.keyProperty(resultMaps.toString()); + } + + builder.timeout(ms.getTimeout()); + builder.parameterMap(ms.getParameterMap()); + ArrayList var9 = new ArrayList(); + ResultMap var10 = (new ResultMap.Builder(ms.getConfiguration(), ms.getId(),Integer.TYPE, EMPTY_RESULTMAPPING)).build(); + var9.add(var10); + builder.resultMaps(var9); + builder.resultSetType(ms.getResultSetType()); + builder.cache(ms.getCache()); + builder.flushCacheRequired(ms.isFlushCacheRequired()); + builder.useCache(ms.isUseCache()); + return builder.build(); + } + + public Object plugin(Object target) { + return target instanceof Executor ? Plugin.wrap(target, this) : target; + } + + public void setProperties(Properties p) { + dialect = p.getProperty("dialect"); + if (dialect != null && !"".equals(dialect)) { + String offset = p.getProperty("offsetAsPageNum"); + if (offset != null && "TRUE".equalsIgnoreCase(offset)) { + offsetAsPageNum = true; + } + + String withcount = p.getProperty("rowBoundsWithCount"); + if (withcount != null && "TRUE".equalsIgnoreCase(withcount)) { + rowBoundsWithCount = true; + } + + String sizeZero = p.getProperty("pageSizeZero"); + if (sizeZero != null && "TRUE".equalsIgnoreCase(sizeZero)) { + pageSizeZero = true; + } + + } else { + throw new BaseSystemException("Mybatis分页插件PageHelper无法获取dialect参数!"); + } + } + + private class BoundSqlSqlSource implements SqlSource { + BoundSql boundSql; + + public BoundSqlSqlSource(BoundSql boundSql) { + this.boundSql = boundSql; + } + + public BoundSql getBoundSql(Object parameterObject) { + return this.boundSql; + } + } + + private static class NullObject { + private NullObject() { + } + } +} diff --git a/common/src/main/java/com/hzya/frame/servlet/ServletContextUtil.java b/common/src/main/java/com/hzya/frame/servlet/ServletContextUtil.java new file mode 100644 index 00000000..beebbab5 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/servlet/ServletContextUtil.java @@ -0,0 +1,173 @@ +package com.hzya.frame.servlet; + +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.context.support.WebApplicationContextUtils; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +/** + * @Content ServletContext 工具类,用于获取Servlet相关上下文信息 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2020-9-1 11:28 + * @Version 1.0 + */ +@SuppressWarnings("ALL") +public class ServletContextUtil { + public static HttpServletRequest getRequest() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder + .currentRequestAttributes(); + return attributes.getRequest(); + } + + public static Map getRequestParameterMap() { + if (getRequest() != null) + return getRequest().getParameterMap(); + + return new HashMap(); + } + + public static Map getRequestAttributeMap() { + Map map = new HashMap(); + if (getRequest() != null) { + Enumeration enumeration = getRequest().getAttributeNames(); + while (enumeration.hasMoreElements()) { + Object key = enumeration.nextElement(); + map.put(key, getRequest().getAttribute((String) key)); + } + } + return map; + } + + public static HttpServletResponse getResponse() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder + .currentRequestAttributes(); + return attributes.getResponse(); + } + + public static HttpSession getSession() { + HttpServletRequest request = getRequest(); + if (request != null) + return request.getSession(); + + return null; + } + + public static Map getSessionMap() { + Map map = new HashMap(); + if (getSession() != null) { + Enumeration enumeration = getSession().getAttributeNames(); + while (enumeration.hasMoreElements()) { + Object key = enumeration.nextElement(); + map.put(key, getSession().getAttribute((String) key)); + } + } + return map; + } + + public static ServletContext getServletContext() { + HttpSession actionSession = getSession(); + return actionSession.getServletContext(); + } + + public static Map getApplicationMap() { + Map map = new HashMap(); + if (getServletContext() != null) { + Enumeration enumeration = getServletContext().getAttributeNames(); + while (enumeration.hasMoreElements()) { + Object key = enumeration.nextElement(); + map.put(key, getSession().getAttribute((String) key)); + } + } + return map; + } + + public static String getContextPath() { + if (getRequest() != null) + return getRequest().getContextPath(); + + return null; + } + + public static String getUrl() { + if (getRequest() != null) { + String url = getRequest().getRequestURI(); + String contextpath = getRequest().getContextPath(); + if (url.startsWith(contextpath)) + url = url.substring(contextpath.length() + 1); + + String queryString = getRequest().getQueryString(); + if (queryString != null) + url = url + "?" + queryString; + + return url; + } + return null; + } + + public static Object getBean(String service_name) { + WebApplicationContext webApplicationContext = WebApplicationContextUtils + .getRequiredWebApplicationContext(getServletContext()); + return webApplicationContext.getBean(service_name); + } + + public static String getRealPath(String logicPath) { + if (getRequest() != null) + return getRequest().getRealPath(logicPath); + + return null; + } + + public static String urlDecoder(String arg0) { + try { + return URLDecoder.decode(arg0, "utf-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return ""; + } + + public static String urlEncoder(String arg0) { + if ((arg0 == null) || ("".equals(arg0))) + return ""; + try { + return URLEncoder.encode(arg0, "utf-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return ""; + } + + public String getServletPath() { + return getRequest().getServletPath().replaceFirst("/", ""); + } + + public String getReferer() { + String referer = ""; + if (getRequest().getHeader("Referer") != null) + referer = getRequest().getHeader("Referer"); + else + referer = ""; + + return referer; + } + + public String contextUrl() { + String contextUrl = getRequest().getHeader("host") + "/" + getRequest().getContextPath(); + contextUrl = "http://" + contextUrl.replaceAll("//", "/"); + if (contextUrl.endsWith("/")) + contextUrl = contextUrl.substring(0, contextUrl.length() - 1); + + return contextUrl; + } +} diff --git a/common/src/main/java/com/hzya/frame/servlet/SpringContextUtil.java b/common/src/main/java/com/hzya/frame/servlet/SpringContextUtil.java new file mode 100644 index 00000000..5d07d4e9 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/servlet/SpringContextUtil.java @@ -0,0 +1,44 @@ +package com.hzya.frame.servlet; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +/** + * @Description spring上下文 + * @Author xiang2lin + * @Date 2021/3/20 16:04 + **/ +@Component +@Lazy(value = false) +public class SpringContextUtil implements ApplicationContextAware { + private static ApplicationContext applicationContext; // Spring应用上下文环境 + + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + if (SpringContextUtil.applicationContext == null) { + SpringContextUtil.applicationContext = applicationContext; + } + } + + public static ApplicationContext getApplicationContext() { + return applicationContext; + } + + public static Object getBean(String name) throws BeansException { + return applicationContext.getBean(name); + } + + public static Object getBean(String name, Class requiredType) + throws BeansException { + return applicationContext.getBean(name, requiredType); + } + + // 通过class获取Bean. + public static T getBean(Class clazz) { + return getApplicationContext().getBean(clazz); + } +} diff --git a/common/src/main/java/com/hzya/frame/stringutil/StringUtil.java b/common/src/main/java/com/hzya/frame/stringutil/StringUtil.java new file mode 100644 index 00000000..db8f8a67 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/stringutil/StringUtil.java @@ -0,0 +1,62 @@ +package com.hzya.frame.stringutil; + +import cn.hutool.core.util.StrUtil; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * @Description 字符串工具 + * @Author xiang2lin + * @Date 2022/3/1 15:47 + **/ +public class StringUtil { + + /** + * 替换空白符,包括 \s \t \r\n + * @param str + * @return + */ + public static String replaceBlank(String str){ + String result= null; + if (str == null) { + return result; + } else { + //Pattern p = Pattern.compile("\\s*|\t|\r|\n|\\u00A0"); + Pattern p = Pattern.compile("[\\s\\t\\r\\n\\u00A0]"); + Matcher m = p.matcher(str); + result= m.replaceAll(""); + return result; + } + } + + + /** + * 按_拆分字符串 + * @param code_name + * @return + */ + public static List splitStr(String code_name){ + List list = new ArrayList<>(); + if (StrUtil.isNotBlank(code_name)){ + list = StrUtil.split(code_name, StrUtil.C_UNDERLINE); + if (list.size() == 1){ + list.add(""); + } + }else { + list.add(""); + list.add(""); + } + return list; + } + + //null转成空字符串 + public static String nullConvert(String str){ + if (null == str){ + return ""; + } + return str; + } +} diff --git a/common/src/main/java/com/hzya/frame/threadPool/TaskExecutorConfig.java b/common/src/main/java/com/hzya/frame/threadPool/TaskExecutorConfig.java new file mode 100644 index 00000000..5fcdf523 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/threadPool/TaskExecutorConfig.java @@ -0,0 +1,39 @@ +package com.hzya.frame.threadPool; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.ThreadPoolExecutor; + +@Configuration +@EnableAsync +public class TaskExecutorConfig { + // 获取服务器的cpu个数 + private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); + // 核心线程数量 + private static final int COUR_SIZE = CPU_COUNT * 2+1; + // 线程最大数量 + private static final int MAX_COUR_SIZE = COUR_SIZE * 4; + + @Bean(name = "taskExecutor") + public TaskExecutor getAsyncExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + //核心线程数5:线程池创建时候初始化的线程数 + executor.setCorePoolSize(CPU_COUNT); + //最大线程数10:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 + executor.setMaxPoolSize(COUR_SIZE); + //缓冲队列20:用来缓冲执行任务的队列 + executor.setQueueCapacity(Integer.MAX_VALUE); + //允许线程的空闲时间200秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁 + executor.setKeepAliveSeconds(200); + //线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池 + executor.setThreadNamePrefix("taskExecutor-"); + // 线程拒绝任务处理策略:没精力处理时,直接拒绝任务;若执行程序已被关闭,则直接丢弃 + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + executor.initialize(); + return executor; + } +} diff --git a/common/src/main/java/com/hzya/frame/util/AESUtil.java b/common/src/main/java/com/hzya/frame/util/AESUtil.java new file mode 100644 index 00000000..349869d8 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/AESUtil.java @@ -0,0 +1,80 @@ +package com.hzya.frame.util; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.crypto.SecureUtil; +import cn.hutool.crypto.symmetric.SymmetricAlgorithm; +import cn.hutool.crypto.symmetric.SymmetricCrypto; + +/** + * @Description AES加密解密 + * @Author xiang2lin + * @Date 2021/3/16 15:48 + **/ +public class AESUtil { + private static String KEY = "`o7eotan9ws8c:aj"; + + /** + * AES加密 + * @param data 要加密的内容 + * @return 密文字符串 + */ + public static String encrypt(String data){ + if (StrUtil.isNotEmpty(data)){ + return encrypt(data,KEY); + } + return null; + } + + /** + * AES加密 + * @param data 待加密的字符串 + * @param key 秘钥 + * @return 加密后的字符串 + */ + public static String encrypt(String data,String key){ + if (StrUtil.isNotEmpty(data) && StrUtil.isNotEmpty(key)){ + return SecureUtil.aes(key.getBytes()).encryptHex(data); + } + return null; + } + /** + * AES加密 + * @param content 待加密的字符串 + * @return 加密后的字符串 + */ + public static String encipher(String content){ + // 生成密钥 + byte[] byteKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), KEY.getBytes()).getEncoded(); + SymmetricCrypto aes = SecureUtil.aes(byteKey); + // 加密 + String encryptData = aes.encryptBase64(content); + // 解密 + //String decryptData = aes.decryptStr(encryptData); + return encryptData; + } + /** + * AES解密 + * @param ciphertext 密文 + * @return 解密后的明文 + */ + public static String decrypt(String ciphertext){ + if (StrUtil.isNotEmpty(ciphertext)){ + return decrypt(ciphertext,KEY); + } + return null; + } + + /** + * AES解密 + * @param ciphertext 密文 + * @param key 秘钥 + * @return 解密后的明文 + */ + public static String decrypt(String ciphertext,String key){ + if (StrUtil.isNotEmpty(ciphertext) && StrUtil.isNotEmpty(key)){ + return SecureUtil.aes(key.getBytes()).decryptStr(ciphertext); + } + return null; + } + +} diff --git a/common/src/main/java/com/hzya/frame/util/HttpUtil.java b/common/src/main/java/com/hzya/frame/util/HttpUtil.java new file mode 100644 index 00000000..03baff63 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/HttpUtil.java @@ -0,0 +1,155 @@ +package com.hzya.frame.util; + +import cn.hutool.http.HttpRequest; +import cn.hutool.http.HttpResponse; +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; + +import java.util.Map; + + +/** + * @Author lvleigang + * @Description 请求 工具类 + * @Date 11:36 上午 2023/3/6 + * @return + **/ +public class HttpUtil { + private final Integer timeOut = 2000; + private final String encoding = "UTF-8"; + + + //url + public HttpResponse getExecute(String url) { + return HttpRequest.get(url).charset(encoding).timeout(timeOut).execute(); + } + + //encoding + public HttpResponse getExecute(String url, String encoding) { + return HttpRequest.get(url).charset(encoding).timeout(timeOut).execute(); + } + //header + public HttpResponse getExecute(String url, Map header) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).timeout(timeOut).execute(); + } + //body + public HttpResponse getExecute(String url, JSONObject body) { + return HttpRequest.get(url).charset(encoding).body(JSON.toJSONString(body)).timeout(timeOut).execute(); + } + //timeout + public HttpResponse getExecute(String url, Integer timeout) { + return HttpRequest.get(url).charset(encoding).timeout(timeout).execute(); + } + //encoding header + public HttpResponse getExecute(String url, String encoding, Map header) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).timeout(timeOut).execute(); + } + //encoding body + public HttpResponse getExecute(String url, String encoding, JSONObject body) { + return HttpRequest.get(url).charset(encoding).body(JSON.toJSONString(body)).timeout(timeOut).execute(); + } + //encoding timeout + public HttpResponse getExecute(String url, String encoding, Integer timeout) { + return HttpRequest.get(url).charset(encoding).timeout(timeout).execute(); + } + //header body + public HttpResponse getExecute(String url, Map header, JSONObject body) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).body(JSON.toJSONString(body)).timeout(timeOut).execute(); + } + //header timeout + public HttpResponse getExecute(String url, Map header, Integer timeout) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).timeout(timeout).execute(); + } + //body timeout + public HttpResponse getExecute(String url,JSONObject body, Integer timeout) { + return HttpRequest.get(url).charset(encoding).body(JSON.toJSONString(body)).timeout(timeout).execute(); + } + //encoding header body + public HttpResponse getExecute(String url, String encoding, Map header,JSONObject body) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).body(JSON.toJSONString(body)).timeout(timeOut).execute(); + } + //encoding header timeout + public HttpResponse getExecute(String url, String encoding, Map header, Integer timeout) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).timeout(timeout).execute(); + } + //encoding body timeout + public HttpResponse getExecute(String url, String encoding,JSONObject body, Integer timeout) { + return HttpRequest.get(url).charset(encoding).body(JSON.toJSONString(body)).timeout(timeout).execute(); + } + //header body timeout + public HttpResponse getExecute(String url,Map header, JSONObject body, Integer timeout) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).body(JSON.toJSONString(body)).timeout(timeout).execute(); + } + //encoding header body timeout + public HttpResponse getExecute(String url, String encoding, Map header, JSONObject body,Integer timeout) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).body(JSON.toJSONString(body)).timeout(timeout).execute(); + } + + + + //url + public HttpResponse postExecute(String url) { + return HttpRequest.get(url).charset(encoding).timeout(timeOut).execute(); + } + + //encoding + public HttpResponse postExecute(String url, String encoding) { + return HttpRequest.get(url).charset(encoding).timeout(timeOut).execute(); + } + //header + public HttpResponse postExecute(String url, Map header) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).timeout(timeOut).execute(); + } + //body + public HttpResponse postExecute(String url, JSONObject body) { + return HttpRequest.get(url).charset(encoding).body(JSON.toJSONString(body)).timeout(timeOut).execute(); + } + //timeout + public HttpResponse postExecute(String url, Integer timeout) { + return HttpRequest.get(url).charset(encoding).timeout(timeout).execute(); + } + //encoding header + public HttpResponse postExecute(String url, String encoding, Map header) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).timeout(timeOut).execute(); + } + //encoding body + public HttpResponse postExecute(String url, String encoding, JSONObject body) { + return HttpRequest.get(url).charset(encoding).body(JSON.toJSONString(body)).timeout(timeOut).execute(); + } + //encoding timeout + public HttpResponse postExecute(String url, String encoding, Integer timeout) { + return HttpRequest.get(url).charset(encoding).timeout(timeout).execute(); + } + //header body + public HttpResponse postExecute(String url, Map header, JSONObject body) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).body(JSON.toJSONString(body)).timeout(timeOut).execute(); + } + //header timeout + public HttpResponse postExecute(String url, Map header, Integer timeout) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).timeout(timeout).execute(); + } + //body timeout + public HttpResponse postExecute(String url,JSONObject body, Integer timeout) { + return HttpRequest.get(url).charset(encoding).body(JSON.toJSONString(body)).timeout(timeout).execute(); + } + //encoding header body + public HttpResponse postExecute(String url, String encoding, Map header,JSONObject body) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).body(JSON.toJSONString(body)).timeout(timeOut).execute(); + } + //encoding header timeout + public HttpResponse postExecute(String url, String encoding, Map header, Integer timeout) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).timeout(timeout).execute(); + } + //encoding body timeout + public HttpResponse postExecute(String url, String encoding,JSONObject body, Integer timeout) { + return HttpRequest.get(url).charset(encoding).body(JSON.toJSONString(body)).timeout(timeout).execute(); + } + //header body timeout + public HttpResponse postExecute(String url,Map header, JSONObject body, Integer timeout) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).body(JSON.toJSONString(body)).timeout(timeout).execute(); + } + //encoding header body timeout + public HttpResponse postExecute(String url, String encoding, Map header, JSONObject body,Integer timeout) { + return HttpRequest.get(url).charset(encoding).addHeaders(header).body(JSON.toJSONString(body)).timeout(timeout).execute(); + } +} diff --git a/common/src/main/java/com/hzya/frame/util/IPHelper.java b/common/src/main/java/com/hzya/frame/util/IPHelper.java new file mode 100644 index 00000000..0a8493ad --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/IPHelper.java @@ -0,0 +1,59 @@ +package com.hzya.frame.util; + +import javax.servlet.http.HttpServletRequest; + +public class IPHelper { + + + /****************************************************************************************************** + * + * + * 获取用户真实IP地址,不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址, + * 可是,如果通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP值 + * + * + * @return ip + * + * @auther xubin + * @serialData 20180827 编写 + * + * + */ + public static String getIpAddr(HttpServletRequest request) { + String ip = request.getHeader("x-forwarded-for"); + /*System.out.println("x-forwarded-for ip: " + ip);*/ + if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) { + // 多次反向代理后会有多个ip值,第一个ip才是真实ip + if( ip.indexOf(",")!=-1 ){ + ip = ip.split(",")[0]; + } + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + /*System.out.println("Proxy-Client-IP ip: " + ip);*/ + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + /*System.out.println("WL-Proxy-Client-IP ip: " + ip);*/ + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_CLIENT_IP"); + /*System.out.println("HTTP_CLIENT_IP ip: " + ip);*/ + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_X_FORWARDED_FOR"); + /*System.out.println("HTTP_X_FORWARDED_FOR ip: " + ip);*/ + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getHeader("X-Real-IP"); + /*System.out.println("X-Real-IP ip: " + ip);*/ + } + if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + /*System.out.println("getRemoteAddr ip: " + ip);*/ + } + /*System.out.println("获取客户端ip: " + ip);*/ + return ip; + } + +} diff --git a/common/src/main/java/com/hzya/frame/util/ServiceUtil.java b/common/src/main/java/com/hzya/frame/util/ServiceUtil.java new file mode 100644 index 00000000..fb3bd437 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/ServiceUtil.java @@ -0,0 +1,43 @@ +package com.hzya.frame.util; + +import com.alibaba.fastjson.JSONObject; + +/** + * @Author lvleigang + * @Description service 工具类 + * @Date 11:36 上午 2023/3/6 + * @return + **/ +public class ServiceUtil { + /** + * @param key 健 + * @param jsonObject json数据 + * @return java.lang.String + * @Author lvleigang + * @Description 根据key获取数据jsonObject中的数据,如果没有设置默认值 + * @Date 3:41 下午 2023/2/14 + **/ + protected T getData(String key, JSONObject jsonObject, Class clz) { + if (checkStr(jsonObject.getString(key))) { + return jsonObject.getJSONObject(key).toJavaObject(clz); + } + return null; + } + + /** + * @param str + * @return void + * @Author lvleigang + * @Description 校验字符串 + * @Date 11:41 上午 2022/12/7 + **/ + private Boolean checkStr(String str) { + Boolean flag = true; + if (str == null || "".equals(str)) { + flag = false; + } + return flag; + } + + +} diff --git a/common/src/main/java/com/hzya/frame/util/bipV3/Base64Util.java b/common/src/main/java/com/hzya/frame/util/bipV3/Base64Util.java new file mode 100644 index 00000000..233803cd --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/bipV3/Base64Util.java @@ -0,0 +1,31 @@ +package com.hzya.frame.util.bipV3; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import java.io.IOException; + +/** + * Base64工具类 + * + * @author liyang + * + */ +public class Base64Util { + + /** + * Base64编码 + */ + public static String encryptBASE64(byte[] key) { + return (new BASE64Encoder()).encodeBuffer(key); + } + + /** + * Base64解码 + * @throws IOException + */ + public static byte[] decryptBASE64(String key) throws IOException { + return (new BASE64Decoder()).decodeBuffer(key); + } + +} diff --git a/common/src/main/java/com/hzya/frame/util/bipV3/CipherConstant.java b/common/src/main/java/com/hzya/frame/util/bipV3/CipherConstant.java new file mode 100644 index 00000000..f918f1da --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/bipV3/CipherConstant.java @@ -0,0 +1,12 @@ +package com.hzya.frame.util.bipV3; + +public class CipherConstant { + // 加密算法规则AES对称加密 + public static final String AES = "AES"; + // public static final String AES_ALGORITHM = "AES"; + public static final String AES_ALGORITHM = "AES/CTR/NoPadding"; + // 加密算法规则RSA非对称加密 + public static final String RSA = "RSA"; + // public static final String RSA_ALGORITHM = "RSA"; + public static final String RSA_ALGORITHM = "RSA/ECB/OAEPWithSHA-256AndMGF1Padding"; +} diff --git a/common/src/main/java/com/hzya/frame/util/bipV3/Encryption.java b/common/src/main/java/com/hzya/frame/util/bipV3/Encryption.java new file mode 100644 index 00000000..2cec44e2 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/bipV3/Encryption.java @@ -0,0 +1,98 @@ +package com.hzya.frame.util.bipV3; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.OAEPParameterSpec; +import javax.crypto.spec.PSource; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.security.spec.MGF1ParameterSpec; + +/** + * 加密类 + * + * @author liyang + */ +public class Encryption { + + // RSA最大加密明文大小 + private static final int MAX_ENCRYPT_BLOCK = 117; + + /** + * symEncrypt 对称加密 + * + * @param strkey 对称密钥 + * @param src 原文 + * @return 密文 + */ + public static String symEncrypt(String strkey, String src) throws Exception { + String target = null; + try { + Key key = KeysFactory.getSymKey(strkey); + //加密 + Cipher cipher = Cipher.getInstance(CipherConstant.AES_ALGORITHM); + IvParameterSpec iv = new IvParameterSpec(strkey.substring(0, 16).getBytes()); + cipher.init(Cipher.ENCRYPT_MODE, key, iv); + byte[] encodeResult = cipher.doFinal(src.getBytes(StandardCharsets.UTF_8)); + target = Base64Util.encryptBASE64(encodeResult); + } catch (NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedEncodingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + throw new Exception("加密失败" + e.getMessage()); + } + return target; + } + + /** + * pubEncrypt 公钥加密 + * + * @param pubKey 公钥 + * @param src 原文 + * @return 密文 + * @throws IOException + * @throws Exception + */ + public static String pubEncrypt(String pubKey, String src) throws Exception { + String target = null; + ByteArrayOutputStream out = null; + try { + Key key = KeysFactory.getPublicKey(pubKey); + + Cipher cipher = Cipher.getInstance(CipherConstant.RSA_ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, key,new OAEPParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), PSource.PSpecified.DEFAULT)); + byte[] data = src.getBytes(); + int inputLen = data.length; + out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // 对数据分段加密 + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_ENCRYPT_BLOCK; + } + + target = Base64Util.encryptBASE64(out.toByteArray()); + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + throw new Exception("加密失败" + e.getMessage()); + } finally { + if (out != null) { + out.close(); + } + } + return target; + } + +} diff --git a/common/src/main/java/com/hzya/frame/util/bipV3/KeyPairs.java b/common/src/main/java/com/hzya/frame/util/bipV3/KeyPairs.java new file mode 100644 index 00000000..9df249c8 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/bipV3/KeyPairs.java @@ -0,0 +1,28 @@ +package com.hzya.frame.util.bipV3; + +import java.security.KeyPair; + +/** + * KeyPairs + * 主键对 + * + * @author liyang + * @date: 2019-5-20下午4:34:51 + * + */ +public class KeyPairs { + + private KeyPair keyPair; + + public KeyPairs(KeyPair keyPair){ + this.keyPair = keyPair; + } + + public String getPublicKey(){ + return Base64Util.encryptBASE64(keyPair.getPublic().getEncoded()); + } + + public String getPrivateKey(){ + return Base64Util.encryptBASE64(keyPair.getPrivate().getEncoded()); + } +} diff --git a/common/src/main/java/com/hzya/frame/util/bipV3/KeysFactory.java b/common/src/main/java/com/hzya/frame/util/bipV3/KeysFactory.java new file mode 100644 index 00000000..c14ea488 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/bipV3/KeysFactory.java @@ -0,0 +1,103 @@ +package com.hzya.frame.util.bipV3; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +/** + * Key工厂类 + * + * @author liyang + */ +public class KeysFactory { + + /** + * buildAsymKey 生成一组非对称密钥 + * + * @return KeyPair key是PublicKey和PrivateKey + * @throws NoSuchAlgorithmException + */ + public static KeyPairs buildAsymKey() throws Exception { + + /* 初始化密钥生成器 */ + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CipherConstant.RSA); + keyPairGenerator.initialize(2048, SecureRandomProxy.getRandomInstance()); + + /* 生成密钥 */ + return new KeyPairs(keyPairGenerator.generateKeyPair()); + } + + /** + * buildAsymKey 生成一个对称密钥 + * + * @return 对称密钥 + * @throws NoSuchAlgorithmException + * @throws Exception + */ + public static String buildSymKey() throws Exception { + // 生成Key + KeyGenerator keyGenerator = KeyGenerator.getInstance(CipherConstant.AES); + + keyGenerator.init(256, SecureRandomProxy.getRandomInstance()); + // 使用上面这种初始化方法可以特定种子来生成密钥,这样加密后的密文是唯一固定的。 + SecretKey secretKey = keyGenerator.generateKey(); + + return Base64Util.encryptBASE64(secretKey.getEncoded()); + + } + + public static Key getPublicKey(String pubKey) throws Exception { + Key key = null; + + try { + byte[] keyBytes = Base64Util.decryptBASE64(pubKey); + KeyFactory keyFactory = KeyFactory.getInstance(CipherConstant.RSA); + + X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); + key = keyFactory.generatePublic(x509KeySpec); + + } catch (Exception e) { + throw new Exception("无效的密钥 " + e.getMessage()); + } + + return key; + } + + public static Key getPrivateKey(String priKey) throws Exception { + Key key = null; + + try { + byte[] keyBytes = Base64Util.decryptBASE64(priKey); + + KeyFactory keyFactory = KeyFactory.getInstance(CipherConstant.RSA); + + PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); + key = keyFactory.generatePrivate(pkcs8KeySpec); + + } catch (Exception e) { + throw new Exception("无效密钥 " + e.getMessage()); + } + + return key; + } + + public static Key getSymKey(String symKey) throws Exception { + Key key = null; + + try { + byte[] keyBytes = Base64Util.decryptBASE64(symKey); + // Key转换 + key = new SecretKeySpec(keyBytes, CipherConstant.AES); + } catch (Exception e) { + throw new Exception("无效密钥 " + e.getMessage()); + } + + return key; + } +} diff --git a/common/src/main/java/com/hzya/frame/util/bipV3/SHA256Util.java b/common/src/main/java/com/hzya/frame/util/bipV3/SHA256Util.java new file mode 100644 index 00000000..bf3f4bc2 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/bipV3/SHA256Util.java @@ -0,0 +1,51 @@ +package com.hzya.frame.util.bipV3; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +public class SHA256Util { + + public static String getSHA256(String str, String key) { + //加盐 + byte[] salt = new byte[16]; + try { + SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + random.setSeed(key.getBytes()); + random.nextBytes(salt); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + String salt_string = Base64Util.encryptBASE64(salt); + //System.out.println("salt_String::" + salt_string); + return getSHA256(str + salt_string.replaceAll("\r|\n", "")); + } + + private static String getSHA256(String str) { + MessageDigest messageDigest; + String encodestr = ""; + try { + messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(str.getBytes(StandardCharsets.UTF_8)); + encodestr = byte2Hex(messageDigest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return encodestr; + } + + private static String byte2Hex(byte[] bytes) { + StringBuffer stringBuffer = new StringBuffer(); + String temp = null; + for (int i = 0; i < bytes.length; i++) { + temp = Integer.toHexString(bytes[i] & 0xFF); + if (temp.length() == 1) { + stringBuffer.append("0"); + } + stringBuffer.append(temp); + } + return stringBuffer.toString(); + } + +} diff --git a/common/src/main/java/com/hzya/frame/util/bipV3/SecureRandomProxy.java b/common/src/main/java/com/hzya/frame/util/bipV3/SecureRandomProxy.java new file mode 100644 index 00000000..63f5ae08 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/bipV3/SecureRandomProxy.java @@ -0,0 +1,27 @@ +package com.hzya.frame.util.bipV3; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; + +/** + * @Describe + * @Author lizhmf + * @Date 2021/3/16 19:32 + * @Version 1.0 + */ +public class SecureRandomProxy { + + public static SecureRandom getRandomInstance() { + SecureRandom random = null; + try { + random = SecureRandom.getInstance("SHA1PRNG"); +// random = SecureRandom.getInstance("NativePRNG"); +// random = SecureRandom.getInstance("NativePRNGNonBlocking"); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + + return random; + } +} + diff --git a/common/src/main/java/com/hzya/frame/util/oldNcc/Base64Util.java b/common/src/main/java/com/hzya/frame/util/oldNcc/Base64Util.java new file mode 100644 index 00000000..4757712c --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/oldNcc/Base64Util.java @@ -0,0 +1,31 @@ +package com.hzya.frame.util.oldNcc; + +import java.io.IOException; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +/** + * Base64������ + * + * @author liyang + * + */ +public class Base64Util { + + /** + * Base64���� + */ + public static String encryptBASE64(byte[] key) { + return (new BASE64Encoder()).encodeBuffer(key); + } + + /** + * Base64���� + * @throws IOException + */ + public static byte[] decryptBASE64(String key) throws IOException { + return (new BASE64Decoder()).decodeBuffer(key); + } + +} diff --git a/common/src/main/java/com/hzya/frame/util/oldNcc/CipherConstant.java b/common/src/main/java/com/hzya/frame/util/oldNcc/CipherConstant.java new file mode 100644 index 00000000..e18a7cb4 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/oldNcc/CipherConstant.java @@ -0,0 +1,8 @@ +package com.hzya.frame.util.oldNcc; + +public class CipherConstant { + // �����㷨����AES�ԳƼ��� + public static final String ALGORITHM_AES = "AES"; + // �����㷨����RSA�ǶԳƼ��� + public static final String ALGORITHM_RSA = "RSA"; +} diff --git a/common/src/main/java/com/hzya/frame/util/oldNcc/CompressUtil.java b/common/src/main/java/com/hzya/frame/util/oldNcc/CompressUtil.java new file mode 100644 index 00000000..e5f2671c --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/oldNcc/CompressUtil.java @@ -0,0 +1,173 @@ +package com.hzya.frame.util.oldNcc; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.zip.DataFormatException; +import java.util.zip.Deflater; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; +import java.util.zip.Inflater; + +/** + * ѹ�������� + * + * @author liyang + * + */ +public class CompressUtil { + + private static int buffSize = 1024; + + /** + * deflaterCompress Ĭ��ѹ�� + * + * @param source + * ԭ�� + * @return + * @throws IOException + * @throws BizException + * @throws Exception + */ + public static String deflaterCompress(String source) throws Exception { + String value = null; + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + Deflater compressor = new Deflater(); + + try { + + byte[] input = source.getBytes(StandardCharsets.UTF_8); + // ����ѹ���Ǽ� + compressor.setLevel(Deflater.DEFAULT_COMPRESSION); + compressor.setInput(input); + compressor.finish(); + final byte[] buf = new byte[buffSize]; + + while (!compressor.finished()) { + int count = compressor.deflate(buf); + bos.write(buf, 0, count); + } + value = Base64Util.encryptBASE64(bos.toByteArray()); + + } finally { + bos.close(); + compressor.end(); + } + + return value; + } + + /** + * deflaterDecompress Ĭ�Ͻ�ѹ + * + * @param source + * ѹ�����ı� + * @return + * @throws IOException + * @throws @throws + * Exception + */ + public static String deflaterDecompress(String source) throws Exception { + String value = null; + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + Inflater decompressor = new Inflater(); + + try { + byte[] input = Base64Util.decryptBASE64(source); + + decompressor.setInput(input); + final byte[] buf = new byte[buffSize]; + + while (!decompressor.finished()) { + int count = decompressor.inflate(buf); + bos.write(buf, 0, count); + } + + value = new String(bos.toByteArray(), StandardCharsets.UTF_8); + } catch (IOException | DataFormatException e) { + throw new Exception("��ѹ�쳣 " + e.getMessage()); + } finally { + bos.close(); + decompressor.end(); + } + return value; + } + + /** + * gzipCompress ����gzipѹ�� + * + * @param source + * ԭ�� + * @return + * @throws IOException + * @throws BizException + * @throws Exception + */ + public static String gzipCompress(String source) throws Exception { + String value = null; + + ByteArrayOutputStream out = null; + + try { + out = new ByteArrayOutputStream(); + GZIPOutputStream gzip = new GZIPOutputStream(out); + byte[] input = source.getBytes(StandardCharsets.UTF_8); + gzip.write(input); + gzip.close(); + value = Base64Util.encryptBASE64(out.toByteArray()); + } catch (IOException e) { + throw new Exception("ѹ���쳣 " + e.getMessage()); + }finally { + if(out != null){ + out.close(); + } + } + + return value; + } + + /** + * gzipDecompress gzip��ѹ + * + * @param source + * ѹ�����ı� + * @return + * @throws BizException + * @throws Exception + */ + public static String gzipDecompress(String source) throws Exception { + String value = null; + + ByteArrayOutputStream out = null; + ByteArrayInputStream in = null; + + try { + byte[] input = Base64Util.decryptBASE64(source); + out = new ByteArrayOutputStream(); + in = new ByteArrayInputStream(input); + GZIPInputStream ungzip = new GZIPInputStream(in); + + byte[] buffer = new byte[buffSize]; + int n; + while ((n = ungzip.read(buffer)) >= 0) { + out.write(buffer, 0, n); + } + ungzip.close(); + value = new String(out.toByteArray(), StandardCharsets.UTF_8); + } catch (IOException e) { + throw new Exception("ѹ���쳣 " + e.getMessage()); + } finally { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + + } + return value; + } +} diff --git a/common/src/main/java/com/hzya/frame/util/oldNcc/Decryption.java b/common/src/main/java/com/hzya/frame/util/oldNcc/Decryption.java new file mode 100644 index 00000000..bdb58ecb --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/oldNcc/Decryption.java @@ -0,0 +1,105 @@ +package com.hzya.frame.util.oldNcc; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; + +/** + * ������ + * + * @author liyang + * + */ +public class Decryption { + + // RSA���������Ĵ�С + private static final int MAX_DECRYPT_BLOCK = 128; + + /** + * symDecrypt �Գƽ��� + * + * @param strkey �Գ���Կ + * @param src ���� + * @return ԭ�� + * @throws IOException + * @throws Exception + */ + public static String symDecrypt(String strkey, String src) throws Exception { + + String target = null; + + try { + Key key = KeysFactory.getSymKey(strkey); + // ���� + Cipher cipher = Cipher.getInstance(CipherConstant.ALGORITHM_AES); + cipher.init(Cipher.DECRYPT_MODE, key); + byte[] decodeResult = cipher.doFinal(Base64Util.decryptBASE64(src)); + target = new String(decodeResult); + + } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException | InvalidKeyException e) { + e.printStackTrace(); + throw new Exception("����ʧ��" + e.getMessage()); + } + + return target; + } + + /** + * priDecrypt ˽Կ���� + * + * @param priKey ˽Կ + * @param src ���� + * @return ԭ�� + * @throws IOException + * @throws Exception + */ + public static String priDecrypt(String priKey, String src) throws Exception { + + String target = null; + ByteArrayOutputStream out = null; + try { + Key key = KeysFactory.getPrivateKey(priKey); + + // ���� + Cipher cipher = Cipher.getInstance(CipherConstant.ALGORITHM_RSA); + cipher.init(Cipher.DECRYPT_MODE, key); + // byte[] decodeResult = cipher.doFinal(src.getBytes(CHARSET)); + // target = new String(decodeResult); + + byte[] data = Base64Util.decryptBASE64(src); + int inputLen = data.length; + out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // �����ݷֶν��� + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_DECRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_DECRYPT_BLOCK; + } + target = new String(out.toByteArray()); + + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + e.printStackTrace(); + throw new Exception("����ʧ��" + e.getMessage()); + }finally{ + if(out != null){ + out.close(); + } + } + return target; + } +} diff --git a/common/src/main/java/com/hzya/frame/util/oldNcc/Encryption.java b/common/src/main/java/com/hzya/frame/util/oldNcc/Encryption.java new file mode 100644 index 00000000..012b5e21 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/oldNcc/Encryption.java @@ -0,0 +1,103 @@ +package com.hzya.frame.util.oldNcc; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; + +/** + * ������ + * + * @author liyang + * + */ +public class Encryption { + + // RSA���������Ĵ�С + private static final int MAX_ENCRYPT_BLOCK = 117; + + /** + * symEncrypt �ԳƼ��� + * + * @param strkey + * �Գ���Կ + * @param src + * ԭ�� + * @return ���� + * @throws BizException + */ + public static String symEncrypt(String strkey, String src) throws Exception { + String target = null; + try { + Key key = KeysFactory.getSymKey(strkey); + // ���� + Cipher cipher = Cipher.getInstance(CipherConstant.ALGORITHM_AES); + cipher.init(Cipher.ENCRYPT_MODE, key); + byte[] encodeResult = cipher.doFinal(src.getBytes(StandardCharsets.UTF_8)); + target = Base64Util.encryptBASE64(encodeResult); + } catch (NoSuchAlgorithmException | NoSuchPaddingException | UnsupportedEncodingException | InvalidKeyException | IllegalBlockSizeException + | BadPaddingException e) { + e.printStackTrace(); + throw new Exception("����ʧ��" + e.getMessage()); + } + return target; + } + + /** + * pubEncrypt ��Կ���� + * + * @param pubKey + * ��Կ + * @param src + * ԭ�� + * @return ���� + * @throws IOException + * @throws Exception + */ + public static String pubEncrypt(String pubKey, String src) throws Exception { + String target = null; + ByteArrayOutputStream out = null; + try { + Key key = KeysFactory.getPublicKey(pubKey); + + Cipher cipher = Cipher.getInstance(CipherConstant.ALGORITHM_RSA); + cipher.init(Cipher.ENCRYPT_MODE, key); + // encodeResult = cipher.doFinal(src.getBytes()); + byte[] data = src.getBytes(); + int inputLen = data.length; + out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + // �����ݷֶμ��� + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_ENCRYPT_BLOCK; + } + + target = Base64Util.encryptBASE64(out.toByteArray()); + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + e.printStackTrace(); + throw new Exception("����ʧ��" + e.getMessage()); + }finally{ + if(out != null){ + out.close(); + } + } + return target; + } +} diff --git a/common/src/main/java/com/hzya/frame/util/oldNcc/KeyPairs.java b/common/src/main/java/com/hzya/frame/util/oldNcc/KeyPairs.java new file mode 100644 index 00000000..8b2da135 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/oldNcc/KeyPairs.java @@ -0,0 +1,27 @@ +package com.hzya.frame.util.oldNcc; + +import java.security.KeyPair; + +/** + * KeyPairs ������ + * + * @author liyang + * @date: 2019-5-20����4:34:51 + * + */ +public class KeyPairs { + + private KeyPair keyPair; + + public KeyPairs(KeyPair keyPair){ + this.keyPair = keyPair; + } + + public String getPublicKey(){ + return Base64Util.encryptBASE64(keyPair.getPublic().getEncoded()); + } + + public String getPrivateKey(){ + return Base64Util.encryptBASE64(keyPair.getPrivate().getEncoded()); + } +} diff --git a/common/src/main/java/com/hzya/frame/util/oldNcc/KeysFactory.java b/common/src/main/java/com/hzya/frame/util/oldNcc/KeysFactory.java new file mode 100644 index 00000000..23e71199 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/oldNcc/KeysFactory.java @@ -0,0 +1,106 @@ +package com.hzya.frame.util.oldNcc; + +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; + +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.SecretKeySpec; + +/** + * Key������ + * + * @author liyang + * + */ +public class KeysFactory { + + /** + * buildAsymKey ����һ��ǶԳ���Կ + * + * @return KeyPair key��PublicKey��PrivateKey + * @throws NoSuchAlgorithmException + */ + public static KeyPairs buildAsymKey() throws Exception { + + /* ��ʼ����Կ������ */ + KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CipherConstant.ALGORITHM_RSA); + keyPairGenerator.initialize(1024, new SecureRandom()); + + /* ������Կ */ + return new KeyPairs(keyPairGenerator.generateKeyPair()); + } + + /** + * buildAsymKey ����һ���Գ���Կ + * + * @return �Գ���Կ + * @throws NoSuchAlgorithmException + * @throws Exception + */ + public static String buildSymKey() throws Exception{ + // ����Key + KeyGenerator keyGenerator = KeyGenerator.getInstance(CipherConstant.ALGORITHM_AES); + + keyGenerator.init(256, new SecureRandom()); + // ʹ���������ֳ�ʼ�����������ض�������������Կ���������ܺ��������Ψһ�̶��ġ� + SecretKey secretKey = keyGenerator.generateKey(); + + return Base64Util.encryptBASE64(secretKey.getEncoded()); + + } + + public static Key getPublicKey(String pubKey) throws Exception { + Key key = null; + + try { + byte[] keyBytes = Base64Util.decryptBASE64(pubKey); + KeyFactory keyFactory = KeyFactory.getInstance(CipherConstant.ALGORITHM_RSA); + + X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); + key = keyFactory.generatePublic(x509KeySpec); + + } catch (Exception e) { + throw new Exception("��Ч����Կ " + e.getMessage()); + } + + return key; + } + + public static Key getPrivateKey(String priKey) throws Exception { + Key key = null; + + try { + byte[] keyBytes = Base64Util.decryptBASE64(priKey); + + KeyFactory keyFactory = KeyFactory.getInstance(CipherConstant.ALGORITHM_RSA); + + PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); + key = keyFactory.generatePrivate(pkcs8KeySpec); + + } catch (Exception e) { + throw new Exception("��Ч��Կ " + e.getMessage()); + } + + return key; + } + + public static Key getSymKey(String symKey) throws Exception { + Key key = null; + + try { + byte[] keyBytes = Base64Util.decryptBASE64(symKey); + // Keyת�� + key = new SecretKeySpec(keyBytes, CipherConstant.ALGORITHM_AES); + } catch (Exception e) { + throw new Exception("��Ч��Կ " + e.getMessage()); + } + + return key; + } +} diff --git a/common/src/main/java/com/hzya/frame/util/oldNcc/ResultMessageUtil.java b/common/src/main/java/com/hzya/frame/util/oldNcc/ResultMessageUtil.java new file mode 100644 index 00000000..6e57190d --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/oldNcc/ResultMessageUtil.java @@ -0,0 +1,45 @@ +package com.hzya.frame.util.oldNcc; + +public class ResultMessageUtil { + + private boolean success; + + private Object data; + + private String code; + + private String errorMessage; + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public Object getData() { + return data; + } + + public void setData(Object data) { + this.data = data; + } + + public String getCode() { + return code; + } + + public void setCode(String code) { + this.code = code; + } + + public String getErrorMessage() { + return errorMessage; + } + + public void setErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + } + +} diff --git a/common/src/main/java/com/hzya/frame/util/oldNcc/SHA256Util.java b/common/src/main/java/com/hzya/frame/util/oldNcc/SHA256Util.java new file mode 100644 index 00000000..69aa23cb --- /dev/null +++ b/common/src/main/java/com/hzya/frame/util/oldNcc/SHA256Util.java @@ -0,0 +1,36 @@ +package com.hzya.frame.util.oldNcc; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +public class SHA256Util { + + public static String getSHA256(String str) { + MessageDigest messageDigest; + String encodestr = ""; + try { + messageDigest = MessageDigest.getInstance("SHA-256"); + messageDigest.update(str.getBytes(StandardCharsets.UTF_8)); + encodestr = byte2Hex(messageDigest.digest()); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + return encodestr; + } + + private static String byte2Hex(byte[] bytes) { + StringBuffer stringBuffer = new StringBuffer(); + String temp = null; + for (int i = 0; i < bytes.length; i++) { + temp = Integer.toHexString(bytes[i] & 0xFF); + if (temp.length() == 1) { + // 1瀵版鍩屾稉?缍呴惃鍕箻鐞涘矁藟0閹垮秳缍�? + stringBuffer.append("0"); + } + stringBuffer.append(temp); + } + return stringBuffer.toString(); + } + +} diff --git a/common/src/main/java/com/hzya/frame/uuid/UUIDLong.java b/common/src/main/java/com/hzya/frame/uuid/UUIDLong.java new file mode 100644 index 00000000..1fc570d5 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/uuid/UUIDLong.java @@ -0,0 +1,27 @@ +package com.hzya.frame.uuid; + +import java.util.UUID; + +/** + * @Content 返回UUIDlang类型 + * @Author gjh + * @Date 2018/11/1 11:32 + * @Version 1.0 + */ +public class UUIDLong { + public static long longUUID() { + return UUID.randomUUID().getMostSignificantBits(); + } + + public static long absLongUUID() { + while (true) { + long r = longUUID(); + if (r > 5379549617455104L) { + return r; + } + } + } + public static String absLongUUIDStr() { + return String.valueOf(absLongUUID()); + } +} diff --git a/common/src/main/java/com/hzya/frame/uuid/UUIDUtils.java b/common/src/main/java/com/hzya/frame/uuid/UUIDUtils.java new file mode 100644 index 00000000..0fc1db50 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/uuid/UUIDUtils.java @@ -0,0 +1,50 @@ +package com.hzya.frame.uuid; + +import java.util.UUID; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2020-11-22 15:53 + * @Version 1.0 + */ +public class UUIDUtils { + + + /** + *32位默认长度的uuid + * (获取32位uuid) + * + * @return + */ + public static String getUUID() + { + return UUID.randomUUID().toString().replace("-", ""); + } + + /** + * + * (获取指定长度uuid) + * + * @return + */ + public static String getUUID(int len) + { + if(0 >= len) + { + return null; + } + + String uuid = getUUID(); + StringBuffer str = new StringBuffer(); + + for (int i = 0; i < len; i++) + { + str.append(uuid.charAt(i)); + } + + return str.toString(); + } + + +} diff --git a/common/src/main/java/com/hzya/frame/web/action/ApplicationContextUtil.java b/common/src/main/java/com/hzya/frame/web/action/ApplicationContextUtil.java new file mode 100644 index 00000000..7ab549d7 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/action/ApplicationContextUtil.java @@ -0,0 +1,54 @@ +package com.hzya.frame.web.action; + +import com.hzya.frame.basedao.service.BaseDaoUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +import java.util.Map; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-05 9:40 + * @Version 1.0 + */ +@Component +public class ApplicationContextUtil implements ApplicationContextAware { + Logger logger = LoggerFactory.getLogger(ApplicationContextUtil.class); + private static ApplicationContext context; + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + context = applicationContext; + } + public static ApplicationContext getApplicationContext(){ + return context; + } + + public static BaseDaoUtil getBaseDaoUtil(){ + BaseDaoUtil baseDaoUtil = (BaseDaoUtil) ApplicationContextUtil.getBeanByName("baseDaoUtilImpl"); + return baseDaoUtil; + } + /** + * 通过name获取 Bean + * @param name beanName + * @return Object + */ + public static Object getBeanByName(String name){ + return getApplicationContext().getBean(name); + } + public static Map getBeansOfType(Class beaNameClass){ + return getApplicationContext().getBeansOfType(beaNameClass); + } + + public static T getBeanByClass(Class requiredType) throws BeansException{ + return getApplicationContext().getBean(requiredType); + } + + public static Object getBeanByName2(String name){ + return getApplicationContext().getParentBeanFactory(); + } +} diff --git a/common/src/main/java/com/hzya/frame/web/action/DefaultController.java b/common/src/main/java/com/hzya/frame/web/action/DefaultController.java new file mode 100644 index 00000000..7eeef491 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/action/DefaultController.java @@ -0,0 +1,97 @@ +package com.hzya.frame.web.action; + +import com.hzya.frame.web.entity.BaseEntity; +import com.hzya.frame.web.entity.JsonResultEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.support.ApplicationObjectSupport; + + + +/** + * @author 郭军辉 + *

+ * 2016年12月14日下午5:20:51 + */ + +public class DefaultController extends ApplicationObjectSupport { + + protected Logger logger = LoggerFactory.getLogger(DefaultController.class); + private Long currentTime = System.currentTimeMillis(); + + /** + * 请求失败 + * + * @param message 提示信息 + * @return + */ + public JsonResultEntity getFailureMessageEntity(String message) { + return new JsonResultEntity(message, false); + } + + /** + * 请求失败 + * + * @param message 提示信息 + * @return + */ + public JsonResultEntity getFailureMessageEntity(String message, Object mo) { + return new JsonResultEntity(message, false, mo); + } + + /** + * 请求成功 + * + * @param message 提示消息 + * @param mo 返回对象 + * @return + */ + public JsonResultEntity getSuccessMessageEntity(String message, Object mo) { + return new JsonResultEntity(message, true, mo); + } + + /** + * 请求成功 + * + * @param message 提示消息 + * @return + */ + public JsonResultEntity getSuccessMessageEntity(String message ) { + return new JsonResultEntity(message, true); + } + + + + + + + + + + /** + * //绑定org_id + * + * @param entity + * @author 相二林 + * 2019年5月8日 08:38:56 + */ + public void bindOrg(BaseEntity entity) { + //当前登陆人 + /* UserEntity user = SessionContext.getCurrentUser(); + if (null != user) { + //当前登陆人操作级别 + if (!("superadministrator").equals(user.getLevel())) { + if (entity instanceof CompanyEntity) { + OrganizationEntity orgEntity = organizationService.get(user.getOrg_id()); + if (null != orgEntity) { + ((CompanyEntity) entity).setUp_id(orgEntity.getCompany_id()); + } + } else if (entity instanceof OrganizationEntity) { + ((OrganizationEntity) entity).setId(user.getOrg_id()); + } else if (entity instanceof UserEntity) { + entity.setOrg_id(user.getOrg_id()); + } + } + }*/ + } +} diff --git a/common/src/main/java/com/hzya/frame/web/action/SessionContext.java b/common/src/main/java/com/hzya/frame/web/action/SessionContext.java new file mode 100644 index 00000000..a6f3362b --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/action/SessionContext.java @@ -0,0 +1,50 @@ +package com.hzya.frame.web.action; + +import com.alibaba.fastjson.JSONObject; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.servlet.http.HttpServletRequest; + +public class SessionContext { + + private static Log logger = LogFactory.getLog(SessionContext.class); + + private SessionContext() { + } + + + + //获取当前登录对象 + public static JSONObject getCurrentUser(){ + HttpServletRequest request = WebContext.getRequest(); + JSONObject current_user = (JSONObject) request.getSession().getAttribute("_CURRENT_USER"); + return current_user; + } + /** + * 设置用户到session中 + * + * @param userObj + * @return + */ + public static boolean setCurrentUser(JSONObject userObj) { + HttpServletRequest request = WebContext.getRequest(); + boolean flag = true; + request.getSession().setAttribute("_CURRENT_USER", userObj); + return flag; + } + + /** + * 删除当前用户 + * + * @param + * @return + */ + public static boolean removeCurrentUser() { + boolean flag = true; + HttpServletRequest request = WebContext.getRequest(); + request.getSession().removeAttribute("_CURRENT_USER"); + return flag; + } + +} diff --git a/common/src/main/java/com/hzya/frame/web/action/WebContext.java b/common/src/main/java/com/hzya/frame/web/action/WebContext.java new file mode 100644 index 00000000..7f03493b --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/action/WebContext.java @@ -0,0 +1,167 @@ +package com.hzya.frame.web.action; + +import org.springframework.web.context.WebApplicationContext; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.context.support.WebApplicationContextUtils; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +@SuppressWarnings("ALL") +public final class WebContext { + public static HttpServletRequest getRequest() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder + .currentRequestAttributes(); + return attributes.getRequest(); + } + + public static Map getRequestParameterMap() { + if (getRequest() != null) + return getRequest().getParameterMap(); + + return new HashMap(); + } + + public static Map getRequestAttributeMap() { + Map map = new HashMap(); + if (getRequest() != null) { + Enumeration enumeration = getRequest().getAttributeNames(); + while (enumeration.hasMoreElements()) { + Object key = enumeration.nextElement(); + map.put(key, getRequest().getAttribute((String) key)); + } + } + return map; + } + + public static HttpServletResponse getResponse() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder + .currentRequestAttributes(); + return attributes.getResponse(); + } + + public static HttpSession getSession() { + HttpServletRequest request = getRequest(); + if (request != null) + return request.getSession(); + + return null; + } + + public static Map getSessionMap() { + Map map = new HashMap(); + if (getSession() != null) { + Enumeration enumeration = getSession().getAttributeNames(); + while (enumeration.hasMoreElements()) { + Object key = enumeration.nextElement(); + map.put(key, getSession().getAttribute((String) key)); + } + } + return map; + } + + public static ServletContext getServletContext() { + HttpSession actionSession = getSession(); + return actionSession.getServletContext(); + } + + public static Map getApplicationMap() { + Map map = new HashMap(); + if (getServletContext() != null) { + Enumeration enumeration = getServletContext().getAttributeNames(); + while (enumeration.hasMoreElements()) { + Object key = enumeration.nextElement(); + map.put(key, getSession().getAttribute((String) key)); + } + } + return map; + } + + public static String getContextPath() { + if (getRequest() != null) + return getRequest().getContextPath(); + + return null; + } + + public String getServletPath() { + return getRequest().getServletPath().replaceFirst("/", ""); + } + + public String getReferer() { + String referer = ""; + if (getRequest().getHeader("Referer") != null) + referer = getRequest().getHeader("Referer"); + else + referer = ""; + + return referer; + } + + public static String getUrl() { + if (getRequest() != null) { + String url = getRequest().getRequestURI(); + String contextpath = getRequest().getContextPath(); + if (url.startsWith(contextpath)) + url = url.substring(contextpath.length() + 1); + + String queryString = getRequest().getQueryString(); + if (queryString != null) + url = url + "?" + queryString; + + return url; + } + return null; + } + + public static Object getBean(String service_name) { + WebApplicationContext webApplicationContext = WebApplicationContextUtils + .getRequiredWebApplicationContext(getServletContext()); + return webApplicationContext.getBean(service_name); + } + + public static String getRealPath(String logicPath) { + if (getRequest() != null) + return getRequest().getRealPath(logicPath); + + return null; + } + + public String contextUrl() { + String contextUrl = getRequest().getHeader("host") + "/" + getRequest().getContextPath(); + contextUrl = "http://" + contextUrl.replaceAll("//", "/"); + if (contextUrl.endsWith("/")) + contextUrl = contextUrl.substring(0, contextUrl.length() - 1); + + return contextUrl; + } + + public static String urlDecoder(String arg0) { + try { + return URLDecoder.decode(arg0, "utf-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return ""; + } + + public static String urlEncoder(String arg0) { + if ((arg0 == null) || ("".equals(arg0))) + return ""; + try { + return URLEncoder.encode(arg0, "utf-8"); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + return ""; + } +} diff --git a/common/src/main/java/com/hzya/frame/web/cache/ServiceMethodCache.java b/common/src/main/java/com/hzya/frame/web/cache/ServiceMethodCache.java new file mode 100644 index 00000000..2b5ac02a --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/cache/ServiceMethodCache.java @@ -0,0 +1,47 @@ +package com.hzya.frame.web.cache; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.cache.Cache; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.cache.annotation.CachePut; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.stereotype.Component; + +import java.util.HashMap; +import java.util.Map; + +/** + * @Contentservice方法对应表名称缓存 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-07 11:09 + * @Version 1.0 + */ +@Component +public class ServiceMethodCache { + Logger logger = LoggerFactory.getLogger(ServiceMethodCache.class); + private static Map serviceMethodMap = new HashMap(); + + //查询数据库后 数据添加到缓存 + @Cacheable(key = "'_'+#serviceMethod",cacheNames = "cacheManager:",cacheManager = "cacheManager", unless = "#result == null") + public String get(String serviceMethod) { + logger.info("获取:" + serviceMethod); + return serviceMethodMap.get(serviceMethod); + } + + //清除一条缓存,key为要清空的数据 + @CacheEvict(cacheNames = "cacheManager", key = "#serviceMethod") + public void delete(String serviceMethod) { + serviceMethodMap.remove(serviceMethod); + logger.info("删除:" + serviceMethod); + } + + + //修改数据后更新缓存 + @CachePut(cacheNames = "cacheManager", key = "'_'+#map['key']", unless = "#result == null") + public void update(Map map) { + serviceMethodMap.putAll(map); + logger.info("新增[修改]:" + serviceMethodMap.toString()); + } + +} diff --git a/common/src/main/java/com/hzya/frame/web/entity/BaseEntity.java b/common/src/main/java/com/hzya/frame/web/entity/BaseEntity.java new file mode 100644 index 00000000..3bd5beb6 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/entity/BaseEntity.java @@ -0,0 +1,285 @@ +package com.hzya.frame.web.entity; + +import cn.dev33.satoken.stp.StpUtil; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.hzya.frame.uuid.UUIDUtils; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.util.ObjectUtils; + +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +/** + * 基类 + * + * @author Administrator + */ +@JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler", "operations", "roles", "menus"}) +public class BaseEntity implements Serializable { + + private static final long serialVersionUID = 5490326162916773912L; + /** + * 主键ID + */ + private String id; + /** + * 创建人ID + */ + private String create_user_id; + //下级用户id集合 + private List subUserIdList; + /** + * 创建时间ID + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date create_time; + /** + * 修改时间 + */ + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date modify_time; + /** + * 修改人ID + */ + private String modify_user_id; + /** + * 创建人名称 + */ + private String createUserName; + /** + * 所属组织机构 + */ + private String org_id; + /** + * 企业会员ID + */ + private String company_org_id; + /** + * 状态 + */ + private String sts; + //==========分页用============== + private Long start; + private Long limit; + private Long offset; + private String sort; + private String order; + private String dir; + private Long rows; + private Long page; + //==========分页用============== + //账套名 + private String acc_name; + //区分数据库类型 + private String dialect_type; + private Integer pageNum; + private Integer pageSize; + //排序号 + private Long sorts; + /**** + * @Content:数据源 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-07-17 15:05 + * @Param + * @return + **/ + private String dataSourceCode; + + public static long getSerialVersionUID() { + return serialVersionUID; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getCreate_user_id() { + return create_user_id; + } + + public void setCreate_user_id(String create_user_id) { + this.create_user_id = create_user_id; + } + + public List getSubUserIdList() { + return subUserIdList; + } + + public void setSubUserIdList(List subUserIdList) { + this.subUserIdList = subUserIdList; + } + + public Date getCreate_time() { + return create_time; + } + + public void setCreate_time(Date create_time) { + this.create_time = create_time; + } + + public Date getModify_time() { + return modify_time; + } + + public void setModify_time(Date modify_time) { + this.modify_time = modify_time; + } + + public String getModify_user_id() { + return modify_user_id; + } + + public void setModify_user_id(String modify_user_id) { + this.modify_user_id = modify_user_id; + } + + public String getCreateUserName() { + return createUserName; + } + + public void setCreateUserName(String createUserName) { + this.createUserName = createUserName; + } + + public String getOrg_id() { + return org_id; + } + + public void setOrg_id(String org_id) { + this.org_id = org_id; + } + + public String getCompany_org_id() { + return company_org_id; + } + + public void setCompany_org_id(String company_org_id) { + this.company_org_id = company_org_id; + } + + public String getSts() { + return sts; + } + + public void setSts(String sts) { + this.sts = sts; + } + + public Long getStart() { + return start; + } + + public void setStart(Long start) { + this.start = start; + } + + public Long getLimit() { + return limit; + } + + public void setLimit(Long limit) { + this.limit = limit; + } + + public Long getOffset() { + return offset; + } + + public void setOffset(Long offset) { + this.offset = offset; + } + + public String getSort() { + return sort; + } + + public void setSort(String sort) { + this.sort = sort; + } + + public String getOrder() { + return order; + } + + public void setOrder(String order) { + this.order = order; + } + + public String getDir() { + return dir; + } + + public void setDir(String dir) { + this.dir = dir; + } + + public Long getRows() { + return rows; + } + + public void setRows(Long rows) { + this.rows = rows; + } + + public Long getPage() { + return page; + } + + public void setPage(Long page) { + this.page = page; + } + + public String getAcc_name() { + return acc_name; + } + + public void setAcc_name(String acc_name) { + this.acc_name = acc_name; + } + + public String getDialect_type() { + return dialect_type; + } + + public void setDialect_type(String dialect_type) { + this.dialect_type = dialect_type; + } + + public Integer getPageNum() { + return pageNum; + } + + public void setPageNum(Integer pageNum) { + this.pageNum = pageNum; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public String getDataSourceCode() { + + return dataSourceCode; + } + + public void setDataSourceCode(String dataSourceCode) { + this.dataSourceCode = dataSourceCode; + } + + public BaseEntity() { + this.dataSourceCode = "master"; + } + +} diff --git a/common/src/main/java/com/hzya/frame/web/entity/BaseResult.java b/common/src/main/java/com/hzya/frame/web/entity/BaseResult.java new file mode 100644 index 00000000..cbf18815 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/entity/BaseResult.java @@ -0,0 +1,117 @@ +package com.hzya.frame.web.entity; + +import com.alibaba.fastjson.JSON; + +/** + * @Content定义全局 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 9:54 + * @Version 1.0 + */ +public class BaseResult { + + /** + * 请求失败 + * + * @param message 提示信息 + * @return + */ + public static JsonResultEntity getFailureMessageEntity(String message) { + return new JsonResultEntity(message, false,"500"); + } + /** + * 请求失败 + * + * @param message 提示信息 + * @return + */ + public static JsonResultEntity getFailureMessageEntity(String message, Object mo) { + return new JsonResultEntity(message,false,"500", mo); + } + /*** + * @Content:请求失败 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 11:00 + * @Param [message, type, status, mo] + * @return com.hzya.frame.web.entity.JsonResultEntity + **/ + public static JsonResultEntity getFailureMessageEntity(String message, String status) { + return new JsonResultEntity(message, false, status); + } + /*** + * @Content:请求失败 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 11:00 + * @Param [message, type, status, mo] + * @return com.hzya.frame.web.entity.JsonResultEntity + **/ + public static JsonResultEntity getFailureMessageEntity(String message, String status,Object mo) { + return new JsonResultEntity(message, false, status,mo); + } + + + /** + * 请求成功 + * + * @param message 提示消息 + * @return + */ + public static JsonResultEntity getSuccessMessageEntity(String message) { + return new JsonResultEntity(message,true,"200"); + } + /** + * 请求成功 + * + * @param type 类型 + * @param message 提示消息 + * @param mo 返回对象 + * @return + */ + public static String getSuccessMessageEntityByStringResult(String message, String type, Object mo) { + return JSON.toJSONString(new JsonResultEntity(message, true,type, mo)); + } + + /** + * 请求成功 + * + * @param message 提示消息 + * @return + */ + public static String getSuccessMessageEntityByStringResult(String message) { + return JSON.toJSONString( new JsonResultEntity( message,true)); + } + + /**** + * @Content: 返回失败结果,返回的是字符串格式 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2020-11-23 18:41 + * @Param [message, type] + * @return java.lang.String + **/ + public static String getFailureMessageEntityByString(String message) { + return JSON.toJSONString(new JsonResultEntity( message,false)); + } + /** + * 请求失败 + * + * @param type 类型 + * @param message 提示信息 + * @return + */ + public static String getFailureMessageEntityByString(String message, String type, Object mo) { + return JSON.toJSONString(new JsonResultEntity(message,false , type, mo)); + } + + /** + * 请求成功 + * @return + */ + public static JsonResultEntity getSuccessMessageEntity(Object obj) { + return new JsonResultEntity("成功",true,"200" ,obj); + } + public static JsonResultEntity getSuccessMessageEntity(String message, Object mo) { + return new JsonResultEntity(message,true,"200" ,mo); + } + + +} diff --git a/common/src/main/java/com/hzya/frame/web/entity/JsonResultEntity.java b/common/src/main/java/com/hzya/frame/web/entity/JsonResultEntity.java new file mode 100644 index 00000000..d68804ee --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/entity/JsonResultEntity.java @@ -0,0 +1,91 @@ +package com.hzya.frame.web.entity; + +/** + * + * @author 郭军辉 + * + * 2016年12月14日下午5:21:35 + */ +public class JsonResultEntity { + /** 提示信息 */ + private String msg; + /** 返回类型 */ + private String type; + /** 是否成功 true成功 false失败 */ + private boolean flag; + /** 状态码*/ + private String status; + /** request 域放的对象 */ + private Object attribute; + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public boolean isFlag() { + return flag; + } + + public void setFlag(boolean flag) { + this.flag = flag; + } + + public Object getAttribute() { + return attribute; + } + + public void setAttribute(Object attribute) { + this.attribute = attribute; + } + + public JsonResultEntity(String msg, boolean flag, Object attribute) { + super(); + this.msg = msg; + this.flag = flag; + this.attribute = attribute; + } + + public JsonResultEntity(String msg, boolean flag, String status) { + this.msg = msg; + this.flag = flag; + this.status = status; + } + + public JsonResultEntity(String msg, boolean flag, String status, Object attribute) { + this.msg = msg; + this.flag = flag; + this.status = status; + this.attribute = attribute; + } + + public JsonResultEntity(String msg, boolean flag) { + super(); + this.msg = msg; + this.flag = flag; + } + + public JsonResultEntity() { + super(); + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + +} diff --git a/common/src/main/java/com/hzya/frame/web/exception/BaseSystemException.java b/common/src/main/java/com/hzya/frame/web/exception/BaseSystemException.java new file mode 100644 index 00000000..d998737b --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/exception/BaseSystemException.java @@ -0,0 +1,29 @@ +package com.hzya.frame.web.exception; + +/** + * @Auther: xiang2lin + * @Date: 2020/3/24 08:43 + * 异常类,业务代码全部抛出这个异常 + */ +public class BaseSystemException extends RuntimeException { + public BaseSystemException(String message) { + super(message); + } + public BaseSystemException(String message,Exception e) { + super(message,e); + } + + public BaseSystemException(Exception ex) { + super(ex); + } + + public BaseSystemException() { + super(); + } + + public BaseSystemException(Throwable throwable) { + super(throwable); + } + + +} diff --git a/common/src/main/java/com/hzya/frame/web/request/RequestBodyUtils.java b/common/src/main/java/com/hzya/frame/web/request/RequestBodyUtils.java new file mode 100644 index 00000000..f3e79c3c --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/request/RequestBodyUtils.java @@ -0,0 +1,85 @@ +package com.hzya.frame.web.request; + +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.io.*; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 9:29 + * @Version 1.0 + */ +public class RequestBodyUtils { + + private static final int BUFFER_SIZE = 1024 * 8; + + /** + * read string. + * + * @param reader Reader instance. + * @return String. + * @throws IOException + */ + public static String read(Reader reader) throws IOException + { + StringWriter writer = new StringWriter(); + try + { + write(reader, writer); + return writer.getBuffer().toString(); + } + finally{ writer.close(); } + } + /** + * 获取requestBody + */ + public static String getRequestBody() throws IOException { + RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); + ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) attributes; + HttpServletRequest request = servletRequestAttributes.getRequest(); + BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); + //读取输入流的内容转换为String类型IOUtils必须引入org.apache.dubbo.common.utils.IOUtils;包 + String body = RequestBodyUtils.read(reader); + return body; + } + + /** + * write. + * + * @param reader Reader. + * @param writer Writer. + * @return count. + * @throws IOException + */ + public static long write(Reader reader, Writer writer) throws IOException + { + return write(reader, writer, BUFFER_SIZE); + } + + /** + * write. + * + * @param reader Reader. + * @param writer Writer. + * @param bufferSize buffer size. + * @return count. + * @throws IOException + */ + public static long write(Reader reader, Writer writer, int bufferSize) throws IOException + { + int read; + long total = 0; + char[] buf = new char[BUFFER_SIZE]; + while( ( read = reader.read(buf) ) != -1 ) + { + writer.write(buf, 0, read); + total += read; + } + return total; + } + +} diff --git a/common/src/main/java/com/hzya/frame/web/transactiontemplate/DataSourceTransactionManagerUtil.java b/common/src/main/java/com/hzya/frame/web/transactiontemplate/DataSourceTransactionManagerUtil.java new file mode 100644 index 00000000..dc4f6f60 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/transactiontemplate/DataSourceTransactionManagerUtil.java @@ -0,0 +1,50 @@ +package com.hzya.frame.web.transactiontemplate; + +import com.hzya.frame.datasource.DataSourceUtil; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.DefaultTransactionDefinition; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-15 10:22 + * @Version 1.0 + */ +public class DataSourceTransactionManagerUtil { + + private static DataSourceTransactionManager dataSourceTransactionManager; + private static DefaultTransactionDefinition txDefinition; + + //public static TransactionStatus defaultBegin() { + // dataSourceTransactionManager = DataSourceUtil.getDataSourceTransactionMaManager("default_db"); + // txDefinition = new DefaultTransactionDefinition(); + // // 如果当前没有事物,则新建一个事物;如果已经存在一个事物,则加入到这个事物中。 + // txDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + // TransactionStatus transaction = dataSourceTransactionManager.getTransaction(txDefinition); + // return transaction; + //} + + // 开启事务 + //public static TransactionStatus begin(String dataSourceKey) { + // dataSourceTransactionManager = DataSourceUtil.getDataSourceTransactionMaManager(dataSourceKey); + // txDefinition = new DefaultTransactionDefinition(); + // // 如果当前没有事物,则新建一个事物;如果已经存在一个事物,则加入到这个事物中。 + // txDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + // TransactionStatus transaction = dataSourceTransactionManager.getTransaction(txDefinition); + // return transaction; + //} + + // 提交事务 + //public static void commit(TransactionStatus transactionStatus) { + // dataSourceTransactionManager.commit(transactionStatus); + //} + + // 回滚事务 + //public static void rollback(TransactionStatus transactionStatus) { + // dataSourceTransactionManager.rollback(transactionStatus); + //} + +} diff --git a/common/src/main/java/com/hzya/frame/web/transactiontemplate/TransactionUtils.java b/common/src/main/java/com/hzya/frame/web/transactiontemplate/TransactionUtils.java new file mode 100644 index 00000000..a1ae08d7 --- /dev/null +++ b/common/src/main/java/com/hzya/frame/web/transactiontemplate/TransactionUtils.java @@ -0,0 +1,24 @@ +package com.hzya.frame.web.transactiontemplate; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-15 8:55 + * @Version 1.0 + */ + +import org.springframework.stereotype.Component; + +/*** + * @Content: + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-15 10:31 + * @Param + * @return + **/ +@Component +public class TransactionUtils { + + +} + diff --git a/common/src/test/java/Test.java b/common/src/test/java/Test.java new file mode 100644 index 00000000..0e7d759f --- /dev/null +++ b/common/src/test/java/Test.java @@ -0,0 +1,8 @@ +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2023-07-18 13:57 + * @Version 1.0 + */ +public class Test { +} diff --git a/core/pom.xml b/core/pom.xml new file mode 100644 index 00000000..bca91dfa --- /dev/null +++ b/core/pom.xml @@ -0,0 +1,40 @@ + + + + kangarooDataCenterV3 + com.hzya.frame + ${revision} + + 4.0.0 + core + ${revision} + jar + + + com.hzya.frame + common + ${revision} + + + + + + org.springframework.boot + spring-boot-maven-plugin + + none + execute + + + + + repackage + + + + + + + diff --git a/core/src/main/java/com/hzya/frame/base/PluginBaseEntity.java b/core/src/main/java/com/hzya/frame/base/PluginBaseEntity.java new file mode 100644 index 00000000..7593d6fa --- /dev/null +++ b/core/src/main/java/com/hzya/frame/base/PluginBaseEntity.java @@ -0,0 +1,11 @@ +package com.hzya.frame.base; + +/** + * @Content定义插件基类 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2023-08-02 10:28 + * @Version 1.0 + */ +public abstract class PluginBaseEntity implements SystemPluginInitializer { + +} diff --git a/core/src/main/java/com/hzya/frame/base/PluginBaseEntityVo.java b/core/src/main/java/com/hzya/frame/base/PluginBaseEntityVo.java new file mode 100644 index 00000000..7f394806 --- /dev/null +++ b/core/src/main/java/com/hzya/frame/base/PluginBaseEntityVo.java @@ -0,0 +1,47 @@ +package com.hzya.frame.base; + +/** + * @Content定义插件基类 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2023-08-02 10:28 + * @Version 1.0 + */ +public class PluginBaseEntityVo { + + private String pluginType; + private String pluginName; + private String pluginId; + private String pluginLabel; + + public String getPluginType() { + return pluginType; + } + + public void setPluginType(String pluginType) { + this.pluginType = pluginType; + } + + public String getPluginName() { + return pluginName; + } + + public void setPluginName(String pluginName) { + this.pluginName = pluginName; + } + + public String getPluginId() { + return pluginId; + } + + public void setPluginId(String pluginId) { + this.pluginId = pluginId; + } + + public String getPluginLabel() { + return pluginLabel; + } + + public void setPluginLabel(String pluginLabel) { + this.pluginLabel = pluginLabel; + } +} diff --git a/core/src/main/java/com/hzya/frame/base/SystemPluginInitializer.java b/core/src/main/java/com/hzya/frame/base/SystemPluginInitializer.java new file mode 100644 index 00000000..49018944 --- /dev/null +++ b/core/src/main/java/com/hzya/frame/base/SystemPluginInitializer.java @@ -0,0 +1,74 @@ +package com.hzya.frame.base; + +import com.alibaba.fastjson.JSONObject; + +/** + * @Content插件基类接口 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2023-08-02 10:48 + * @Version 1.0 + */ +public interface SystemPluginInitializer { + /*** + * 插件初始化方法 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-08-02 10:48 + * @Param [] + * @return void + **/ + void initialize(); + + /**** + * 插件销毁方法 + * @author 👻👻👻👻👻👻👻👻 gjh + * @date 2023-08-02 10:48 + * @param + * @return void + **/ + void destroy(); + + /**** + * 插件的ID + * @author 👻👻👻👻👻👻👻👻 gjh + * @date 2023-08-02 10:48 + * @param + * @return void + **/ + String getPluginId(); + + /**** + * 插件的名称 + * @author 👻👻👻👻👻👻👻👻 gjh + * @date 2023-08-02 10:48 + * @param + * @return void + **/ + String getPluginName(); + + /**** + * 插件的显示值 + * @author 👻👻👻👻👻👻👻👻 gjh + * @date 2023-08-02 10:48 + * @param + * @return void + **/ + String getPluginLabel(); + + /*** + * 插件类型 1、场景插件 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-08-02 14:01 + * @Param [] + * @return java.lang.String + **/ + String getPluginType(); + + /*** + * 执行业务代码 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-08-07 11:20 + * @param requestJson 执行业务代码的参数 + * @return void + **/ + String executeBusiness(JSONObject requestJson) throws Exception; +} diff --git a/core/src/main/java/com/hzya/frame/fileutil/ConstantClassField.java b/core/src/main/java/com/hzya/frame/fileutil/ConstantClassField.java new file mode 100644 index 00000000..8d91d800 --- /dev/null +++ b/core/src/main/java/com/hzya/frame/fileutil/ConstantClassField.java @@ -0,0 +1,14 @@ +package com.hzya.frame.fileutil; + +/** + * @Content 定义针对文件的常量类 + * @Author gjh + * @Date 2019/3/14 16:11 + * @Version 1.0 + */ +public class ConstantClassField { + + //public static final String DSK = "/Users/apple/myself/file"; + public static final String DSK = "/home/webservice/zt/file"; + +} diff --git a/core/src/main/java/com/hzya/frame/fileutil/FileUtils.java b/core/src/main/java/com/hzya/frame/fileutil/FileUtils.java new file mode 100644 index 00000000..16c0a25d --- /dev/null +++ b/core/src/main/java/com/hzya/frame/fileutil/FileUtils.java @@ -0,0 +1,130 @@ +package com.hzya.frame.fileutil; + +import java.io.File; +import java.io.IOException; + +/** + * @Content 针对文件,和文件夹的工具类 + * @Author gjh + * @Date 2019/3/14 16:11 + * @Version 1.0 + */ +public class FileUtils { + + /** + * 判断目录是否存在,如果不存在,直接创建,如果存在,删了在创建 + * + * @param destDirName + * @return + */ + public static boolean createDir(String destDirName) { + File dir = new File(destDirName); + + if (!dir.exists()) { + /*** 创建目录 */ + dir.mkdirs(); + } + return false; + + } + + /*** + * 创建文件 + * @param destFileName 文件名称 + * @return + */ + public static boolean createFile(String destFileName) { + File file = new File(destFileName); + if (file.exists()) { + System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!"); + return false; + } + if (destFileName.endsWith(File.separator)) { + System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!"); + return false; + } + // 判断目标文件所在的目录是否存在 + if (!file.getParentFile().exists()) { + // 如果目标文件所在的目录不存在,则创建父目录 + System.out.println("目标文件所在目录不存在,准备创建它!"); + if (!file.getParentFile().mkdirs()) { + System.out.println("创建目标文件所在目录失败!"); + return false; + } + } + // 创建目标文件 + try { + if (file.createNewFile()) { + System.out.println("创建单个文件" + destFileName + "成功!"); + return true; + } else { + System.out.println("创建单个文件" + destFileName + "失败!"); + return false; + } + } catch (IOException e) { + e.printStackTrace(); + System.out.println("创建单个文件" + destFileName + "失败!" + e.getMessage()); + return false; + } + + } + + /** + * 递归删除目录下的所有文件及子目录下所有文件 + * + * @param dir 将要删除的文件目录 + * @return boolean Returns "true" if all deletions were successful. + * If a deletion fails, the method stops attempting to + * delete and returns "false". + */ + private static boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + //递归删除目录中的子目录下 + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(dir, children[i])); + if (!success) { + return false; + } + } + } + // 目录此时为空,可以删除 + return dir.delete(); + } + + + /** + * 删除单个文件 + * + * @param filePath 文件路径 + * @return 单个文件删除成功返回true,否则返回false + */ + public static boolean deleteFile(String filePath) { + File file = new File(filePath); + // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除 + return deleteFile(file); + } + + /** + * 删除单个文件 + * + * @param file 直接删除文件 + * @return 单个文件删除成功返回true,否则返回false + */ + public static boolean deleteFileByFile(File file) { + // 如果文件路径所对应的文件存在,并且是一个文件,则直接删除 + return deleteFile(file); + } + + private static boolean deleteFile(File file) { + if (file.exists() && file.isFile()) { + if (file.delete()) { + return true; + } else { + return false; + } + } else { + return false; + } + } +} diff --git a/core/src/main/java/com/hzya/frame/fileutil/ZipUtils.java b/core/src/main/java/com/hzya/frame/fileutil/ZipUtils.java new file mode 100644 index 00000000..21af4f1b --- /dev/null +++ b/core/src/main/java/com/hzya/frame/fileutil/ZipUtils.java @@ -0,0 +1,93 @@ +package com.hzya.frame.fileutil; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * @Content + * @Author gjh + * @Date 2019/3/21 14:29 + * @Version 1.0 + */ +public class ZipUtils { + + + private ZipUtils() { + } + + public static void doCompress(String srcFile, String zipFile) throws IOException { + doCompress(new File(srcFile), new File(zipFile)); + } + + /** + * 文件压缩 + * + * @param srcFile 目录或者单个文件 + * @param zipFile 压缩后的ZIP文件 + */ + public static void doCompress(File srcFile, File zipFile) throws IOException { + ZipOutputStream out = null; + try { + out = new ZipOutputStream(new FileOutputStream(zipFile)); + doCompress(srcFile, out); + } catch (Exception e) { + throw e; + } finally { + out.close();//记得关闭资源 + } + } + + public static void doCompress(String filelName, ZipOutputStream out) throws IOException { + doCompress(new File(filelName), out); + } + + public static void doCompress(File file, ZipOutputStream out) throws IOException { + doCompress(file, out, ""); + } + + public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException { + if (inFile.isDirectory()) { + File[] files = inFile.listFiles(); + if (files != null && files.length > 0) { + for (File file : files) { + String name = inFile.getName(); + if (!"".equals(dir)) { + name = dir + "/" + name; + } + ZipUtils.doCompress(file, out, name); + } + } + } else { + ZipUtils.doZip(inFile, out, dir); + } + } + + public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException { + String entryName = null; + if (!"".equals(dir)) { + entryName = dir + "/" + inFile.getName(); + } else { + entryName = inFile.getName(); + } + ZipEntry entry = new ZipEntry(entryName); + out.putNextEntry(entry); + + int len = 0; + byte[] buffer = new byte[1024]; + FileInputStream fis = new FileInputStream(inFile); + while ((len = fis.read(buffer)) > 0) { + out.write(buffer, 0, len); + out.flush(); + } + out.closeEntry(); + fis.close(); + } + + public static void main(String[] args) throws IOException { + doCompress("D:/java/", "D:/java.zip"); + } +} diff --git a/core/src/main/java/com/hzya/frame/util/PluginUtils.java b/core/src/main/java/com/hzya/frame/util/PluginUtils.java new file mode 100644 index 00000000..33b0e058 --- /dev/null +++ b/core/src/main/java/com/hzya/frame/util/PluginUtils.java @@ -0,0 +1,58 @@ +package com.hzya.frame.util; + +import com.hzya.frame.base.PluginBaseEntity; +import com.hzya.frame.web.action.ApplicationContextUtil; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 框架外接插件工具类 + * + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2023-08-02 11:37 + * @Version 1.0 + */ +public class PluginUtils { + private static List pluginBeansList; + + static { + if (pluginBeansList == null) { + pluginBeansList = getPlugins(); + } + } + + public static List getPlugins() { + Map beans = ApplicationContextUtil.getBeansOfType(PluginBaseEntity.class); + List> list = new ArrayList<>(beans.entrySet()); + List list1 = new ArrayList(); + Iterator> in = list.iterator(); + while (in.hasNext()) { + Map.Entry entityEntry = in.next(); + list1.add(entityEntry.getValue()); + } + return list1; + } + + public static List getPluginsByType(String type) { + + List pluginBaseEntityList = pluginBeansList.stream().filter(pl -> type.equalsIgnoreCase(pl.getPluginType())).collect(Collectors.toList()); + return pluginBaseEntityList; + } + + public static PluginBaseEntity getPluginsById(String pluginId) { + PluginBaseEntity pluginBaseEntity = null; + if (pluginId != null && !"".equals(pluginId)) { + for (int i = 0; i < pluginBeansList.size(); i++) { + if (pluginId.equals(pluginBeansList.get(i).getPluginId())) { + pluginBaseEntity = pluginBeansList.get(i); + } + } + } + + return pluginBaseEntity; + } +} diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..50f68190 --- /dev/null +++ b/pom.xml @@ -0,0 +1,404 @@ + + + + buildpackage + service + common + webapp + core + + com.hzya.frame + kangarooDataCenterV3 + kangarooDataCenterV3 + ${revision} + kangarooDataCenterV3 + 4.0.0 + pom + + 0.0.1-SNAPSHOT + UTF-8 + UTF-8 + 1.8 + 1.8 + 4.12 + 2.0.33 + 2.7.4 + 2.7.4 + 3.9.1 + 2.8.5 + 3.3.0 + 5.8.19 + 1.1.22 + 2.2.2 + + 5.1.49 + 1.4.6 + 2.7.4 + 1.30.0 + 3.13.0 + 2.6 + 2.6 + 1.9.4 + 2.6.0 + 1.30.0 + 1.30.0 + 32.0.1-jre + 1.18.22 + 1.3.1 + 2.0.20 + 4.5.13 + 6.1.0.jre8 + 11.2.0.4 + 3.5.2 + 1.2.18 + 2.7.4 + 2.7.4 + 2.7.4 + 4.12 + 2.3.0 + 5.3.23 + + + + org.springframework.boot + spring-boot-starter-parent + 2.7.4 + + + + + + + + + + + + + + + + + net.sourceforge.jtds + jtds + ${net.sourceforge.jtds.version} + + + org.springframework.boot + spring-boot-starter-aop + ${spring-boot-starter-aop.version} + + + + + org.apache.httpcomponents + httpclient + ${httpclient.version} + + + org.springframework.boot + spring-boot-starter-cache + ${spring-boot-starter-cache.version} + + + org.springframework.boot + spring-boot-starter-test + ${spring-boot-starter-test.version} + + + org.springframework + spring-core + + + + + junit + junit + ${unit.version} + + + + com.alibaba + fastjson + ${fastjson.version} + + + + + p6spy + p6spy + ${p6spy.version} + + + + com.google.code.gson + gson + ${gson.version} + + + com.google.zxing + core + ${zxing.version} + + + + com.google.guava + guava + ${guava.version} + + + + org.mybatis.spring.boot + mybatis-spring-boot-starter + ${mybatis-spring-boot-starter.version} + + + org.springframework.boot + spring-boot-autoconfigure + + + org.springframework.boot + spring-boot-starter + + + + + + + mysql + mysql-connector-java + ${mysql-connector-java} + + + + com.github.pagehelper + pagehelper-spring-boot-starter + ${pagehelper-spring-boot-starter.version} + + + mybatis + org.mybatis + + + org.springframework.boot + spring-boot-autoconfigure + + + org.springframework.boot + spring-boot-starter + + + + + + cn.hutool + hutool-all + ${hutool.version} + + + + cn.dev33 + sa-token-spring-boot-starter + ${sa.token.version} + + + cn.dev33 + sa-token-oauth2 + ${sa-token-oauth2.version} + + + cn.dev33 + sa-token-jwt + ${sa-token-jwt.version} + + + + com.baomidou + dynamic-datasource-spring-boot-starter + ${dynamic-datasource-spring-boot-starter.version} + + + + com.alibaba + druid-spring-boot-starter + ${druid-spring-boot-starter.version} + + + org.springframework.boot + spring-boot-autoconfigure + + + + + + + com.dameng + Dm8JdbcDriver18 + 8.1.1.49 + + + + + commons-beanutils + commons-beanutils + ${beanutils.version} + + + org.apache.commons + commons-pool2 + ${commons.pool2.version} + + + + org.apache.commons + commons-lang3 + ${lang3.version} + + + + org.projectlombok + lombok + ${lombok.version} + true + + + + + + + + + + + + + + + + + + + + + + + org.apache.pdfbox + pdfbox + ${pdfbox.version} + + + + + + + + + com.oracle.database.jdbc + ojdbc6 + ${ojdbc6.version} + + + + org.quartz-scheduler + quartz + ${quartz.version} + + + org.springframework + spring-context-support + ${org.springframework.version} + + + commons-io + commons-io + ${commons.io.version} + + + dom4j + dom4j + 1.6.1 + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + 2.6 + + UTF-8 + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.10.1 + + 1.8 + 1.8 + UTF-8 + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.7.4 + + ${project.artifactId} + none + execute + + + + + + + + src/main/java + + **/*.xml + + + + src/main/resources + + **/*.properties + **/*.xml + **/*.xmreport + **/*.xlsx + **/*.json + **/*.xdb + + + + + + src/ + + **/*.properties + **/*.xml + **/*.json + + true + + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/libs-milestone + + false + + + + + + diff --git a/service/pom.xml b/service/pom.xml new file mode 100644 index 00000000..4f1692fd --- /dev/null +++ b/service/pom.xml @@ -0,0 +1,44 @@ + + + + kangarooDataCenterV3 + com.hzya.frame + ${revision} + + 4.0.0 + service + jar + + + com.hzya.frame + core + ${revision} + + + mysql + mysql-connector-java + ${mysql-connector-java} + + + + + + org.springframework.boot + spring-boot-maven-plugin + + none + execute + + + + + repackage + + + + + + + diff --git a/service/src/main/java/com/hzya/frame/serviceUtil/DsDataSourceUtil.java b/service/src/main/java/com/hzya/frame/serviceUtil/DsDataSourceUtil.java new file mode 100644 index 00000000..ff97fdf4 --- /dev/null +++ b/service/src/main/java/com/hzya/frame/serviceUtil/DsDataSourceUtil.java @@ -0,0 +1,143 @@ +package com.hzya.frame.serviceUtil; + +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; +import com.baomidou.dynamic.datasource.exception.CannotFindDataSourceException; +import com.hzya.frame.datasource.DataSourceUtilProperties; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DriverManager; + + +@Component +public class DsDataSourceUtil { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Resource + private DataSource dataSource; + + public void addDataSource(SysDataSourceEntity sysDataSourceVo) throws Exception { + DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource; + JSONObject defaultDataSourceProperties = new JSONObject(); + defaultDataSourceProperties.put("datasource_code", sysDataSourceVo.getSourceCode()); + defaultDataSourceProperties.put("source_url", sysDataSourceVo.getSourceUrl()); + defaultDataSourceProperties.put("source_type", sysDataSourceVo.getSourceTypeName()); + defaultDataSourceProperties.put("login_name", sysDataSourceVo.getLoginName()); + defaultDataSourceProperties.put("password", sysDataSourceVo.getPassword()); + defaultDataSourceProperties.put("db_name", sysDataSourceVo.getDbName()); + logger.info("***初始化数据源-{}:*********", sysDataSourceVo.getSourceName()); + DruidDataSource dataSource = createDefaultDataSource(defaultDataSourceProperties); + ds.addDataSource(sysDataSourceVo.getSourceCode(), dataSource); + logger.info("***初始化数据源-{}成功:*********", sysDataSourceVo.getSourceName()); + } + + /** + * @param code + * @return boolean + * @Author lvleigang + * @Description 删除数据源 + * @Date 11:40 上午 2023/9/6 + **/ + public void removeDataSource(String code) { + DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource; + try { + DataSource dataSource = ds.getDataSource(code); + ds.removeDataSource(code); + } catch (CannotFindDataSourceException var4) { + logger.info("***初始化数据源-{}不存在不需要删除:*********", code); + } + } + + /** + * @param sysDataSourceVo + * @return boolean + * @Author lvleigang + * @Description 修改数据源 + * @Date 11:40 上午 2023/9/6 + **/ + public void editDataSource(SysDataSourceEntity sysDataSourceVo) throws Exception { + //先删除后添加 + removeDataSource(sysDataSourceVo.getSourceCode()); + addDataSource(sysDataSourceVo); + } + + + /**** + * @Content:创建数据源,返回DruidDataSource + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-06-14 9:11 + * @Param [defaultDataSourceProperties] + * @return com.alibaba.druid.pool.DruidDataSource + **/ + private DruidDataSource createDefaultDataSource(JSONObject defaultDataSourceProperties) throws RuntimeException { + //根据datasource_code查询数据源配置信息 + String datasource_code = String.valueOf(defaultDataSourceProperties.get("datasource_code")); + String source_url = String.valueOf(defaultDataSourceProperties.get("source_url")); + String login_name = String.valueOf(defaultDataSourceProperties.get("login_name")); + String password = String.valueOf(defaultDataSourceProperties.get("password")); + String db_name = String.valueOf(defaultDataSourceProperties.get("db_name")); + String source_type = String.valueOf(defaultDataSourceProperties.get("source_type")); + if (defaultDataSourceProperties != null) { + String driveClass = ""; + if ("mysql".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.MYSQLDRIVER_6; + } else if ("oracle".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.ORACLEDRIVER; + } else if ("sqlserver2000".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.SQL2000DRIVER; + } else if ("sqlServer".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.SQL2005DRIVER; + } + try { + //测试连接 + Class.forName(driveClass); + Connection connection = DriverManager.getConnection(source_url, login_name, password);// 相当于连接数据库 + if (connection != null) { + //初始化数据源信息 + DruidDataSource druidDataSource = new DruidDataSource(); + druidDataSource.setUrl(source_url); + druidDataSource.setUsername(login_name); + druidDataSource.setPassword(password); + druidDataSource.setName(db_name); + druidDataSource.setDriverClassName(driveClass); + druidDataSource.setInitialSize(5); + druidDataSource.setMinIdle(5); + druidDataSource.setMaxActive(100); + druidDataSource.setMaxWait(60000); + druidDataSource.setTimeBetweenEvictionRunsMillis(60000); + druidDataSource.setMinEvictableIdleTimeMillis(300000); + druidDataSource.setMaxEvictableIdleTimeMillis(600000); + if ("oracle".equals(source_type)) { + druidDataSource.setValidationQuery("select 1 from dual"); + } else { + druidDataSource.setValidationQuery("SELECT 1"); + } + druidDataSource.setTestWhileIdle(true); + druidDataSource.setTestOnBorrow(false); + druidDataSource.setTestOnReturn(false); + druidDataSource.setPoolPreparedStatements(true); + druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20); + druidDataSource.setRemoveAbandoned(true); + druidDataSource.setRemoveAbandonedTimeout(999999); + druidDataSource.init(); + return druidDataSource; + } else { + throw new RuntimeException("测试默认数据库连接失败datasource_code:" + datasource_code); + } + } catch (Exception e) { + logger.info("==================创建数据源失败==================="); + throw new RuntimeException("创建数据源失败" + e.getMessage()); + } + + + } else { + throw new RuntimeException("source_code:" + datasource_code + "不存在"); + } + } +} diff --git a/service/src/main/java/com/hzya/frame/serviceUtil/ServiceUtil.java b/service/src/main/java/com/hzya/frame/serviceUtil/ServiceUtil.java new file mode 100644 index 00000000..115ed061 --- /dev/null +++ b/service/src/main/java/com/hzya/frame/serviceUtil/ServiceUtil.java @@ -0,0 +1,76 @@ +package com.hzya.frame.serviceUtil; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.util.List; + + +/** + * @Author lvleigang + * @Description service 工具类 + * @Date 11:36 上午 2023/3/6 + * @return + **/ +public class ServiceUtil { + + /** + * @param key 健 + * @param jsonObject json数据 + * @return java.lang.String + * @Author lvleigang + * @Description 根据key获取数据jsonObject中的数据,如果没有设置默认值 + * @Date 3:41 下午 2023/2/14 + **/ + protected T getData(String key, JSONObject jsonObject, Class clz) { + if (checkStr(jsonObject.getString(key))) { + return jsonObject.getJSONObject(key).toJavaObject(clz); + } + return null; + } + + /** + * @param key + * @param object + * @return com.alibaba.fastjson.JSONObject + * @Author lvleigang + * @Description 获取对象转换成jsonobj + * @Date 11:51 下午 2023/7/10 + **/ + protected JSONObject getstrObj(String key, JSONObject object) { + if (checkStr(object.getString(key))) { + return object.getJSONObject(key); + } + return new JSONObject(); + } + + /** + * @param key 健 + * @param jsonObject json数据 + * @return java.lang.String + * @Author lvleigang + * @Description 根据key获取数据jsonObject中的数据,如果没有设置默认值 + * @Date 3:41 下午 2023/2/14 + **/ + protected List getListData(String key, JSONObject jsonObject, Class clz) { + if (checkStr(jsonObject.getString(key))) { + return JSONArray.parseArray(jsonObject.getString(key), clz); + } + return null; + } + + /** + * @param str + * @return void + * @Author lvleigang + * @Description 校验字符串 + * @Date 11:41 上午 2022/12/7 + **/ + protected Boolean checkStr(String str) { + Boolean flag = true; + if (str == null || "".equals(str)) { + flag = false; + } + return flag; + } +} diff --git a/service/src/main/java/com/hzya/frame/sys/dataSource/dao/ISysDataSourceDao.java b/service/src/main/java/com/hzya/frame/sys/dataSource/dao/ISysDataSourceDao.java new file mode 100644 index 00000000..98096b59 --- /dev/null +++ b/service/src/main/java/com/hzya/frame/sys/dataSource/dao/ISysDataSourceDao.java @@ -0,0 +1,23 @@ +package com.hzya.frame.sys.dataSource.dao; + +import com.hzya.frame.basedao.dao.IBaseDao; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceEntity; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceVo; + +import java.util.List; + +/** + * 数据源表(sys_data_source: table)表数据库访问层 + * + * @author makejava + * @since 2023-09-05 16:07:01 + */ +public interface ISysDataSourceDao extends IBaseDao { + + List queryVoList(SysDataSourceEntity entity); + + int queryVoList_COUNT(SysDataSourceEntity entity); + + Integer entity_count_not_id(SysDataSourceEntity checkEntity); +} + diff --git a/service/src/main/java/com/hzya/frame/sys/dataSource/dao/impl/SysDataSourceDaoImpl.java b/service/src/main/java/com/hzya/frame/sys/dataSource/dao/impl/SysDataSourceDaoImpl.java new file mode 100644 index 00000000..c0705220 --- /dev/null +++ b/service/src/main/java/com/hzya/frame/sys/dataSource/dao/impl/SysDataSourceDaoImpl.java @@ -0,0 +1,41 @@ +package com.hzya.frame.sys.dataSource.dao.impl; + +import com.baomidou.dynamic.datasource.annotation.DS; +import com.hzya.frame.basedao.dao.MybatisGenericDao; +import com.hzya.frame.sys.dataSource.dao.ISysDataSourceDao; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceEntity; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceVo; +import org.springframework.stereotype.Repository; + +import java.util.List; + +/** + * 数据源表(SysDataSource)表数据库访问层 + * + * @author makejava + * @since 2023-09-05 16:07:03 + */ +@Repository(value = "SysDataSourceDaoImpl") +public class SysDataSourceDaoImpl extends MybatisGenericDao implements ISysDataSourceDao { + + + @DS("master") + @Override + public List queryVoList(SysDataSourceEntity entity) { + List o = (List) super.selectList(getSqlIdPrifx() + "queryVoList", entity); + return o; + } + + @Override + public int queryVoList_COUNT(SysDataSourceEntity entity) { + int o = (int) super.selectOne(getSqlIdPrifx() + "queryVoList_COUNT", entity); + return o; + } + + @Override + public Integer entity_count_not_id(SysDataSourceEntity entity) { + Integer o = (Integer) super.selectOne(getSqlIdPrifx() + "entity_count_not_id", entity); + return o; + } +} + diff --git a/service/src/main/java/com/hzya/frame/sys/dataSource/entity/SysDataSourceEntity.java b/service/src/main/java/com/hzya/frame/sys/dataSource/entity/SysDataSourceEntity.java new file mode 100644 index 00000000..a85d6d4d --- /dev/null +++ b/service/src/main/java/com/hzya/frame/sys/dataSource/entity/SysDataSourceEntity.java @@ -0,0 +1,177 @@ +package com.hzya.frame.sys.dataSource.entity; + +import com.hzya.frame.web.entity.BaseEntity; + +/** + * 数据源表(SysDataSource)实体类 + * + * @author makejava + * @since 2023-09-05 16:07:06 + */ +public class SysDataSourceEntity extends BaseEntity { + + /** + * 数据源唯一编码 + */ + private String sourceCode; + /** + * 数据源名称 + */ + private String sourceName; + /** + * ip + */ + private String sourceIp; + /** + * 端口 + */ + private String sourcePort; + /** + * 数据库名称 + */ + private String dbName; + /** + * 数据源类型 1oracle 2sqlsever 3mysql + */ + private String sourceType; + /** + * 登录名 + */ + private String loginName; + /** + * 密码 + */ + private String password; + /** + * 选择oracle下服务名称 + */ + private String serviceName; + /** + * 使用状态1启用0锁定 + */ + private Integer useState; + + + public String getSourceCode() { + return sourceCode; + } + + public void setSourceCode(String sourceCode) { + this.sourceCode = sourceCode; + } + + public String getSourceName() { + return sourceName; + } + + public void setSourceName(String sourceName) { + this.sourceName = sourceName; + } + + public String getSourceIp() { + return sourceIp; + } + + public void setSourceIp(String sourceIp) { + this.sourceIp = sourceIp; + } + + public String getSourcePort() { + return sourcePort; + } + + public void setSourcePort(String sourcePort) { + this.sourcePort = sourcePort; + } + + public String getDbName() { + return dbName; + } + + public void setDbName(String dbName) { + this.dbName = dbName; + } + + public String getSourceType() { + return sourceType; + } + + public void setSourceType(String sourceType) { + this.sourceType = sourceType; + } + + public String getLoginName() { + return loginName; + } + + public void setLoginName(String loginName) { + this.loginName = loginName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public Integer getUseState() { + return useState; + } + + public void setUseState(Integer useState) { + this.useState = useState; + } + + public String getSourceUrl() { + StringBuffer sourceUrl = new StringBuffer(); + if (sourceType != null) { + switch (sourceType) { + case "1": //oracle + //jdbc:oracle:thin:@60.204.132.91:1521:ORCL + sourceUrl.append("jdbc:oracle:thin:@").append(sourceIp).append(":").append(sourcePort).append(":").append(serviceName); + break; + case "2": //sqlsever + //jdbc:sqlserver://221.12.175.82:1433;DatabaseName=U8CLOUD;encrypt=false;trustServerCertificate=true + sourceUrl.append("jdbc:sqlserver://").append(sourceIp).append(":").append(sourcePort).append(";DatabaseName=").append(dbName).append(";encrypt=false;trustServerCertificate=true"); + break; + case "3": //mysql + //jdbc:mysql://hzya.ufyct.com:9096/businesscenter?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false + sourceUrl.append("jdbc:mysql://").append(sourceIp).append(":").append(sourcePort).append("/").append(dbName).append("?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false"); + break; + default: + } + } + return sourceUrl.toString(); + } + + public String getSourceTypeName() { + String sourceTypeName = null; + if (sourceType != null) { + switch (sourceType) { + case "1": //oracle + sourceTypeName = "oracle"; + break; + case "2": //sqlsever + sourceTypeName = "sqlServer"; + break; + case "3": //mysql + sourceTypeName = "mysql"; + break; + default: + } + } + + return sourceTypeName; + } +} + diff --git a/service/src/main/java/com/hzya/frame/sys/dataSource/entity/SysDataSourceEntity.xml b/service/src/main/java/com/hzya/frame/sys/dataSource/entity/SysDataSourceEntity.xml new file mode 100644 index 00000000..4d7404d6 --- /dev/null +++ b/service/src/main/java/com/hzya/frame/sys/dataSource/entity/SysDataSourceEntity.xml @@ -0,0 +1,431 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + id + ,source_code + ,source_name + ,source_ip + ,source_port + ,db_name + ,source_type + ,login_name + ,password + ,service_name + ,use_state + ,sorts + ,create_user_id + ,create_time + ,modify_user_id + ,modify_time + ,sts + ,org_id + + + + + + + + + + + + + + + + + + + + + + + + + + + insert into sys_data_source( + + id , + source_code , + source_name , + source_ip , + source_port , + db_name , + source_type , + login_name , + password , + service_name , + use_state , + sorts , + create_user_id , + create_time , + modify_user_id , + modify_time , + sts , + org_id , + sorts, + sts, + + )values( + + #{id} , + #{sourceCode} , + #{sourceName} , + #{sourceIp} , + #{sourcePort} , + #{dbName} , + #{sourceType} , + #{loginName} , + #{password} , + #{serviceName} , + #{useState} , + #{sorts} , + #{create_user_id} , + #{create_time} , + #{modify_user_id} , + #{modify_time} , + #{sts} , + #{org_id} , + (select (max(IFNULL( a.sorts, 0 )) + 1) as sort from sys_data_source a WHERE a.sts + = 'Y' ), + + 'Y', + + ) + + + + insert into sys_data_source(source_code, source_name, source_ip, source_port, db_name, source_type, login_name, + password, service_name, use_state, sorts, create_user_id, create_time, modify_user_id, modify_time, sts, org_id, + sts) + values + + (#{entity.sourceCode},#{entity.sourceName},#{entity.sourceIp},#{entity.sourcePort},#{entity.dbName},#{entity.sourceType},#{entity.loginName},#{entity.password},#{entity.serviceName},#{entity.useState},#{entity.sorts},#{entity.create_user_id},#{entity.create_time},#{entity.modify_user_id},#{entity.modify_time},#{entity.sts},#{entity.org_id}, + 'Y') + + + + + insert into sys_data_source(source_code, source_name, source_ip, source_port, db_name, source_type, login_name, + password, service_name, use_state, sorts, create_user_id, create_time, modify_user_id, modify_time, sts, org_id) + values + + (#{entity.sourceCode},#{entity.sourceName},#{entity.sourceIp},#{entity.sourcePort},#{entity.dbName},#{entity.sourceType},#{entity.loginName},#{entity.password},#{entity.serviceName},#{entity.useState},#{entity.sorts},#{entity.create_user_id},#{entity.create_time},#{entity.modify_user_id},#{entity.modify_time},#{entity.sts},#{entity.org_id}) + + on duplicate key update + source_code = values(source_code), + source_name = values(source_name), + source_ip = values(source_ip), + source_port = values(source_port), + db_name = values(db_name), + source_type = values(source_type), + login_name = values(login_name), + password = values(password), + service_name = values(service_name), + use_state = values(use_state), + sorts = values(sorts), + create_user_id = values(create_user_id), + create_time = values(create_time), + modify_user_id = values(modify_user_id), + modify_time = values(modify_time), + sts = values(sts), + org_id = values(org_id) + + + + update sys_data_source set + + source_code = #{sourceCode}, + source_name = #{sourceName}, + source_ip = #{sourceIp}, + source_port = #{sourcePort}, + db_name = #{dbName}, + source_type = #{sourceType}, + login_name = #{loginName}, + password = #{password}, + service_name = #{serviceName}, + use_state = #{useState}, + sorts = #{sorts}, + create_user_id = #{create_user_id}, + create_time = #{create_time}, + modify_user_id = #{modify_user_id}, + modify_time = #{modify_time}, + sts = #{sts}, + org_id = #{org_id}, + + where id = #{id} + + + +update sys_data_source set sts= 'N' ,modify_time = #{modify_time},modify_user_id = #{modify_user_id} +where id = #{id} + + + + update sys_data_source set sts= 'N' ,modify_time = #{modify_time},modify_user_id = #{modify_user_id} + + and id = #{id} + and source_code = #{sourceCode} + and source_name = #{sourceName} + and source_ip = #{sourceIp} + and source_port = #{sourcePort} + and db_name = #{dbName} + and source_type = #{sourceType} + and login_name = #{loginName} + and password = #{password} + and service_name = #{serviceName} + and use_state = #{useState} + and sorts = #{sorts} + and sts = #{sts} + and sts='Y' + + + + + delete from sys_data_source where id = #{id} + + + + diff --git a/service/src/main/java/com/hzya/frame/sys/dataSource/entity/SysDataSourceVo.java b/service/src/main/java/com/hzya/frame/sys/dataSource/entity/SysDataSourceVo.java new file mode 100644 index 00000000..73d1d6bd --- /dev/null +++ b/service/src/main/java/com/hzya/frame/sys/dataSource/entity/SysDataSourceVo.java @@ -0,0 +1,183 @@ +package com.hzya.frame.sys.dataSource.entity; + + +public class SysDataSourceVo { + + /** + * 主键ID + */ + private String id; + /** + * 数据源编码 + */ + private String sourceCode; + /** + * 数据源名称 + */ + private String sourceName; + /** + * ip + */ + private String sourceIp; + /** + * 端口 + */ + private String sourcePort; + /** + * 数据库名称 + */ + private String dbName; + /** + * 数据源类型 1oracle 2sqlsever 3mysql 4dm + */ + private String sourceType; + /** + * 登录名 + */ + private String loginName; + /** + * 密码 + */ + private String password; + /** + * 选择oracle下服务名称 + */ + private String serviceName; + /** + * 使用状态1启用0锁定 + */ + private Integer useState; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getSourceCode() { + return sourceCode; + } + + public void setSourceCode(String sourceCode) { + this.sourceCode = sourceCode; + } + + public String getSourceName() { + return sourceName; + } + + public void setSourceName(String sourceName) { + this.sourceName = sourceName; + } + + public String getSourceIp() { + return sourceIp; + } + + public void setSourceIp(String sourceIp) { + this.sourceIp = sourceIp; + } + + public String getSourcePort() { + return sourcePort; + } + + public void setSourcePort(String sourcePort) { + this.sourcePort = sourcePort; + } + + public String getDbName() { + return dbName; + } + + public void setDbName(String dbName) { + this.dbName = dbName; + } + + public String getSourceType() { + return sourceType; + } + + public void setSourceType(String sourceType) { + this.sourceType = sourceType; + } + + public String getLoginName() { + return loginName; + } + + public void setLoginName(String loginName) { + this.loginName = loginName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getServiceName() { + return serviceName; + } + + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + public Integer getUseState() { + return useState; + } + + public void setUseState(Integer useState) { + this.useState = useState; + } + + public String getSourceUrl() { + StringBuffer sourceUrl = new StringBuffer(); + switch (sourceType) { + case "1": //oracle + //jdbc:oracle:thin:@60.204.132.91:1521:ORCL + sourceUrl.append("jdbc:oracle:thin:@").append(sourceIp).append(":").append(sourcePort).append(":").append(serviceName); + break; + case "2": //sqlsever + //jdbc:sqlserver://221.12.175.82:1433;DatabaseName=U8CLOUD;encrypt=false;trustServerCertificate=true + sourceUrl.append("jdbc:jtds:sqlserver://").append(sourceIp).append(":").append(sourcePort).append("/").append(dbName).append(";encrypt=false;trustServerCertificate=true"); + break; + case "3": //mysql + //jdbc:mysql://hzya.ufyct.com:9096/businesscenter?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false + sourceUrl.append("jdbc:mysql://").append(sourceIp).append(":").append(sourcePort).append("/").append(dbName).append("?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false"); + break; + case "4": //dm + //jdbc:dm://hzya.ufyct.com:9040?schema=businesscenter&characterEncoding=UTF-8 + sourceUrl.append("jdbc:dm://").append(sourceIp).append(":").append(sourcePort).append("?schema=").append(dbName).append("&characterEncoding=UTF-8"); + break; + default: + } + return sourceUrl.toString(); + } + + public String getSourceTypeName() { + String sourceTypeName = null; + switch (sourceType) { + case "1": //oracle + sourceTypeName = "oracle"; + break; + case "2": //sqlsever + sourceTypeName = "sqlServer"; + break; + case "3": //mysql + sourceTypeName = "mysql"; + break; + case "4": //mysql + sourceTypeName = "dm"; + break; + default: + } + return sourceTypeName; + } +} + diff --git a/service/src/main/java/com/hzya/frame/sys/dataSource/service/ISysDataSourceService.java b/service/src/main/java/com/hzya/frame/sys/dataSource/service/ISysDataSourceService.java new file mode 100644 index 00000000..c7c470db --- /dev/null +++ b/service/src/main/java/com/hzya/frame/sys/dataSource/service/ISysDataSourceService.java @@ -0,0 +1,69 @@ +package com.hzya.frame.sys.dataSource.service; + +import com.alibaba.fastjson.JSONObject; +import com.hzya.frame.basedao.service.IBaseService; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceEntity; +import com.hzya.frame.web.entity.JsonResultEntity; + +/** + * 数据源表(SysDataSource)表服务接口 + * + * @author makejava + * @since 2023-09-05 16:07:10 + */ +public interface ISysDataSourceService extends IBaseService { + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询列表 + * @Date 2:18 下午 2023/7/17 + **/ + JsonResultEntity queryList(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询列表 + * @Date 2:18 下午 2023/7/17 + **/ + JsonResultEntity queryPage(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 获取数据 + * @Date 2:18 下午 2023/7/17 + **/ + JsonResultEntity queryEntity(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 新增数据 + * @Date 2:18 下午 2023/7/17 + **/ + JsonResultEntity addEntity(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 修改数据 + * @Date 2:18 下午 2023/7/17 + **/ + JsonResultEntity editEntity(JSONObject jsonObject); + + /** + * @param jsonObject + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 删除数据 + * @Date 2:18 下午 2023/7/17 + **/ + JsonResultEntity deleteEntity(JSONObject jsonObject); + +} diff --git a/service/src/main/java/com/hzya/frame/sys/dataSource/service/impl/SysDataSourceServiceImpl.java b/service/src/main/java/com/hzya/frame/sys/dataSource/service/impl/SysDataSourceServiceImpl.java new file mode 100644 index 00000000..ddfe8ab3 --- /dev/null +++ b/service/src/main/java/com/hzya/frame/sys/dataSource/service/impl/SysDataSourceServiceImpl.java @@ -0,0 +1,222 @@ +package com.hzya.frame.sys.dataSource.service.impl; + +import cn.dev33.satoken.stp.StpUtil; +import com.alibaba.fastjson.JSONObject; +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.hzya.frame.basedao.service.impl.BaseService; +import com.hzya.frame.serviceUtil.DsDataSourceUtil; +import com.hzya.frame.sys.dataSource.dao.ISysDataSourceDao; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceEntity; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceVo; +import com.hzya.frame.sys.dataSource.service.ISysDataSourceService; +import com.hzya.frame.uuid.UUIDUtils; +import com.hzya.frame.web.entity.BaseResult; +import com.hzya.frame.web.entity.JsonResultEntity; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.util.Date; +import java.util.List; + +/** + * 数据源表(SysDataSource)表服务实现类 + * + * @author makejava + * @since 2023-09-05 16:07:13 + */ +@Service(value = "sysDataSourceService") +public class SysDataSourceServiceImpl extends BaseService implements ISysDataSourceService { + + private ISysDataSourceDao sysDataSourceDao; + @Resource + private DsDataSourceUtil dsDataSourceUtil; + + @Autowired + public void setSysDataSourceDao(ISysDataSourceDao dao) { + this.sysDataSourceDao = dao; + this.dao = dao; + } + + /** + * @param object + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询列表 + * @Date 2:18 下午 2023/7/17 + **/ + @Override + public JsonResultEntity queryList(JSONObject object) { + SysDataSourceEntity entity = getData("jsonStr", object, SysDataSourceEntity.class); + List sysDataSourceEntities = sysDataSourceDao.queryVoList(entity); + return BaseResult.getSuccessMessageEntity("查询数据成功", sysDataSourceEntities); + } + + /** + * @param object + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 查询列表 + * @Date 2:18 下午 2023/7/17 + **/ + @Override + public JsonResultEntity queryPage(JSONObject object) { + SysDataSourceEntity entity = getData("jsonStr", object, SysDataSourceEntity.class); + //判断分页 + if (entity == null || entity.getPageNum() == null || entity.getPageSize() == null) { + return BaseResult.getFailureMessageEntity("分页查询参数不存在"); + } + PageHelper.startPage(entity.getPageNum(), entity.getPageSize()); + List sysDataSourceEntities = sysDataSourceDao.queryVoList(entity); + PageInfo pageInfo = new PageInfo(sysDataSourceEntities); + return BaseResult.getSuccessMessageEntity("查询数据成功", pageInfo); + } + + /** + * @param object + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 获取数据 + * @Date 2:18 下午 2023/7/17 + **/ + @Override + public JsonResultEntity queryEntity(JSONObject object) { + SysDataSourceEntity entity = getData("jsonStr", object, SysDataSourceEntity.class); + //判断分页 + if (entity == null || entity.getId() == null || "".equals(entity.getId())) { + return BaseResult.getFailureMessageEntity("请先传递请求主键"); + } + SysDataSourceEntity sysDataSourceEntity = sysDataSourceDao.queryOne(entity); + return BaseResult.getSuccessMessageEntity("查询数据成功", sysDataSourceEntity); + } + + /** + * @param object + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 新增数据 + * @Date 2:18 下午 2023/7/17 + **/ + @Override + public JsonResultEntity addEntity(JSONObject object) { + SysDataSourceEntity entity = getData("jsonStr", object, SysDataSourceEntity.class); + if (entity == null) { + return BaseResult.getFailureMessageEntity("参数不允许为空"); + } + if (entity.getSourceName() == null || "".equals(entity.getSourceName())) { + return BaseResult.getFailureMessageEntity("请先输入数据源名称"); + } + if (entity.getSourceCode() == null || "".equals(entity.getSourceCode())) { + return BaseResult.getFailureMessageEntity("请先输入数据源编码"); + } + SysDataSourceEntity checkEntity = new SysDataSourceEntity(); + checkEntity.setSts("Y"); + checkEntity.setSourceCode(entity.getSourceCode()); + int checkCount = sysDataSourceDao.getCount(checkEntity); + if (checkCount > 0) { + return BaseResult.getFailureMessageEntity("数据源编码已存在"); + } + setCreate(entity); + if (entity.getUseState() == 1) { + try { + dsDataSourceUtil.addDataSource(entity); + } catch (Exception e) { + return BaseResult.getFailureMessageEntity("初始化数据源失败,请检查数据源配置是否正确"); + } + } + sysDataSourceDao.save(entity); + return BaseResult.getSuccessMessageEntity("保存数据源成功", entity.getId()); + } + + private void setCreate(SysDataSourceEntity entity) { + entity.setId(UUIDUtils.getUUID()); + entity.setSts("Y"); + entity.setCreate_user_id(StpUtil.getLoginIdAsString()); + entity.setModify_user_id(StpUtil.getLoginIdAsString()); + entity.setCreate_time(new Date()); + entity.setModify_time(new Date()); + } + + /** + * @param object + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 修改数据 + * @Date 2:18 下午 2023/7/17 + **/ + @Override + public JsonResultEntity editEntity(JSONObject object) { + SysDataSourceEntity entity = getData("jsonStr", object, SysDataSourceEntity.class); + if (entity == null) { + return BaseResult.getFailureMessageEntity("参数不允许为空"); + } + if (entity.getId() == null || "".equals(entity.getId())) { + return BaseResult.getFailureMessageEntity("系统错误"); + } + if (entity.getSourceName() == null || "".equals(entity.getSourceName())) { + return BaseResult.getFailureMessageEntity("请先输入数据源名称"); + } + if (entity.getSourceCode() == null || "".equals(entity.getSourceCode())) { + return BaseResult.getFailureMessageEntity("请先输入数据源编码"); + } + SysDataSourceEntity checkEntity = new SysDataSourceEntity(); + checkEntity.setSts("Y"); + checkEntity.setId(entity.getId()); + checkEntity.setSourceCode(entity.getSourceCode()); + int checkCount = sysDataSourceDao.entity_count_not_id(checkEntity); + if (checkCount > 0) { + return BaseResult.getFailureMessageEntity("接口编码已存在"); + } + entity.setModify_user_id(StpUtil.getLoginIdAsString()); + entity.setModify_time(new Date()); + entity.setSts("Y"); + if (entity.getUseState() == 1) { + try { + dsDataSourceUtil.editDataSource(entity); + } catch (Exception e) { + return BaseResult.getSuccessMessageEntity("修改数据源失败,请检查数据源配置是否正确"); + } + } else { + try { + dsDataSourceUtil.removeDataSource(entity.getSourceCode()); + } catch (Exception e) { + return BaseResult.getSuccessMessageEntity("修改数据源失败"); + } + } + sysDataSourceDao.update(entity); + return BaseResult.getSuccessMessageEntity("修改数据源成功", entity.getId()); + + } + + /** + * @param object + * @return com.hzya.frame.web.entity.JsonResultEntity + * @Author lvleigang + * @Description 删除数据 + * @Date 2:18 下午 2023/7/17 + **/ + @Override + public JsonResultEntity deleteEntity(JSONObject object) { + SysDataSourceEntity entity = getData("jsonStr", object, SysDataSourceEntity.class); + //判断编码是否重复 + if (entity == null) { + return BaseResult.getFailureMessageEntity("请先填写内容"); + } + if (entity.getId() == null || "".equals(entity.getId())) { + return BaseResult.getFailureMessageEntity("请先选择数据"); + } + SysDataSourceEntity deleteEntity = sysDataSourceDao.queryOne(entity); + //删除主表和明细表 + entity.setModify_user_id(StpUtil.getLoginIdAsString()); + entity.setModify_time(new Date()); + entity.setSts("Y"); + try { + dsDataSourceUtil.removeDataSource(deleteEntity.getSourceCode()); + } catch (Exception e) { + return BaseResult.getSuccessMessageEntity("删除数据源失败"); + } + sysDataSourceDao.logicRemoveMultiCondition(entity); + return BaseResult.getSuccessMessageEntity("删除成功"); + } +} diff --git a/service/src/main/java/com/hzya/frame/sys/login/ILoginService.java b/service/src/main/java/com/hzya/frame/sys/login/ILoginService.java new file mode 100644 index 00000000..4279efab --- /dev/null +++ b/service/src/main/java/com/hzya/frame/sys/login/ILoginService.java @@ -0,0 +1,18 @@ +package com.hzya.frame.sys.login; + +import com.alibaba.fastjson.JSONObject; +import com.hzya.frame.web.entity.JsonResultEntity; + +/** + * 登录 + */ +public interface ILoginService { + + /** + * 登录 + * @param jsonObject + * @return + * @throws Exception + */ + JsonResultEntity doLogin(JSONObject jsonObject)throws Exception; +} diff --git a/service/src/main/java/com/hzya/frame/sys/login/impl/LoginServiceImpl.java b/service/src/main/java/com/hzya/frame/sys/login/impl/LoginServiceImpl.java new file mode 100644 index 00000000..b341acdc --- /dev/null +++ b/service/src/main/java/com/hzya/frame/sys/login/impl/LoginServiceImpl.java @@ -0,0 +1,38 @@ +package com.hzya.frame.sys.login.impl; + +import cn.dev33.satoken.stp.SaTokenInfo; +import cn.dev33.satoken.stp.StpUtil; +import com.alibaba.fastjson.JSONObject; +import com.hzya.frame.sys.login.ILoginService; +import com.hzya.frame.web.entity.BaseResult; +import com.hzya.frame.web.entity.JsonResultEntity; +import org.springframework.stereotype.Service; + +/** + * @Description 登录 + * @Author xiangerlin + * @Date 2022/12/20 16:09 + **/ +@Service(value = "loginService") +public class LoginServiceImpl implements ILoginService { + /** + * 登录 + * + * @param requestJsonData + * @return + * @throws Exception + */ + @Override + public JsonResultEntity doLogin(JSONObject requestJsonData) throws Exception { + //登录 + StpUtil.login("1"); + //获取token + SaTokenInfo tokenInfo = StpUtil.getTokenInfo(); + String token = tokenInfo.getTokenValue(); + //返回值 + JSONObject res = new JSONObject(); + res.put("token", token); + res.put("token", token); + return BaseResult.getSuccessMessageEntity("登录成功", res); + } +} diff --git a/service/src/test/java/com/hzya/frame/Tetst01.java b/service/src/test/java/com/hzya/frame/Tetst01.java new file mode 100644 index 00000000..28ac6e3e --- /dev/null +++ b/service/src/test/java/com/hzya/frame/Tetst01.java @@ -0,0 +1,19 @@ +package com.hzya.frame; + +import com.alibaba.fastjson.JSONObject; + +import org.junit.jupiter.api.Test; + +import javax.annotation.Resource; + + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2023-07-18 13:58 + * @Version 1.0 + */ + +public class Tetst01 { + +} diff --git a/webapp/pom.xml b/webapp/pom.xml new file mode 100644 index 00000000..4db047f7 --- /dev/null +++ b/webapp/pom.xml @@ -0,0 +1,39 @@ + + + + kangarooDataCenterV3 + com.hzya.frame + ${revision} + + 4.0.0 + jar + webapp + + + com.hzya.frame + service + ${revision} + + + + + + org.springframework.boot + spring-boot-maven-plugin + + none + execute + + + + + repackage + + + + + + + diff --git a/webapp/src/main/java/com/hzya/frame/web/init/ApplicationContextInitialized.java b/webapp/src/main/java/com/hzya/frame/web/init/ApplicationContextInitialized.java new file mode 100644 index 00000000..3cd24762 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/web/init/ApplicationContextInitialized.java @@ -0,0 +1,56 @@ +package com.hzya.frame.web.init; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * @Content系统初始化监听 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-11-30 14:29 + * @Version 1.0 + */ +public class ApplicationContextInitialized implements ApplicationContextInitializer { + + Logger logger = LoggerFactory.getLogger(ApplicationContextInitialized.class); + + @Override + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + + logger.info("**************************系统已经启动开始初始化********************************"); + logger.info("**************************初始化数据源*****************************************"); +// +//// SqlSession sqlSession = DataSourceUtil.getDefaultSqlSession(); +//// IExecSqlService execSqlService = configurableApplicationContext.getBean(IExecSqlService.class); +//// try { +//// List> data = execSqlService.execSelectSql(" SELECT * from sys_user ", "322"); +//// System.out.println("dataSize" + data.size()); +//// } catch (Exception e) { +//// e.printStackTrace(); +//// } +//// System.out.println("sqlSession" + sqlSession); +// String path = ApplicationContextInitialized.class.getClass().getResource("/").getPath(); +// System.out.println(path); +//// path = path.substring(1, path.indexOf("classes")); +// System.out.println(path); +// +// path += "cfgHome\\plugin\\A8YundaProjectToEsb\\spring\\spring-A8YundaProjectToEsb-manager.xml"; +// path = "cfgHome\\plugin\\A8YundaProjectToEsb\\spring\\spring-A8YundaProjectToEsb-manager.xml"; +// +//// DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); +//// +//// XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); +////// FileSystemXmlApplicationContext fileSystemXmlApplicationContext = new FileSystemXmlApplicationContext(); +//// beanDefinitionReader.loadBeanDefinitions(path); + + } + + + private void closeApplication(ConfigurableApplicationContext configurableApplicationContext) { + + System.exit(1); + } + + +} diff --git a/webapp/src/main/java/com/hzya/frame/web/init/MyApplicationListener.java b/webapp/src/main/java/com/hzya/frame/web/init/MyApplicationListener.java new file mode 100644 index 00000000..2636fc97 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/web/init/MyApplicationListener.java @@ -0,0 +1,266 @@ +package com.hzya.frame.web.init; + +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; +import com.hzya.frame.datasource.DataSourceUtil; +import com.hzya.frame.datasource.DataSourceUtilProperties; +import com.hzya.frame.sys.dataSource.dao.ISysDataSourceDao; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.ArrayList; +import java.util.List; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2023-06-20 17:07 + * @Version 1.0 + */ +@Component +@Order(998) +public class MyApplicationListener implements ApplicationListener { + private Logger logger = LoggerFactory.getLogger(this.getClass()); + @Resource + private DataSource dataSource; + @Resource + private ISysDataSourceDao sysDataSourceDao; + //@Resource + //private IIntegrationTaskService iIntegrationTaskService; + + @Override + public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) { + logger.info("***初始化数据源*******"); + DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource; + DruidDataSource defaultDataSource = createDefaultDataSource(getDefaultDataSourceJsonObject()); + //创建SqlSessionFactory,添加到MAP缓存 + DataSourceUtil.createSqlSessionFactoryToCache("master", defaultDataSource); + ds.addDataSource("master", defaultDataSource); + ds.setPrimary("master"); + ds.setStrict(true); + logger.info("***初始化数据源成功!数据源编码:master ya251 *********"); + + //数据源初始化完成后,执行初始化定时任务 + initTask(); + } + + /**** + * @Content:创建数据源,返回DruidDataSource + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-06-14 9:11 + * @Param [defaultDataSourceProperties] + * @return com.alibaba.druid.pool.DruidDataSource + **/ + private DruidDataSource createDefaultDataSource(JSONObject defaultDataSourceProperties) throws RuntimeException { + //根据datasource_code查询数据源配置信息 + String datasource_code = String.valueOf(defaultDataSourceProperties.get("datasource_code")); + String source_url = String.valueOf(defaultDataSourceProperties.get("source_url")); + String login_name = String.valueOf(defaultDataSourceProperties.get("login_name")); + String password = String.valueOf(defaultDataSourceProperties.get("password")); + String db_name = String.valueOf(defaultDataSourceProperties.get("db_name")); + String source_type = String.valueOf(defaultDataSourceProperties.get("source_type")); + if (defaultDataSourceProperties != null) { + String driveClass = ""; + if ("mysql".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.MYSQLDRIVER_6; + } else if ("oracle".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.ORACLEDRIVER; + } else if ("sqlserver2000".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.SQL2000DRIVER; + } else if ("sqlServer".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.SQL2005DRIVER; + } else if ("dm".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.dm; + } + try { + //测试连接 + Class.forName(driveClass); + Connection connection = DriverManager.getConnection(source_url, login_name, password);// 相当于连接数据库 + if (connection != null) { + //初始化数据源信息 + DruidDataSource druidDataSource = new DruidDataSource(); + druidDataSource.setUrl(source_url); + druidDataSource.setUsername(login_name); + druidDataSource.setPassword(password); + druidDataSource.setName(db_name); + druidDataSource.setDriverClassName(driveClass); + // 连接池连接信息 + druidDataSource.setInitialSize(40);//初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时 + druidDataSource.setMaxActive(1000); //最大连接池数量 0表示无限制 + druidDataSource.setMaxWait(28000); //获取连接时最大等待时间,单位毫秒。当链接数已经达到了最大链接数的时候,应用如果还要获取链接就会出现等待的现象,等待链接释放并回到链接池,如果等待的时间过长就应该踢掉这个等待,不然应用很可能出现雪崩现象 + druidDataSource.setMinIdle(20); //最小空闲连接池数量 + //datasource.setMaxIdle(30); //最大空闲连接池数量 0表示无限制 + druidDataSource.setPoolPreparedStatements(false); //是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。 + druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20); + druidDataSource.setTestOnBorrow(true); //申请连接时执行validationQuery检测连接是否有效,这里建议配置为TRUE,防止取到的连接不可用 + druidDataSource.setTestWhileIdle(true);//建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 + if ("oracle".equals(source_type)) { + druidDataSource.setValidationQuery("select 1 from dual");//用来检测连接是否有效的sql,要求是一个查询语句。如果validationQuery为null,testOnBorrow、testOnReturn、testWhileIdle都不会起作用。 + } else { + druidDataSource.setValidationQuery("SELECT 1"); + } + //datasource.setFilters("stat,wall");//属性类型是字符串,通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:stat日志用的filter:log4j防御sql注入的filter:wall + druidDataSource.setTimeBetweenEvictionRunsMillis(60000); //配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 + druidDataSource.setMinEvictableIdleTimeMillis(300000); //配置一个连接在池中最小生存的时间,单位是毫秒,这里配置为3分钟180000 + druidDataSource.setKeepAlive(true); //打开druid.keepAlive之后,当连接池空闲时,池中的minIdle数量以内的连接,空闲时间超过minEvictableIdleTimeMillis,则会执行keepAlive操作,即执行druid.validationQuery指定的查询SQL,一般为select * from dual,只要minEvictableIdleTimeMillis设置的小于防火墙切断连接时间,就可以保证当连接空闲时自动做保活检测,不会被防火墙切断 + druidDataSource.setRemoveAbandoned(true); //是否移除泄露的连接/超过时间限制是否回收。 + druidDataSource.setRemoveAbandonedTimeout(3600); //泄露连接的定义时间(要超过最大事务的处理时间);单位为秒。这里配置为1小时 + druidDataSource.setLogAbandoned(true); //移除泄露连接发生是是否记录日志 + druidDataSource.setTestOnReturn(false); + + druidDataSource.init(); + return druidDataSource; + } else { + throw new RuntimeException("测试默认数据库连接失败datasource_code:" + datasource_code); + } + } catch (Exception e) { + logger.info("==================创建数据源失败==================="); + throw new RuntimeException("创建数据源失败" + e.getMessage()); + } + + } else { + throw new RuntimeException("source_code:" + datasource_code + "不存在"); + } + } + + + /**** + * @Content:创建默认数据源配置文件 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2023-06-14 9:09 + * @Param [] + * @return com.alibaba.fastjson.JSONObject + **/ + private JSONObject getDefaultDataSourceJsonObject() { + JSONObject defaultDataSourceProperties = new JSONObject(); + + ///////////////////////////////////////////////////////////公司服务器 + defaultDataSourceProperties.put("datasource_code", "ya251"); + defaultDataSourceProperties.put("source_url", "jdbc:mysql://hzya.ufyct.com:9096/businesscenter?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowLoadLocalInfile=false&autoReconnect=true&failOverReadOnly=false&connectTimeout=30000&socketTimeout=30000&autoReconnectForPools=true"); + defaultDataSourceProperties.put("source_type", "mysql"); + defaultDataSourceProperties.put("login_name", "root"); + defaultDataSourceProperties.put("password", "hzya1314"); + defaultDataSourceProperties.put("db_name", "businesscenter"); + + + //defaultDataSourceProperties.put("datasource_code", "bopro"); + //defaultDataSourceProperties.put("source_url", "jdbc:mysql://127.0.0.1:3306/businesscenter?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowLoadLocalInfile=false&autoReconnect=true&failOverReadOnly=false&connectTimeout=30000&socketTimeout=30000&autoReconnectForPools=true"); + //defaultDataSourceProperties.put("source_type", "mysql"); + //defaultDataSourceProperties.put("login_name", "root"); + //defaultDataSourceProperties.put("password", "Bh1591+-j"); + //defaultDataSourceProperties.put("db_name", "businesscenter"); + + /////////////////////////////////////////////////////////// 公司达梦数据库 + //defaultDataSourceProperties.put("datasource_code", "businesscenter"); + //defaultDataSourceProperties.put("source_url", "jdbc:dm://hzya.ufyct.com:9040?schema=businesscenter&characterEncoding=UTF-8"); + //defaultDataSourceProperties.put("source_type", "dm"); + //defaultDataSourceProperties.put("login_name", "HZYAZT"); + //defaultDataSourceProperties.put("password", "hzya@1314"); + //defaultDataSourceProperties.put("db_name", "businesscenter"); + + ///////////////////////////////////////////////////////////本地服务器 +// defaultDataSourceProperties.put("datasource_code", "ya251"); +// defaultDataSourceProperties.put("source_url", "jdbc:mysql://localhost:3306/businesscenter?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false"); +// defaultDataSourceProperties.put("source_type", "mysql"); +// defaultDataSourceProperties.put("login_name", "root"); +// defaultDataSourceProperties.put("password", "seeyon123456"); +// defaultDataSourceProperties.put("db_name", "businesscenter"); + + ///////////////////////////////////////////////////////////速网服务器 +// defaultDataSourceProperties.put("datasource_code", "ya251"); +// defaultDataSourceProperties.put("source_url", "jdbc:mysql://124.71.200.210:10216/businesscenter?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF8&serverTimezone=GMT%2B8&zeroDateTimeBehavior=convertToNull&useSSL=false"); +// defaultDataSourceProperties.put("source_type", "mysql"); +// defaultDataSourceProperties.put("login_name", "root"); +// defaultDataSourceProperties.put("password", "jSvtCVdRZR@10216"); +// defaultDataSourceProperties.put("db_name", "businesscenter"); + return defaultDataSourceProperties; + } + + private void initTask() { + //需要初始化的taskID集合,如果默认不增加则查询所有的任务计划 + List taskIdList = new ArrayList<>(); + //如不需要系统重新初始化任务计划,放开 +// taskIdList.add("系统不初始化插件"); + //杭泰致远销售合同推送钉钉任务 +// taskIdList.add("3497196579928427970"); + //杭泰BIP供应商传递OA +// taskIdList.add("1343295077748918281"); + //杭泰BIP组织传递OA +// taskIdList.add("1410297000456637817"); + //=====================速网start=================== +// //速网U8C存货档案生成旺店通货品档案 +// taskIdList.add("5480192946193190032"); +// //速网U8C供应商档案生成旺店通供应商档案 +// taskIdList.add("-3655259174701414288"); +// //速网U8C采购订单推送旺店通采购订单 +// taskIdList.add("8470345846677980957"); +// //速网旺店通采购入库单,生成U8C采购入库 +// taskIdList.add("-3281025020354081194"); +// //速网U8C红字采购订单,推送旺店通采购退货单 +// taskIdList.add("-8474333912293880929"); +// //速网旺店通采购退货出库单,生成U8C红字采购入库 +// taskIdList.add("-1925311264968064672"); +// //OMS达人寄样销售出库生成U8C销售订单 +// taskIdList.add("-2069765657546371358"); +// //达人寄样退货入库生成U8C红字销售销售出库单 +// taskIdList.add("-2601013958036799088"); +// //速网(TOC)旺店通换货出库,生成U8C销售订单 +// taskIdList.add("6073023852888933683"); +// //速网(TOB)红字销售订单同步旺店通退换单 +// taskIdList.add("-6740993577531585903"); +// //速网(TOB)旺店通退货入库单生成U8C红字销售出库单 +// taskIdList.add("8186943298008796570"); +// //速网(TOC)退货入库单生成U8C红字销售订单 +// taskIdList.add("-7347438162969149145"); +// //速网(TOB)旺店通销售出库单,生成U8C销售出库单 +// taskIdList.add("2307940401916365256"); +// //速网(TOC)旺店通销售出库单生成U8C销售订单 +// taskIdList.add("4313657280852938148"); +// //速网(TOB)U8C销售订单,推送旺店通原始订单 +// taskIdList.add("-1508341403276391185"); +// +// //240142旺店通生产出库单推送U8C其他出库单202401041457 +// taskIdList.add("-1727593887180373437"); +// //240104速网U8C生产组装拆分单,同步旺店通生产单推送202401041501 +// taskIdList.add("-4332012689203573504"); +// //240104旺店通生产入库单推送U8C其他入库单202401041517 +// taskIdList.add("-9101527738616233282"); +// //240104旺店通盘亏出库、(报废)其他出库,同步u8c其他出库单202401041559 +// taskIdList.add("2565596441674991058"); +// //240104旺店通盘盈入库、其他入库,同步u8c其他入库单202401041607 +// taskIdList.add("337296389084038464"); +// //240104速网U8C调拨订单,推送旺店通调拨单202401041539 +// taskIdList.add("6800106772736788841"); +// //240117旺店通调拨出库单推送速网U8C调拨出库单202401171718 +// taskIdList.add("6268657196004560868"); +// //240117旺店通调拨入库单推送速网U8C调拨入库单202401171719 +// taskIdList.add("7472681518255458048"); + + + //=====================速网end===================== + + // =====================测试=================== + //taskIdList.add("406774952091143809"); + //taskIdList.add("7445578911194825754"); + //taskIdList.add("3313595368368981850"); + //taskIdList.add("3497196579928427970"); + //taskIdList.add("3497196579928427970"); + //taskIdList.add("-6468742747231859632"); + //taskIdList.add("-8410742166114775252"); + //=====================测试===================== + //初始化定时任务 + //if (null != iIntegrationTaskService) { + // iIntegrationTaskService.initTaskByIds(taskIdList); + //} + } + +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/entrance/controler/EntranceController.java b/webapp/src/main/java/com/hzya/frame/webapp/entrance/controler/EntranceController.java new file mode 100644 index 00000000..5475bc91 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/entrance/controler/EntranceController.java @@ -0,0 +1,39 @@ +package com.hzya.frame.webapp.entrance.controler; + +import com.hzya.frame.web.entity.JsonResultEntity; +import com.hzya.frame.webapp.entrance.service.IEntranceService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +/** + * @Content程序唯一入口controller + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-07 8:46 + * @Version 1.0 + */ +@RestControllerAdvice +@RestController +@RequestMapping("/entranceController") +public class EntranceController { + private final Logger logger = LoggerFactory.getLogger(EntranceController.class); + + @Autowired + @Qualifier(value = "entranceServiceImpl") + private IEntranceService entranceService; + + @RequestMapping(value = "/option") + @ResponseBody + public JsonResultEntity option(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { + return entranceService.doBusiness(servletRequest, servletResponse); + } + +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/entrance/service/IEntranceService.java b/webapp/src/main/java/com/hzya/frame/webapp/entrance/service/IEntranceService.java new file mode 100644 index 00000000..c3aceef3 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/entrance/service/IEntranceService.java @@ -0,0 +1,18 @@ +package com.hzya.frame.webapp.entrance.service; + +import com.hzya.frame.web.entity.JsonResultEntity; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-07 8:47 + * @Version 1.0 + */ +public interface IEntranceService { + + JsonResultEntity doBusiness(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception; + +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/entrance/service/impl/EntranceServiceImpl.java b/webapp/src/main/java/com/hzya/frame/webapp/entrance/service/impl/EntranceServiceImpl.java new file mode 100644 index 00000000..95f2aeb6 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/entrance/service/impl/EntranceServiceImpl.java @@ -0,0 +1,108 @@ +package com.hzya.frame.webapp.entrance.service.impl; + +import cn.dev33.satoken.exception.NotLoginException; +import cn.dev33.satoken.stp.StpUtil; +import cn.hutool.extra.servlet.ServletUtil; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.dynamic.datasource.annotation.DSTransactional; +import com.hzya.frame.web.action.ApplicationContextUtil; +import com.hzya.frame.web.cache.ServiceMethodCache; +import com.hzya.frame.web.entity.BaseResult; +import com.hzya.frame.web.entity.JsonResultEntity; +import com.hzya.frame.web.exception.BaseSystemException; +import com.hzya.frame.webapp.entrance.service.IEntranceService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.util.ObjectUtils; + +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * @Content统一根据请求服务处理相关业务service + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-07 8:47 + * @Version 1.0 + */ +@Service(value = "entranceServiceImpl") +public class EntranceServiceImpl implements IEntranceService { + + private final Logger logger = LoggerFactory.getLogger(EntranceServiceImpl.class); + @Autowired + private ServiceMethodCache serviceMethodCache; + + + @Override + @DSTransactional() + public JsonResultEntity doBusiness(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { + HttpServletRequest request = (HttpServletRequest) servletRequest; + //tailuo 要访问的Bean名称 + String service = request.getHeader("tl"); + //bean方法 + String serviceMethod = request.getHeader("dj"); + String body = ServletUtil.getBody(servletRequest); + //获取类 + Object object = null; + try { + object = ApplicationContextUtil.getBeanByName(service); + } catch (SecurityException e) { + return BaseResult.getFailureMessageEntity(service + "未找到"); + } + //获取类下面的方法 + Method[] methods = object.getClass().getMethods(); + logger.info("methodsLength:" + methods.length); + if (methods == null || methods.length == 0) { + logger.info("当前methods:" + methods + "methodsLength = " + methods.length); + return BaseResult.getFailureMessageEntity(service + "未找到" + serviceMethod + "方法"); + } else { + logger.error("当前methods:" + methods + "methodsLength = " + methods.length); + } + for (Method m : methods) { + logger.info("当前mnAME:" + m.getName() + " :serviceMethod = " + serviceMethod.trim()); + if (null != m) { + if (m.getName().equals(serviceMethod.trim())) { + if (!"doLogin".equals(m.getName())) { + try { + StpUtil.checkLogin(); + } catch (NotLoginException e) { + logger.error("token无效"); + return BaseResult.getFailureMessageEntity("token无效"); + } + } + logger.info("m.getNameEquals成功"); + JSONObject jsonObject = new JSONObject(); + if (!ObjectUtils.isEmpty(body)) { + jsonObject.put("jsonStr", body); + } + JsonResultEntity jsonResultEntity; + try { + logger.info("invoke开始>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + logger.info("请求的参数:jsonObject:" + jsonObject.toJSONString()); + jsonResultEntity = (JsonResultEntity) m.invoke(object, jsonObject); + logger.info("invoke结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); + return jsonResultEntity; + } catch (Exception e) { + logger.error("METHOD doBusiness invokeException{}", e.getMessage()); + if (e instanceof InvocationTargetException) { + Throwable targetException = ((InvocationTargetException) e).getTargetException(); + if (targetException instanceof BaseSystemException) { + throw new BaseSystemException(targetException.getMessage()); + } else { + logger.info("METHOD doBusiness :{}", e.getMessage()); + throw e; + } + } else { + throw e; + } + } + } + } + } + return BaseResult.getFailureMessageEntity(service + "未找到" + serviceMethod + "方法"); + } +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/aop/AopDynamicRoutingDataSourceInit.java b/webapp/src/main/java/com/hzya/frame/webapp/web/aop/AopDynamicRoutingDataSourceInit.java new file mode 100644 index 00000000..1406a128 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/aop/AopDynamicRoutingDataSourceInit.java @@ -0,0 +1,170 @@ +package com.hzya.frame.webapp.web.aop; + +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.fastjson.JSONObject; +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; +import com.baomidou.dynamic.datasource.annotation.DS; +import com.baomidou.dynamic.datasource.exception.CannotFindDataSourceException; +import com.hzya.frame.datasource.DataSourceUtilProperties; +import com.hzya.frame.sys.dataSource.dao.ISysDataSourceDao; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceEntity; +import com.hzya.frame.sys.dataSource.entity.SysDataSourceVo; +import com.hzya.frame.web.entity.BaseEntity; +import com.hzya.frame.web.exception.BaseSystemException; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DriverManager; +import java.util.List; + +/** + * @author 👻👻👻👻👻👻👻👻👻👻 gjh + * @version 1.0 + * @content + * @date 2023-10-09 11:50 + */ +@Aspect +@Component +//@Order(1) +public class AopDynamicRoutingDataSourceInit { + private final Logger logger = LoggerFactory.getLogger(this.getClass()); + @Resource + private DataSource dataSource; + @Resource + private ISysDataSourceDao sysDataSourceDao; + + + @Before("@annotation(dsAnnotation)") + public void beforeDynamicRoutingDataSourceInitMethod(JoinPoint joinPoint, DS dsAnnotation) { + logger.info("beforeDynamicRoutingDataSourceInitMethod:拦截所有使用ds注解的方法,根据ds的value值初始化数据源!"); + String dsValue = dsAnnotation.value(); + if (dsValue != null && !"".equals(dsValue) && dsValue.contains("#")) { + Object[] args = joinPoint.getArgs(); + if (args.length > 0) { + for (int i = 0; i < args.length; i++) { + Object arg = args[i]; + if (arg instanceof BaseEntity) { + BaseEntity baseEntity = (BaseEntity) arg; + dsValue = baseEntity.getDataSourceCode(); + } + } + } + } + logger.info("beforeDynamicRoutingDataSourceInitMethod DS.value:" + dsValue); + DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource; + DataSource dsDatasource = null; + try { + dsDatasource = ds.getDataSource(dsValue); + } catch (CannotFindDataSourceException exception) { + logger.info("beforeDynamicRoutingDataSourceInitMethod:根据ds获取dsDatasource失败!异常信息:" + "exception.getMessage()" + " 执行初始化数据源:" + dsValue); + SysDataSourceEntity entity = new SysDataSourceEntity(); + entity.setSts("Y"); + entity.setUseState(1); + entity.setSourceCode(dsValue); + List sysDataSourceEntities = sysDataSourceDao.queryVoList(entity); + logger.info("beforeDynamicRoutingDataSourceInitMethod:根据dsValue获取数据源信息查询结果 sysDataSourceEntities.size:" + sysDataSourceEntities.size()); + if (sysDataSourceEntities != null && sysDataSourceEntities.size() > 0) { + for (int i = 0; i < sysDataSourceEntities.size(); i++) { + JSONObject defaultDataSourceProperties = new JSONObject(); + defaultDataSourceProperties.put("datasource_code", sysDataSourceEntities.get(i).getSourceCode()); + defaultDataSourceProperties.put("source_url", sysDataSourceEntities.get(i).getSourceUrl()); + defaultDataSourceProperties.put("source_type", sysDataSourceEntities.get(i).getSourceTypeName()); + defaultDataSourceProperties.put("login_name", sysDataSourceEntities.get(i).getLoginName()); + defaultDataSourceProperties.put("password", sysDataSourceEntities.get(i).getPassword()); + defaultDataSourceProperties.put("db_name", sysDataSourceEntities.get(i).getDbName()); + try { + logger.info("***初始化数据源-{}:*********", sysDataSourceEntities.get(i).getSourceName()); + DruidDataSource dataSource = createDefaultDataSource(defaultDataSourceProperties); + ds.addDataSource(sysDataSourceEntities.get(i).getSourceCode(), dataSource); + //把datasource放入缓存中 +// DataSourceUtil.createSqlSessionFactoryToCache(sysDataSourceEntities.get(i).getSourceCode(),dataSource); + logger.info("***初始化数据源-{}成功:*********", sysDataSourceEntities.get(i).getSourceName()); + } catch (Exception e) { + logger.info("***初始化数据源-{}失败:*********", sysDataSourceEntities.get(i).getSourceName()); + logger.info(e.getMessage()); + } + } + } else { + logger.info("beforeDynamicRoutingDataSourceInitMethod:根据dsValue未获取数据源信息查询结果 抛出数据源初始化失败异常:" + dsValue); + throw new BaseSystemException("根据dsValue: " + dsValue + " 未能初始化成功数据源!请检查数据源信息!"); + } + } + } + + private DruidDataSource createDefaultDataSource(JSONObject defaultDataSourceProperties) throws RuntimeException { + //根据datasource_code查询数据源配置信息 + String datasource_code = String.valueOf(defaultDataSourceProperties.get("datasource_code")); + String source_url = String.valueOf(defaultDataSourceProperties.get("source_url")); + String login_name = String.valueOf(defaultDataSourceProperties.get("login_name")); + String password = String.valueOf(defaultDataSourceProperties.get("password")); + String db_name = String.valueOf(defaultDataSourceProperties.get("db_name")); + String source_type = String.valueOf(defaultDataSourceProperties.get("source_type")); + if (defaultDataSourceProperties != null) { + String driveClass = ""; + if ("mysql".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.MYSQLDRIVER_6; + } else if ("oracle".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.ORACLEDRIVER; + } else if ("sqlserver2000".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.SQL2000DRIVER; + } else if ("sqlServer".equalsIgnoreCase(source_type)) { + driveClass = DataSourceUtilProperties.SQL2005DRIVER; + } +// else if ("dm".equalsIgnoreCase(source_type)) { +// driveClass = DataSourceUtilProperties.dm; +// } + try { + //测试连接 + Class.forName(driveClass); + Connection connection = DriverManager.getConnection(source_url, login_name, password);// 相当于连接数据库 + if (connection != null) { + //初始化数据源信息 + DruidDataSource druidDataSource = new DruidDataSource(); + druidDataSource.setUrl(source_url); + druidDataSource.setUsername(login_name); + druidDataSource.setPassword(password); + druidDataSource.setName(db_name); + druidDataSource.setDriverClassName(driveClass); + druidDataSource.setInitialSize(5); + druidDataSource.setMinIdle(5); + druidDataSource.setMaxActive(100); + druidDataSource.setMaxWait(60000); + druidDataSource.setTimeBetweenEvictionRunsMillis(60000); + druidDataSource.setMinEvictableIdleTimeMillis(300000); + druidDataSource.setMaxEvictableIdleTimeMillis(600000); + if ("oracle".equals(source_type)) { + druidDataSource.setValidationQuery("select 1 from dual"); + } else { + druidDataSource.setValidationQuery("SELECT 1"); + } + druidDataSource.setTestWhileIdle(true); + druidDataSource.setTestOnBorrow(false); + druidDataSource.setTestOnReturn(false); + druidDataSource.setPoolPreparedStatements(true); + druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(20); + druidDataSource.setRemoveAbandoned(true); + druidDataSource.setRemoveAbandonedTimeout(999999); + druidDataSource.init(); + return druidDataSource; + } else { + throw new RuntimeException("测试默认数据库连接失败datasource_code:" + datasource_code); + } + } catch (Exception e) { + logger.info("==================创建数据源失败==================="); + throw new RuntimeException("创建数据源失败" + e.getMessage()); + } + + + } else { + throw new RuntimeException("source_code:" + datasource_code + "不存在"); + } + } + +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/exception/CommonConstant.java b/webapp/src/main/java/com/hzya/frame/webapp/web/exception/CommonConstant.java new file mode 100644 index 00000000..0fc90313 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/exception/CommonConstant.java @@ -0,0 +1,12 @@ +package com.hzya.frame.webapp.web.exception; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 10:31 + * @Version 1.0 + */ +public class CommonConstant { + public static final String ERROR_CONTROLLER_PATH = "/error/throw"; + +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/exception/ExceptionController.java b/webapp/src/main/java/com/hzya/frame/webapp/web/exception/ExceptionController.java new file mode 100644 index 00000000..3e966cf1 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/exception/ExceptionController.java @@ -0,0 +1,157 @@ +package com.hzya.frame.webapp.web.exception; + + +import cn.dev33.satoken.exception.NotLoginException; +import com.hzya.frame.web.entity.BaseResult; +import com.hzya.frame.web.entity.JsonResultEntity; +import com.hzya.frame.web.exception.BaseSystemException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.NoHandlerFoundException; + +import javax.servlet.http.HttpServletRequest; + +/** + * @Content所有controller抛出的异常,统一此处处理 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 9:37 + * @Version 1.0 + */ +@ControllerAdvice +public class ExceptionController { + + private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionController.class); + +// @Autowired +// private ExceptionLogService exceptionLogService; + + @ExceptionHandler(value = NoHandlerFoundException.class) + public ModelAndView notHandlerFoundExceptionHandler(HttpServletRequest request, Exception e) { + LOGGER.error(e.getMessage(), e); + return new ModelAndView("redirect:/common/404"); + } + + @ExceptionHandler(value = BaseSystemException.class) + @ResponseBody + public JsonResultEntity exceptionHandle(HttpServletRequest request, BaseSystemException baseSystemException) { + HttpStatus httpStatus = getStatus(request); + Integer statusCode = httpStatus.value(); + baseSystemException.printStackTrace(); + LOGGER.error(baseSystemException.getMessage()); + + String message = baseSystemException.getMessage(); + String data = baseSystemException.getLocalizedMessage(); + return getErrorJsonResultEntity(message,data, httpStatus, statusCode); + } + + @ExceptionHandler(NotLoginException.class) + @ResponseBody + public JsonResultEntity exceptionHandle(HttpServletRequest request, NotLoginException notLoginException) { + HttpStatus httpStatus = getStatus(request); + Integer statusCode = httpStatus.value(); + notLoginException.printStackTrace(); + LOGGER.error(notLoginException.getMessage()); + String message = notLoginException.getMessage(); + // 判断场景值,定制化异常信息 + if (notLoginException.getType().equals(NotLoginException.NOT_TOKEN)) { + message = "未提供token"; + } else if (notLoginException.getType().equals(NotLoginException.INVALID_TOKEN)) { + message = "token无效"; + } else if (notLoginException.getType().equals(NotLoginException.TOKEN_TIMEOUT)) { + message = "token已过期"; + } else if (notLoginException.getType().equals(NotLoginException.BE_REPLACED)) { + message = "token已被顶下线"; + } else if (notLoginException.getType().equals(NotLoginException.KICK_OUT)) { + message = "token已被踢下线"; + } else { + message = "当前会话未登录"; + } + String data = notLoginException.getLocalizedMessage(); + return getErrorJsonResultEntity(message,data, httpStatus, statusCode); + } + private JsonResultEntity getErrorJsonResultEntity(String message, String data, HttpStatus httpStatus, Integer statusCode) { + + switch (statusCode){ + case 403: + message = "没有权限"; + data = "/common/403"; + break; + case 404: + message = "未找到请求路径"; + data = "/common/404"; + break; + case 500: + message = message == null ? "系统错误,请联系管理员" : message; + data = "/common/500"; + break; + default: + + } + + + return BaseResult.getFailureMessageEntity(message, String.valueOf(httpStatus.value()), data ); + } + + + /*** + * @Content:监听系统异常 + * @Author 👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 11:40 + * @Param [request, e] + * @return org.springframework.web.servlet.ModelAndView + **/ + @ExceptionHandler(value = Exception.class) + @ResponseBody + public JsonResultEntity exceptionHandle(HttpServletRequest request, Exception exception) { + // 输出异常日志 + exception.printStackTrace(); + //获取状态码 + HttpStatus httpStatus = getStatus( request); + Integer statusCode = httpStatus.value(); + // 构建返回数据 + String message = exception.getMessage(); + String data = exception.getLocalizedMessage(); + LOGGER.info("系统错误!",exception); + return getErrorJsonResultEntity(message,data, httpStatus, statusCode); + } + + private boolean isInterface(HttpServletRequest request) { + // 通过debug调试可以看出request中含有该对象。 + HandlerMethod handlerMethod = (HandlerMethod) request.getAttribute("org.springframework.web.servlet.HandlerMapping.bestMatchingHandler"); + // getBeanType()拿到发送请求得类模板(Class),getDeclaredAnnotationsByType(指定注解类模板)通过指定得注解,得到一个数组。 + if (null != handlerMethod) { + RestController[] annotations1 = handlerMethod.getBeanType().getDeclaredAnnotationsByType(RestController.class); + ResponseBody[] annotations2 = handlerMethod.getBeanType().getDeclaredAnnotationsByType(ResponseBody.class); + ResponseBody[] annotations3 = handlerMethod.getMethod().getAnnotationsByType(ResponseBody.class); + // 判断当类上含有@RestController或是@ResponseBody或是方法上有@ResponseBody时,则表明该异常是一个接口请求发生的 + return annotations1.length > 0 || annotations2.length > 0 || annotations3.length > 0; + } else { + return false; + } + + } + + + protected HttpStatus getStatus(HttpServletRequest request) { + // 获取状态值 + Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); + if (statusCode == null) { + return HttpStatus.INTERNAL_SERVER_ERROR; + } else { + try { + return HttpStatus.valueOf(statusCode); + } catch (Exception var4) { + return HttpStatus.INTERNAL_SERVER_ERROR; + } + } + } +} + + diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/exception/MyBasicErrorController.java b/webapp/src/main/java/com/hzya/frame/webapp/web/exception/MyBasicErrorController.java new file mode 100644 index 00000000..aede65b7 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/exception/MyBasicErrorController.java @@ -0,0 +1,114 @@ +package com.hzya.frame.webapp.web.exception; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 9:40 + * @Version 1.0 + */ + +import com.hzya.frame.web.entity.BaseResult; +import com.hzya.frame.web.entity.JsonResultEntity; +import com.hzya.frame.web.exception.BaseSystemException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.web.error.ErrorAttributeOptions; +import org.springframework.boot.web.servlet.error.ErrorAttributes; +import org.springframework.boot.web.servlet.error.ErrorController; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.context.request.ServletWebRequest; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Map; + +/** + * @Description: + * @ClassName:spring_boot_j220601 + * @Author:。。。。 + * @CreateDate:2022-09-20 16:12:03 + **/ +@SuppressWarnings("ALL") +@Controller +@RequestMapping({"${server.error.path:${error.path:/error}}"}) +public class MyBasicErrorController implements ErrorController { + @Autowired + private ErrorAttributes errorAttributes; + + + @RequestMapping(CommonConstant.ERROR_CONTROLLER_PATH) + public void handleException(HttpServletRequest request) { + throw (BaseSystemException) request.getAttribute("filterError"); + } + + // 页面请求异常 + @RequestMapping(produces = MediaType.TEXT_HTML_VALUE) + public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { + throw new BaseSystemException("系统异常"); + } + + // 接口请求异常 + @RequestMapping + @ResponseBody + public JsonResultEntity error(HttpServletRequest request) { + Map body = getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.ALL)); + body.get("status"); + body.get("error"); + body.get("path"); + body.get("message"); + StringBuffer messageBuffer = new StringBuffer(); + messageBuffer.append("系统异常!请联系系统管理员。错误信息:"); + messageBuffer.append(body.get("error")); + messageBuffer.append(body.get("path")); + return BaseResult.getFailureMessageEntity(messageBuffer.toString(), String.valueOf(body.get("status"))); + } + + protected Map getErrorAttributes(HttpServletRequest request, ErrorAttributeOptions options) { + WebRequest webRequest = new ServletWebRequest(request); + return this.errorAttributes.getErrorAttributes(webRequest, options); + } + + protected HttpStatus getStatus(HttpServletRequest request) { + // 获取状态值 + Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); + if (statusCode == null) { + return HttpStatus.INTERNAL_SERVER_ERROR; + } else { + try { + return HttpStatus.valueOf(statusCode); + } catch (Exception var4) { + return HttpStatus.INTERNAL_SERVER_ERROR; + } + } + } + + protected ErrorAttributeOptions getErrorAttributeOptions(HttpServletRequest request, MediaType mediaType) { + ErrorAttributeOptions options = ErrorAttributeOptions.defaults(); +// if (this.errorProperties.isIncludeException()) { +// options = options.including(new ErrorAttributeOptions.Include[]{ErrorAttributeOptions.Include.EXCEPTION.EXCEPTION}); +// } +// +// if (this.isIncludeStackTrace(request, mediaType)) { +// options = options.including(new ErrorAttributeOptions.Include[]{Include.STACK_TRACE}); +// } +// +// if (this.isIncludeMessage(request, mediaType)) { +// options = options.including(new ErrorAttributeOptions.Include[]{Include.MESSAGE}); +// } +// +// if (this.isIncludeBindingErrors(request, mediaType)) { +// options = options.including(new ErrorAttributeOptions.Include[]{Include.BINDING_ERRORS}); +// } + + return options; + } + +} + + + diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/filter/BaseFilter.java b/webapp/src/main/java/com/hzya/frame/webapp/web/filter/BaseFilter.java new file mode 100644 index 00000000..8d62574e --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/filter/BaseFilter.java @@ -0,0 +1,105 @@ +package com.hzya.frame.webapp.web.filter; + +import com.google.common.collect.Lists; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpServletResponseWrapper; +import java.io.IOException; +import java.util.List; + +/** + * @Content + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-05 9:01 + * @Version 1.0 + */ +public class BaseFilter implements Filter { + static final String TOKEN = "20220423344556abac"; + //内部接口集合 + public static List INSIDE_URLS = Lists.newArrayList("/index", "/inside"); + //白名单接口集合 + public static List WHITE_PATH = Lists.newArrayList("/white", "/login"); + + //无需认证接口 + public static List NotCertifiedService = Lists.newArrayList("seeYonInterFace", "ddInterfaceService"); + + Logger logger = LoggerFactory.getLogger(BaseFilter.class); + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + logger.info("初始化数据"); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + + logger.info("第二过滤器:验证权限"); + HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse); + HttpServletRequest request = (HttpServletRequest) servletRequest; + String requestURI = request.getRequestURI(); + String method = request.getMethod(); + String service = request.getHeader("as"); + String serviceMethod = request.getHeader("dj"); + //要访问的Bean名称 + String tl = request.getHeader("tl"); + + if (INSIDE_URLS.contains(requestURI)) { + //内部接口,直接通过 + filterChain.doFilter(servletRequest, servletResponse); + return; + } + if (WHITE_PATH.contains(requestURI)) { + //白名单接口,直接通过 + filterChain.doFilter(servletRequest, servletResponse); + return; + } + if (NotCertifiedService.contains(tl)) { + //白名单接口,直接通过 + filterChain.doFilter(servletRequest, servletResponse); + return; + } + //校验请求的服务是否有存在权限 + //if (ObjectUtils.isEmpty(serviceMethod)) { + // logger.info("当前请求的服务为空:" + service); + // throw new BaseSystemException("当前请求的方法为空!"); + //} else { + // logger.info("当前请求的方法:" + service); + //} + // + //if (ObjectUtils.isEmpty(service)) { + // logger.info("当前请求的服务为空:" + service); + // throw new BaseSystemException("当前请求的服务为空!"); + //} else { + // logger.info("当前请求的服务:" + service); + //} + + + //进行校验,如token校验 + String token = request.getHeader("token"); + if (TOKEN.equals(token)) { + filterChain.doFilter(servletRequest, servletResponse); + } else { + //token校验不通过,重定向到登录页面 + + +// + filterChain.doFilter(servletRequest, servletResponse); +// wrapper.sendRedirect("/login"); + } + + } + + @Override + public void destroy() { + } +} + diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/filter/ExceptionOptionFilter.java b/webapp/src/main/java/com/hzya/frame/webapp/web/filter/ExceptionOptionFilter.java new file mode 100644 index 00000000..b7bdbb56 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/filter/ExceptionOptionFilter.java @@ -0,0 +1,37 @@ +package com.hzya.frame.webapp.web.filter; + +import com.hzya.frame.webapp.web.exception.CommonConstant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import java.io.IOException; + +/** + * @Content异常处理filter + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 10:18 + * @Version 1.0 + */ + +public class ExceptionOptionFilter implements Filter { + private final static Logger LOGGER = LoggerFactory.getLogger(ExceptionOptionFilter.class); + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { + try { + LOGGER.info("第一过滤器:处理异常Filter"); + filterChain.doFilter(request, response); + } catch (Exception e) { + e.printStackTrace(); + // 传递异常信息 + request.setAttribute("filterError", e); + // 指定处理该请求的处理器 + request.getRequestDispatcher(CommonConstant.ERROR_CONTROLLER_PATH).forward(request, response); + } + } +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/filter/FilterConfiguration.java b/webapp/src/main/java/com/hzya/frame/webapp/web/filter/FilterConfiguration.java new file mode 100644 index 00000000..a3a76652 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/filter/FilterConfiguration.java @@ -0,0 +1,39 @@ +package com.hzya.frame.webapp.web.filter; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @Content注册过滤器,设置过滤器优先级以及过滤路径 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-06 10:34 + * @Version 1.0 + */ +@Configuration +public class FilterConfiguration { + @Bean + public FilterRegistrationBean ExceptionOptionFilter() { + //通过FilterRegistrationBean实例设置优先级可以生效 + //通过@WebFilter无效 + FilterRegistrationBean bean = new FilterRegistrationBean(); + bean.setFilter(new ExceptionOptionFilter());//注册自定义过滤器 + bean.setName("fxceptionOptionFilter");//过滤器名称 + bean.addUrlPatterns("/*");//过滤所有路径 + bean.setOrder(1);//优先级,最顶级 + return bean; + } + + @Bean + public FilterRegistrationBean BaseFilter() { + //通过FilterRegistrationBean实例设置优先级可以生效 + //通过@WebFilter无效 + FilterRegistrationBean bean = new FilterRegistrationBean(); + bean.setFilter(new BaseFilter());//注册自定义过滤器 + bean.setName("baseFilter");//过滤器名称 + bean.addUrlPatterns("/*");//过滤所有路径 + bean.setOrder(2);//优先级,越低越优先 + return bean; + } + +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/filter/SaTokenConfigure.java b/webapp/src/main/java/com/hzya/frame/webapp/web/filter/SaTokenConfigure.java new file mode 100644 index 00000000..b325e29f --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/filter/SaTokenConfigure.java @@ -0,0 +1,30 @@ +package com.hzya.frame.webapp.web.filter; + +import cn.dev33.satoken.config.SaTokenConfig; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +/** + * @Description sa-token配置类 + * @Author xiangerlin + * @Date 2022/12/20 16:04 + **/ +@Configuration +public class SaTokenConfigure { + // Sa-Token 参数配置,参考文档:https://sa-token.cc + // 此配置会覆盖 application.yml 中的配置 + @Bean + @Primary + public SaTokenConfig getSaTokenConfigPrimary() { + SaTokenConfig config = new SaTokenConfig(); + config.setTokenName("token"); // token名称 (同时也是cookie名称) + config.setTimeout(30 * 24 * 60 * 60); // token有效期,单位s 默认30天 + config.setActivityTimeout(-1); // token临时有效期 (指定时间内无操作就视为token过期) 单位: 秒 + config.setIsConcurrent(true); // 是否允许同一账号并发登录 (为true时允许一起登录, 为false时新登录挤掉旧登录) + config.setIsShare(true); // 在多人登录同一账号时,是否共用一个token (为true时所有登录共用一个token, 为false时每次登录新建一个token) + config.setTokenStyle("uuid"); // token风格 + config.setIsLog(false); // 是否输出操作日志 + return config; + } +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/init/ApplicationContextInitialized.java b/webapp/src/main/java/com/hzya/frame/webapp/web/init/ApplicationContextInitialized.java new file mode 100644 index 00000000..5b165541 --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/init/ApplicationContextInitialized.java @@ -0,0 +1,26 @@ +package com.hzya.frame.webapp.web.init; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; + +/** + * @Content系统初始化监听 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-11-30 14:29 + * @Version 1.0 + */ +public class ApplicationContextInitialized implements ApplicationContextInitializer { + + Logger logger = LoggerFactory.getLogger(ApplicationContextInitialized.class); + + @Override + public void initialize(ConfigurableApplicationContext configurableApplicationContext) { + + logger.info("**************************系统开始初始化********************************"); + + } + + +} diff --git a/webapp/src/main/java/com/hzya/frame/webapp/web/listener/InitCommandLineRunner.java b/webapp/src/main/java/com/hzya/frame/webapp/web/listener/InitCommandLineRunner.java new file mode 100644 index 00000000..6e757fed --- /dev/null +++ b/webapp/src/main/java/com/hzya/frame/webapp/web/listener/InitCommandLineRunner.java @@ -0,0 +1,100 @@ +package com.hzya.frame.webapp.web.listener; + +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import com.hzya.frame.base.PluginBaseEntity; +import com.hzya.frame.util.PluginUtils; +import com.hzya.frame.web.action.ApplicationContextUtil; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.context.ApplicationListener; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.List; + +/** + * @Content系统初始化参数监听 + * @Author 👻👻👻👻👻👻👻👻👻👻 gjh + * @Date 2022-12-07 10:45 + * @Version 1.0 + */ + +@Component +@Order(999) +public class InitCommandLineRunner implements ApplicationListener { + + Logger logger = LoggerFactory.getLogger(InitCommandLineRunner.class); + + @Override + public void onApplicationEvent(ApplicationReadyEvent event) { + + + String path = InitCommandLineRunner.class.getClassLoader().getResource("").getPath(); + ; + logger.info("cfgHomeClassURL:" + path); +// System.out.println(System.getProperty("java.class.path")); + //拼接插件路径 + logger.info("初始化插件 START >>>>>>>>>>>>>>>>>>>>>>>>>>"); + String pluginCfgHomePath = path + "cfgHome" + File.separator + "plugin" + File.separator; + File file = new File(pluginCfgHomePath); + File[] files = file.listFiles(); + if (null != files && files.length > 0) { + for (int i = 0; i < files.length; i++) { + File file1 = files[i]; + File[] cFile = file1.listFiles(); + if (cFile.length > 0) { + for (int n = 0; n < cFile.length; n++) { + File file2 = cFile[n]; + String fileName = file2.getName(); + if (fileName.contains("pluginCfg")) { + InputStream is = null; + try { + is = new FileInputStream(file2); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + String xmlStr = null; + try { + xmlStr = IOUtils.toString(is, StandardCharsets.UTF_8); + } catch (IOException e) { + e.printStackTrace(); + } + JSONObject resultJson = JSONUtil.parseFromXml(xmlStr); + JSONObject pluginJson = JSONUtil.parseObj(resultJson.get("plugin")); + String beanID = pluginJson.get("id") + "_Initializer"; + try { +// A8YundaProjectToEsbManager + Object object = ApplicationContextUtil.getBeanByName(beanID); + //System.out.println(object.toString()); + logger.info("初始化插件成功:" + pluginJson.get("name") + " 插件编号:" + pluginJson.get("category")); + } catch (Exception e) { + logger.info("初始化插件失败:" + pluginJson.get("name") + " 插件编号:" + pluginJson.get("category")); + logger.error(e.getMessage()); + } + } + } + } + } + } + logger.info("初始化插件 END <<<<<<<<<<<<<<<<<<<<<<<<"); + logger.info("执行插件init方法 START >>>>>>>>>>>>>>>>>>>>>>>>>>"); + List beans = PluginUtils.getPlugins(); + + for (PluginBaseEntity pluginBaseEntity : beans) { + pluginBaseEntity.getPluginId(); + pluginBaseEntity.getPluginId(); + logger.info(pluginBaseEntity.getPluginLabel() + pluginBaseEntity.getPluginId()); + } + logger.info("pluginBaseEntityList>>>>>>>>>>>>>>>>>>>>>>>>>>"); + } + +}