main
lcode 9 months ago
commit 3e2cfb234a

@ -0,0 +1,45 @@
logs/
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
.mvn/timing.properties
# https://github.com/takari/maven-wrapper#usage-without-binary-jar
.mvn/wrapper/maven-wrapper.jar
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
/mentalhealth/logs.log

@ -0,0 +1 @@
# 883铝业erp

@ -0,0 +1,413 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.currency</groupId>
<artifactId>appengine</artifactId>
<version>1.0.0</version>
<name>appengine</name>
<description>currency appengine project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<fluent-mybatis.version>1.9.7</fluent-mybatis.version>
<magic-api.version>2.1.1</magic-api.version>
<commons-text.version>1.10.0</commons-text.version>
<tencentcloud.version>3.1.872</tencentcloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Paging query plugin -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
<exclusions>
<exclusion>
<artifactId>mybatis-spring-boot-starter</artifactId>
<groupId>org.mybatis.spring.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<!-- csr证书创建 -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.56</version>
</dependency>
<!-- 接入腾讯云短信 -->
<!-- https://central.sonatype.com/search?q=tencentcloud-sdk-java&smo=true 按需接入腾讯云sdk -->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java-sms</artifactId>
<version>${tencentcloud.version}</version><!-- 注:这里只是示例版本号(可直接使用),可获取并替换为 最新的版本号注意不要使用4.0.x版本非最新版本 -->
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.7</version>
</dependency>
<!-- 开发包 -->
<dependency>
<groupId>org.ssssssss</groupId>
<artifactId>magic-api-spring-boot-starter</artifactId>
<version>${magic-api.version}</version>
<exclusions>
<exclusion>
<artifactId>commons-text</artifactId>
<groupId>org.apache.commons</groupId>
</exclusion>
</exclusions>
</dependency>
<!-- 额外依赖commons-text -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>${commons-text.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
<exclusions>
<exclusion>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-ui</artifactId>
</exclusion>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.eclipse.birt.runtime.3_7_1</groupId>
<artifactId>com.lowagie.text</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
<!--OSS Java SDK-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>net.dreamlu</groupId>
<artifactId>mica-weixin</artifactId>
<version>2.1.2</version>
</dependency>
<!-- 邮件start -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
<!-- 邮件end -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.15</version>
</dependency>
<!-- hutool Java工具类库 -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.0.M4</version>
</dependency>
<!-- 导出 -->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.4.0</version>
<exclusions>
<exclusion>
<artifactId>hutool-all</artifactId>
<groupId>cn.hutool</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version> <!-- 使用最新版本 -->
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<!-- thymeleaf模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 获取IP归属地 -->
<dependency>
<groupId>org.lionsoul</groupId>
<artifactId>ip2region</artifactId>
<version>2.6.4</version>
</dependency>
<!-- json -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<!-- 支付 -->
<!-- <dependency>-->
<!-- <groupId>com.github.javen205</groupId>-->
<!-- <artifactId>IJPay-WxPay</artifactId>-->
<!-- <version>2.8.3</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<!--pdf获取页数-->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
<!--word转pdf文档-->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
<!--word转pdf文档-->
<!--导出pdf-->
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.itextpdf/itext-asian -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.7</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.github.javaparser</groupId>
<artifactId>javaparser-core</artifactId>
<version>3.6.5</version> <!-- 请替换为最新版本号 -->
</dependency>
</dependencies>
<repositories>
<repository>
<id>central</id>
<url>https://mirror.aliyun.com/maven/repository</url>
</repository>
<repository>
<id>public</id>
<url>https://mirror.aliyun.com/maven/repository</url>
</repository>
<repository>
<id>sonatype-oss-public</id>
<url>https://oss.sonatype.org/content/repositories/public/</url>
</repository>
</repositories>
<build>
<finalName>appengine</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
<!--将本地使用的jar打包的时候引入lib-->
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin>
<!--本地包打入配置-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>compile</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/lib
</outputDirectory>
<includeScope>system</includeScope>
</configuration>
</execution>
</executions>
</plugin>
<!-- 添加Groovy编译插件 -->
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<configScript>config.groovy</configScript>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,21 @@
package com.currency.appengine;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
@EnableCaching
@EnableAsync
@EnableScheduling // 开启定时任务
public class AppengineApplication {
public static void main(String[] args) {
SpringApplication.run(AppengineApplication.class, args);
}
}

@ -0,0 +1,10 @@
package com.currency.appengine.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckToken {
}

@ -0,0 +1,43 @@
package com.currency.appengine.annotation;
import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.ValueConstants;
import java.lang.annotation.*;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CustomParam {
/**
* Alias for {@link #name}.
*/
@AliasFor("name")
String value() default "";
/**
* The name of the request parameter to bind to.
*
* @since 4.2
*/
@AliasFor("value")
String name() default "";
/**
* Whether the parameter is required.
* <p>Default is {@code true}, leading to an exception thrown in case
* of the parameter missing in the request. Switch this to {@code false}
* if you prefer a {@code null} in case of the parameter missing.
* <p>Alternatively, provide a {@link #defaultValue() defaultValue},
* which implicitly sets this flag to {@code false}.
*/
boolean required() default true;
/**
* The default value to use as a fallback when the request parameter value
* is not provided or empty. Supplying a default value implicitly sets
* {@link #required()} to false.
*/
String defaultValue() default ValueConstants.DEFAULT_NONE;
}

@ -0,0 +1,9 @@
package com.currency.appengine.annotation;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NoResult {
}

@ -0,0 +1,9 @@
package com.currency.appengine.annotation;
import java.lang.annotation.*;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestParamsDeal {
}

@ -0,0 +1,102 @@
package com.currency.appengine.aop;
import com.currency.appengine.utils.HttpUtil;
import com.currency.appengine.utils.JsonUtil;
import com.currency.appengine.utils.ObjectUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Aspect
@Component
//@Profile({"dev", "test"})
public class ControllerLogAspect {
private final static Logger logger = LoggerFactory.getLogger(ControllerLogAspect.class);
private static final String LINE_SEPARATOR = System.lineSeparator();
/**
* @ControllerLog
*/
@Pointcut("execution(* com.currency.appengine.controller..*.*(..))")
public void ControllerLog() {
}
@Before("ControllerLog()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Object[] args = joinPoint.getArgs();
String queryString = request.getQueryString();
Object params = "";
if (args.length > 0) {
if ("POST".equals(request.getMethod())) {
Object object = args[0];
if (Objects.nonNull(object)) {
Map map = getKeyAndValue(object);
params = map;
}
} else if ("GET".equals(request.getMethod())) {
params = queryString;
}
}
logger.info("URL : {}", request.getRequestURL().toString());
logger.info("HTTP Method : {}", request.getMethod());
logger.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
logger.info("IP : {}", HttpUtil.getIpAddress(request));
logger.info("Request Args : {}", params);
logger.info("Request token : user-token[{}] | guest-token[{}]", request.getHeader("user-token"), request.getHeader("guest-token"));
}
@After("ControllerLog()")
public void doAfter() {
}
@Around("ControllerLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
logger.info("========================================== Start ==========================================");
long startTime = System.currentTimeMillis();
Object result = proceedingJoinPoint.proceed();
logger.info("Response Args : {}", JsonUtil.generate(result));
logger.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
logger.info("=========================================== End ===========================================" + LINE_SEPARATOR);
return result;
}
public static Map getKeyAndValue(Object obj) {
Map map = new HashMap<>();
Class userCla = obj.getClass();
if (obj instanceof Map) {
return ObjectUtil.objectToMap(obj);
}
Field[] fs = userCla.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
Field f = fs[i];
f.setAccessible(true);
Object val;
try {
val = f.get(obj);
map.put(f.getName(), val);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return map;
}
}

@ -0,0 +1,58 @@
//package com.currency.appengine.aop;
//
//import com.currency.appengine.utils.ObjectUtil;
//import com.currency.appengine.utils.redisOption.RedisCache;
//import org.aspectj.lang.JoinPoint;
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.*;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//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.util.Arrays;
//import java.util.List;
//
//@Aspect
//@Component
////@Profile({"dev", "test"})
//public class RedisAspect {
// private final static Logger logger = LoggerFactory.getLogger(RedisAspect.class);
// private static final String LINE_SEPARATOR = System.lineSeparator();
//
//
// @Autowired
// RedisCache redisCache;
//
// /**
// * @ControllerLog
// */
// @Pointcut("execution(* com.currency.appengine.controller..*.*(..))")
// public void RedisCache() {
// }
//
// @Before("RedisCache()")
// public void doBefore(JoinPoint joinPoint) {
// }
//
// @After("RedisCache()")
// public void doAfter() {
//
// }
//
// @Around("RedisCache()")
// public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// String targetMethodParams= Arrays.toString(proceedingJoinPoint.getArgs());
// List params = ObjectUtil.objectToList(proceedingJoinPoint.getArgs());
// RequestAttributes ra = RequestContextHolder.getRequestAttributes();
// ServletRequestAttributes sra = (ServletRequestAttributes) ra;
// HttpServletRequest request = sra.getRequest();
// Object result = proceedingJoinPoint.proceed();
// redisCache.redisCacheClear(params, request, result);
// return result;
// }
//}

@ -0,0 +1,17 @@
package com.currency.appengine.config;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
*
*
* @author ruoyi
*/
@Configuration
// 指定要扫描的Mapper类的包的路径
@MapperScan("com.currency.appengine.**.mapper")
public class ApplicationConfig {
// 定义fluent mybatis的MapperFactory
}

@ -0,0 +1,40 @@
package com.currency.appengine.config;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.NettyCustomizer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ClientConfig {
@Bean
public ClientResources clientResources() {
NettyCustomizer nettyCustomizer = new NettyCustomizer() {
@Override
public void afterChannelInitialized(Channel channel) {
channel.pipeline().addLast(
//此处事件必须⼩于超时时间
new IdleStateHandler(40, 0, 0));
channel.pipeline().addLast(new ChannelDuplexHandler() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
ctx.disconnect();
}
}
});
}
@Override
public void afterBootstrapInitialized(Bootstrap bootstrap) {
}
};
return ClientResources.builder().nettyCustomizer(nettyCustomizer).build();
}
}

@ -0,0 +1,24 @@
package com.currency.appengine.config;
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class CommonConfiguration {
/**
* Register MyBatis Paging Plugin PageHelper
*/
@Bean
public PageHelper pageHelper() {
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}

@ -0,0 +1,369 @@
package com.currency.appengine.config;
import com.currency.appengine.domain.system.SysParam;
import com.currency.appengine.enums.EnvEnum;
import com.currency.appengine.enums.ParamCodeEnum;
import com.currency.appengine.mapper.common.DicMapper;
import com.currency.appengine.mapper.system.SysParamMapper;
import com.currency.appengine.utils.JsonUtil;
import com.currency.appengine.utils.StringUtil;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@Component
@Order(value=2)
public class GlobalData implements CommandLineRunner {
/**
*
*/
private static final Logger logger= LoggerFactory.getLogger(GlobalData.class);
@Autowired
SysParamMapper sysParamMapper;
@Autowired
DicMapper dicMapper;
@Resource
Environment environment;
/**
*
*/
public static Map<String, Object> sysParamsMap = new HashMap<>();
public static Searcher searcher = null; // ip 查询归属地对象
public static ConcurrentMap<String, Object> concurrentMap = new ConcurrentHashMap<>();
public static Map<String, Map<String, String>> dicMap = new HashMap<>(); // 字典
/**
*
*
* key:
* */
public String getEnv(String key) {
return environment.getProperty(key);
}
/**
*
* EnvEnum
* key: EnvEnum
* */
public String getEnvByEnum(String envKey) {
return environment.getProperty(EnvEnum.getKey(envKey));
}
public String getFileFolder(){
String fileUploadMode = getSysParams(ParamCodeEnum.fileUploadMode.toString());
if (StringUtil.notBlank(fileUploadMode) && "ON".equals(fileUploadMode)) {
return getSysParams(ParamCodeEnum.ossFileFolder.toString());
} else {
return getSysParams(ParamCodeEnum.fileFolder.toString());
}
}
public String getFilePath(){
String fileUploadMode = getSysParams(ParamCodeEnum.fileUploadMode.toString());
if (StringUtil.notBlank(fileUploadMode) && "ON".equals(fileUploadMode)) {
return getSysParams(ParamCodeEnum.ossFilePath.toString());
} else {
return getSysParams(ParamCodeEnum.filePath.toString());
}
}
/**
* key
* @param key
* @return
*/
public String getSysParams(String key) {
logger.info(">>>>>> 获取参数{} <<<<<< ", key);
try {
/*if (redisUtil.hasKey(InfRedisKey.GLOBPARAMS.key())) {
Object globParams = redisUtil.get(InfRedisKey.GLOBPARAMS.key());
if (StringUtil.notEmpty(globParams)) {
Map<String, Object> obj = JsonUtil.parseObject(String.valueOf(globParams), Map.class);
if (obj == null) {
return null;
}
return String.valueOf(obj.get(key));
}
}*/
if (sysParamsMap.containsKey(key)) {
return String.valueOf(Objects.isNull(sysParamsMap.get(key))?"":sysParamsMap.get(key));
}
// 为空查询数据库
List<SysParam> sysParams = sysParamMapper.sysParams();
// sysParamsMap = sysParams.stream().collect(Collectors.toMap(SysParam::getParamCode, SysParam::getParamValue));
sysParamsMap = sysParams.stream().collect(HashMap::new,
(m, v)->m.put(v.getParamCode(), v.getParamValue()), HashMap::putAll);
// redisUtil.set(InfRedisKey.GLOBPARAMS.key(), JsonUtil.generate(sysParamsMap));
return String.valueOf(sysParamsMap.get(key));
} catch(Exception e) {
logger.error(e.getMessage());
return null;
}
}
/**
* key
* @param key
* @return
*/
public Map<String, Object> getSysParamsVague(String key) {
logger.info(">>>>>> 获取参数{} <<<<<< ", key);
try {
Map<String, Object> result = sysParamsMap.entrySet().stream()
.filter(entry -> entry.getKey().contains(key))
.collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue()));
if (result != null && result.size() > 0) {
return result;
}
// 为空查询数据库
List<SysParam> sysParams = sysParamMapper.sysParams();
sysParamsMap = sysParams.stream().collect(HashMap::new,
(m, v)->m.put(v.getParamCode(), v.getParamValue()), HashMap::putAll);
result = sysParamsMap.entrySet().stream()
.filter(entry -> entry.getKey().contains(key))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return result;
} catch(Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
return null;
}
}
/*
*
* */
@Override
public void run(String... args) throws Exception {
try {
logger.info("***************开始加载缺省数据***************");
//获取系统配置信息,
List<SysParam> sysParams = sysParamMapper.sysParams();
/* 所有参数处理 */
paramsHandle(sysParams);
/* 前端参数单独处理 */
paramsFront(sysParams);
/* 字典数据加载 */
dicHandle();
logger.info("***************结束加载缺省数据***************");
logger.info("***************开始加载IP数据库数据***************");
ipXdb();
logger.info("***************结束加载IP数据库数据***************");
String mysqlIp = getEnv("var.mysql.ip");
String database = getEnv("var.mysql.database");
String env = getEnv("var.env");
String file = environment.getActiveProfiles()[0];
logger.info("***************数据库ip{},数据库名:{},环境:{},配置文件:{}***************", mysqlIp, database, env, file);
} catch (Exception e) {
logger.error("***************结束加载IP数据库数据异常***************");
}
}
/**
*
*/
public void dicHandle() {
logger.info("***************加载字典数据***************");
List<Map<String, String>> dic = dicMapper.getDic();
dicMap = dic.stream().collect(HashMap::new,
(m, v)->m.put(v.get("type") + "_" + v.get("value"), v), HashMap::putAll);
}
/**
*
* @param group
* @return
*/
public List<Map<String, String>> getDic(String group) {
if (dicMap.isEmpty() || dicMap.size() == 0) {
dicHandle();
}
// String regex = group + "_.*"; // 正则表达式
String regex = "(" + group.replaceAll(",", "|") + ")_.*";
Pattern pattern = Pattern.compile(regex);
List<Map<String, String>> res = dicMap.entrySet().stream()
.filter(entry -> pattern.matcher(entry.getKey()).matches())
.map(Map.Entry::getValue)
.collect(Collectors.toList());
return res;
}
public Map<String, List<Map<String, String>>> getDicByGroups(String group) {
if (dicMap.isEmpty() || dicMap.size() == 0) {
dicHandle();
}
String regex = "(" + group.replaceAll(",", "|") + ")_.*"; // 正则表达式
Pattern pattern = Pattern.compile(regex);
Map<String, List<Map<String, String>>> res = dicMap.entrySet().stream().filter(entry -> pattern.matcher(entry.getKey()).matches()).collect(Collectors.groupingBy(
entry -> entry.getKey().split("_")[0],
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
return res;
}
/**
*
* @param group
* @param code
* @return
*/
public Map<String, String> getDicByGroupCode(String group, String code) {
if (dicMap.isEmpty() || dicMap.size() == 0) {
dicHandle();
}
return dicMap.get(group + "_" + code);
}
/**
*
* @param sysParams
*/
private Map<String, Object> paramsFront(List<SysParam> sysParams) {
Map<String, Object> front =
sysParams.stream().filter((s) -> "2".equals(s.getSysFg())).collect(HashMap::new,
(m, v)->m.put(v.getParamCode(), v.getParamValue()), HashMap::putAll);
if (!front.isEmpty()) {
// redisUtil.set(InfRedisKey.GLOBPARAMSFRONT.key(), JsonUtil.generate(front));
}
return front;
}
/**
*
* @param sysParams
*/
private void paramsHandle(List<SysParam> sysParams) {
// sysParamsMap = sysParams.stream().collect(Collectors.toMap(SysParam::getParamCode, SysParam::getParamValue));
sysParamsMap = sysParams.stream().collect(HashMap::new,
(m, v)->m.put(v.getParamCode(), v.getParamValue()), HashMap::putAll);
// redisUtil.set(InfRedisKey.GLOBPARAMS.key(), JsonUtil.generate(sysParamsMap));
// logger.info("所有参数:>>>>>> {}", JsonUtil.generate(sysParamsMap));
}
/**
* IP
*/
private void ipXdb() {
// 获取jar 包目录System.getProperty("user.dir")
String dbPath = System.getProperty("user.dir") + "/ip2region/ip2region.xdb";
Path path = Paths.get(dbPath);
if (Files.exists(path)) {
logger.warn("ip2region文件存在");
} else {
logger.warn("ip2region文件不存在");
return;
}
// 1、从 dbPath 加载整个 xdb 到内存。
byte[] cBuff;
try {
cBuff = Searcher.loadContentFromFile(dbPath);
} catch (Exception e) {
logger.error("failed to load content from `%s`: %s\n", dbPath, e);
return;
}
// 2、使用上述的 cBuff 创建一个完全基于内存的查询对象。
try {
searcher = Searcher.newWithBuffer(cBuff);
} catch (Exception e) {
logger.error("failed to create content cached searcher: %s\n", e);
}
}
/*
*
* */
public void resetSysParams() {
logger.info("***************开始更新缺省数据***************");
//获取系统配置信息,
List<SysParam> sysParams = sysParamMapper.sysParams();
/* 所有参数处理 */
paramsHandle(sysParams);
/* 前端参数单独处理 */
// paramsFront(sysParams);
logger.info("***************结束更新缺省数据***************");
}
/*
* ip
* 使 xdbjar
*
* */
public Map<String, Object> queryBelong(String ip) {
// 获取jar 包目录System.getProperty("user.dir")
// ApplicationHome home = new ApplicationHome(HttpUtil.class);
// File jarFile = home.getSource();
// String path = jarFile.getParentFile().toString();
Map<String, Object> result = new HashMap<>();
result.put("code", 0);
result.put("country", "-");
result.put("province", "-");
result.put("city", "-");
// 从缓存中获取ip 的归属地
// 3、查询
try {
if (searcher == null) {
return result;
}
String region = searcher.search(ip);
if (StringUtil.notEmpty(region)) {
result.put("code", 0);
String[] regions = region.split("\\|");
result.put("country", regions[0]);
result.put("province", regions[2]);
result.put("city", regions[3]);
}
return result;
} catch (Exception e) {
// logger.error("failed to search(%s): %s\n", ip, e);
return result;
}
}
}

@ -0,0 +1,39 @@
package com.currency.appengine.config;
import com.currency.appengine.handler.magic.CustomJsonValueProvider;
import com.currency.appengine.handler.magic.CustomPageProvider;
import com.currency.appengine.handler.magic.CustomRequestInterceptor;
import org.springframework.context.annotation.Configuration;
import org.ssssssss.magicapi.modules.db.provider.PageProvider;
/**
* magic-api
*
* // @Bean 注释查看效果
*/
@Configuration
public class MagicAPIConfiguration {
/**
* JSON
*/
public CustomJsonValueProvider customJsonValueProvider() {
return new CustomJsonValueProvider();
}
/**
*
*/
public PageProvider pageProvider() {
return new CustomPageProvider();
}
/**
*
*/
public CustomRequestInterceptor customRequestInterceptor() {
return new CustomRequestInterceptor();
}
}

@ -0,0 +1,79 @@
package com.currency.appengine.config;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
@Configuration
public class MybatisConfig {
/**
* mybatis resultTypemap线
*/
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setObjectWrapperFactory(new MapWrapperFactory());
}
static class MapWrapperFactory implements ObjectWrapperFactory {
@Override
public boolean hasWrapperFor(Object object) {
return object != null && object instanceof Map;
}
@Override
public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
return new MyMapWrapper(metaObject, (Map) object);
}
}
static class MyMapWrapper extends MapWrapper {
MyMapWrapper(MetaObject metaObject, Map<String, Object> map) {
super(metaObject, map);
}
@Override
public String findProperty(String name, boolean useCamelCaseMapping) {
if (useCamelCaseMapping
&& ((name.charAt(0) >= 'A' && name.charAt(0) <= 'Z')
|| name.contains("_"))) {
return underlineToCamelhump(name);
}
return name;
}
/**
* 线
*
* @param inputString
* @return
*/
private String underlineToCamelhump(String inputString) {
StringBuilder sb = new StringBuilder();
boolean nextUpperCase = false;
for (int i = 0; i < inputString.length(); i++) {
char c = inputString.charAt(i);
if (c == '_') {
if (sb.length() > 0) {
nextUpperCase = true;
}
} else {
if (nextUpperCase) {
sb.append(Character.toUpperCase(c));
nextUpperCase = false;
} else {
sb.append(Character.toLowerCase(c));
}
}
}
return sb.toString();
}
}
}

@ -0,0 +1,107 @@
//package com.currency.appengine.config;
//
//import com.fasterxml.jackson.annotation.JsonAutoDetect;
//import com.fasterxml.jackson.annotation.JsonTypeInfo;
//import com.fasterxml.jackson.annotation.PropertyAccessor;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.fasterxml.jackson.databind.SerializationFeature;
//import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
//import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.cache.annotation.EnableCaching;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.PropertySource;
//import org.springframework.core.env.Environment;
//import org.springframework.data.redis.cache.RedisCacheConfiguration;
//import org.springframework.data.redis.cache.RedisCacheManager;
//import org.springframework.data.redis.connection.RedisConnectionFactory;
//import org.springframework.data.redis.connection.RedisPassword;
//import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
//import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
//import org.springframework.data.redis.serializer.StringRedisSerializer;
//
//import java.time.Duration;
//
//@Configuration
//@EnableCaching
//@PropertySource("classpath:application.yml")
//public class RedisConfig {
// @Autowired
// private Environment env;
//
// @Bean
// public LettuceConnectionFactory redisConnectionFactory() {
// RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration();
// redisConf.setHostName(env.getProperty("spring.redis.host"));
// redisConf.setPort(Integer.parseInt(env.getProperty("spring.redis.port")));
// redisConf.setPassword(RedisPassword.of(env.getProperty("spring.redis.password")));
// redisConf.setDatabase(Integer.parseInt(env.getProperty("spring.redis.database")));
//
// return new LettuceConnectionFactory(redisConf);
// }
//
// @Bean
// public RedisCacheConfiguration cacheConfiguration() {
// RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
// .entryTtl(Duration.ofSeconds(600))
// .disableCachingNullValues();
// return cacheConfig;
// }
//
// @Bean
// public RedisCacheManager cacheManager() {
// RedisCacheManager rcm = RedisCacheManager.builder(redisConnectionFactory())
// .cacheDefaults(cacheConfiguration())
// .transactionAware()
// .build();
// return rcm;
// }
//
// /**
// * retemplate configuration
// *
// * @param redisConnectionFactory
// * @return
// */
// @Bean
// public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
// RedisTemplate<String, Object> template = new RedisTemplate<>();
// template.setConnectionFactory(redisConnectionFactory);
// setRedisTemplate(template);
// return template;
// }
//
// private void setRedisTemplate(RedisTemplate<String, Object> template) {
// // json serialization configuration
// Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
// ObjectMapper objectMapper = new ObjectMapper();
// objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// // solve the problem that Jackson2 cannot deserialize LocalDateTime
// objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// objectMapper.registerModule(new JavaTimeModule());
// // om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// // the above enableDefaultTyping method is outdated, use activateDefaultTyping
// objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
// jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//
// // string serialization configuration
// StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//
// // key uses string serialization
// template.setKeySerializer(stringRedisSerializer);
// // the value uses string serialization
// template.setValueSerializer(stringRedisSerializer);
//
// // the hash key uses string serialization
// template.setHashKeySerializer(stringRedisSerializer);
// // the hash value serialization method uses jackson
// template.setHashValueSerializer(jackson2JsonRedisSerializer);
// // The serialization of the value uses FastJsonRedisSerializer.
// // Set the key serialization using StringRedisSerializer.
// template.afterPropertiesSet();
// }
//
//}

@ -0,0 +1,21 @@
package com.currency.appengine.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
// .apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.currency.appengine"))
.paths(PathSelectors.regex("/api/.*"))
.build();
}
}

@ -0,0 +1,85 @@
package com.currency.appengine.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ThreadPoolConfiguration {
/**
* 线线线0线
* 线线corePoolSize
* 线线maxPoolSize使
*/
/**
* 线线
*/
private static final int corePoolSize = 1;
/**
* 线
*/
private static final int maxPoolSize = 10;
/**
* 线
*/
private static final int keepAliveSeconds = 60;
/**
*
*/
private static final int queueCapacity = 100;
/**
* 线
*/
private static final String threadNamePrefix = "hanshui-logThread-";
@Bean("logThread")
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setKeepAliveSeconds(keepAliveSeconds);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix(threadNamePrefix);
// 线程池对拒绝任务的处理策略
// CallerRunsPolicy由调用线程提交任务的线程处理该任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
executor.initialize();
return executor;
}
@Bean("emailThread")
public ThreadPoolTaskExecutor emailThread () {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程数10线程池创建时候初始化的线程数
executor.setCorePoolSize(10);
// 最大线程数20
executor.setMaxPoolSize(15);
// 缓冲队列200
executor.setQueueCapacity(200);
// 允许线程的空闲时间60秒
executor.setKeepAliveSeconds(60);
// 线程池名的前缀:
executor.setThreadNamePrefix("emailThread-");
/*
线CallerRunsPolicy
*/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
executor.setWaitForTasksToCompleteOnShutdown(true);
// 设置线程池中任务的等待时间,如果超过这个时候还没有销毁就强制销毁,
executor.setAwaitTerminationSeconds(600);
return executor;
}
}

@ -0,0 +1,72 @@
package com.currency.appengine.config;
import com.currency.appengine.handler.GlobalInterceptor;
import com.currency.appengine.handler.CustomMethodArgumentResolver;
import com.currency.appengine.handler.magic.DevInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.*;
import java.util.List;
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
/**
* Interceptor verification token
*
* @return
*/
@Bean
public GlobalInterceptor GlobalInterceptor() {
return new GlobalInterceptor();
}
@Bean
public DevInterceptor DevInterceptor() {
return new DevInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(GlobalInterceptor()).addPathPatterns("/**");
registry.addInterceptor(DevInterceptor()).addPathPatterns("/swagger-ui.html").addPathPatterns("/magic/**");
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(new CustomMethodArgumentResolver());
WebMvcConfigurer.super.addArgumentResolvers(resolvers);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
// .allowedOrigins("*")
.allowedOriginPatterns("*")
.allowCredentials(true)
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.maxAge(3600);
}
/*
* swagger2访
* : 访swaggerswagger
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
// registry.addResourceHandler("/webjars/**")
// .addResourceLocations("classpath:/META-INF/resources/webjars/");
// registry.addResourceHandler("doc.html").addResourceLocations(
// "classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:knife4j/webjars/");
registry.addResourceHandler("doc.html").addResourceLocations(
"classpath:knife4j/");
}
}

@ -0,0 +1,13 @@
package com.currency.appengine.config.api;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
@Component
public class AutoPrefixConfiguration implements WebMvcRegistrations {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new AutoPrefixUrlMapping();
}
}

@ -0,0 +1,31 @@
package com.currency.appengine.config.api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.lang.reflect.Method;
@Component
public class AutoPrefixUrlMapping extends RequestMappingHandlerMapping {
// 从配置文件中读取根目录
@Value("${project.api-package}")
private String apiPackagePath;
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
RequestMappingInfo mappingInfo = super.getMappingForMethod(method, handlerType);
if (mappingInfo != null){
String prefix = this.getPrefix(handlerType);
RequestMappingInfo newMappingInfo = RequestMappingInfo.paths(prefix).build().combine(mappingInfo);
return newMappingInfo;
}
return mappingInfo;
}
// 获取前缀
private String getPrefix(Class<?> handlerType){
String packageName = handlerType.getPackage().getName();
String newPath = packageName.replaceAll(this.apiPackagePath, "");
return newPath.replace(".","/");
}
}

@ -0,0 +1,323 @@
package com.currency.appengine.controller;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.currency.appengine.annotation.CheckToken;
import com.currency.appengine.domain.system.SysParam;
import com.currency.appengine.service.system.SysMenuService;
import com.currency.appengine.service.system.SysParamService;
import com.currency.appengine.service.system.SysRoleService;
import com.currency.appengine.service.system.SysUserService;
import com.currency.appengine.utils.JsonUtil;
import com.currency.appengine.utils.ReqParamsUtil;
import com.currency.appengine.utils.Result;
import com.currency.appengine.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @date 2021/07/25
*/
@RestController
@RequestMapping("/sys/authority")
public class SystemController {
@Autowired
SysUserService sysUserService;
@Autowired
SysMenuService sysMenuService;
@Autowired
SysRoleService sysRoleService;
@Autowired
SysParamService sysParamService;
/*
*
* */
@RequestMapping("/kaptcha")
public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setContentType("image/jpeg");
//生成验证码
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 60);
session.setAttribute("KAPTCHA_SESSION_KEY", lineCaptcha.getCode());
//向客户端写出
ServletOutputStream out = response.getOutputStream();
lineCaptcha.write(out);
try {
out.flush();
} finally {
out.close();
}
}
/**
*
* @param params
* @return
*/
@PostMapping("/user/login")
public Result userLogin(@RequestBody Map<String, Object> params, HttpSession session) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("user");
mustExistList.add("password");
mustExistList.add("verifycode");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
// 校验验证码
String code = String.valueOf(session.getAttribute("KAPTCHA_SESSION_KEY"));
if (StringUtil.notEmpty(session.getAttribute("KAPTCHA_SESSION_KEY"))) {
String vercode = String.valueOf(params.get("verifycode"));
if (!code.equals(vercode)) {
return Result.fail(-14,"验证码错误");
}
} else {
return Result.fail(-14,"验证码错误");
}
return sysUserService.userLogin(params);
}
/**
*
**/
@GetMapping("/user/list/all")
@CheckToken
public Result userListAll() {
return sysUserService.userListAll();
}
@PostMapping("/user/add")
@CheckToken
public Result userAdd(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("userName");
mustExistList.add("name");
mustExistList.add("password");
mustExistList.add("group");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysUserService.userAdd(params);
}
@PostMapping("/user/del")
@CheckToken
public Result userDel(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("ids");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysUserService.userDel(params);
}
@PostMapping("/user/edit")
@CheckToken
public Result userEdit(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("id");
mustExistList.add("userName");
mustExistList.add("name");
mustExistList.add("group");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysUserService.userEdit(params);
}
@PostMapping("/user/edit/password")
@CheckToken
public Result userEditPassword(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("id");
mustExistList.add("password");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysUserService.userEditPassword(params);
}
@PostMapping("/user/edit/name")
@CheckToken
public Result userEditName(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("id");
mustExistList.add("name");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysUserService.userEditName(params);
}
/**
*
* @return
*/
@GetMapping("/role/list/all")
@CheckToken
public Result roleListAll() {
return sysRoleService.getRoleListAll();
}
@PostMapping("/role/add")
@CheckToken
public Result roleAdd(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("sort");
mustExistList.add("label");
mustExistList.add("alias");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysRoleService.roleAdd(params);
}
@PostMapping("/role/edit")
@CheckToken
public Result roleEdit(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("id");
mustExistList.add("sort");
mustExistList.add("label");
mustExistList.add("alias");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysRoleService.roleEdit(params);
}
@PostMapping("/role/del")
@CheckToken
public Result roleDel(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("ids");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysRoleService.roleDel(params);
}
@PostMapping("/role/menu")
@CheckToken
public Result roleAndMenu(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("id");
mustExistList.add("menuIds");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysRoleService.roleAndMenu(params);
}
@GetMapping("/role/menu/check")
@CheckToken
public Result roleAndMenuCheck(@RequestParam Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("id");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysRoleService.roleAndMenuCheck(params);
}
/**
*
* @return
*/
@GetMapping("/menu/list/all")
@CheckToken
public Result menuListAll() {
return sysMenuService.getRouterListAll();
}
@PostMapping("/menu/add")
@CheckToken
public Result menuAdd(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("name");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysMenuService.menuAdd(params);
}
@PostMapping("/menu/edit")
@CheckToken
public Result menuEdit(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("name");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysMenuService.menuEdit(params);
}
@PostMapping("/menu/del")
@CheckToken
public Result menuDel(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("names");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysMenuService.menuDel(params);
}
@PostMapping("/param/add")
@CheckToken
public Result add(@RequestBody SysParam sysParam) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("paramCode");
Map map = JsonUtil.parse(sysParam, Map.class);
if (ReqParamsUtil.paramIsExist(mustExistList, map) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysParamService.save(sysParam);
}
@PostMapping("/param/update")
@CheckToken
public Result update(@RequestBody SysParam sysParam) {
return sysParamService.update(sysParam);
}
@PostMapping("/param/delete")
@CheckToken
public Result deleteById(@RequestBody Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
mustExistList.add("sysParamIds");
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysParamService.deleteById(params);
}
@GetMapping("/param/pagelist")
@CheckToken
public Result pageList(@RequestParam Map<String, Object> params) {
List<String> mustExistList = new ArrayList<String>();
if (ReqParamsUtil.paramIsExist(mustExistList, params) == 1) {
return Result.fail(-1, "result.others.request.param_not_null");
}
return sysParamService.pageList(params);
}
@PostMapping("/param/cache/update")
@CheckToken
public Result cacheUpdate() {
return sysParamService.cacheUpdate();
}
}

@ -0,0 +1,43 @@
package com.currency.appengine.controller;
import cn.hutool.json.JSONUtil;
import com.currency.appengine.mapper.common.CommonMapper;
import com.currency.appengine.utils.JsonUtil;
import com.currency.appengine.utils.Result;
import com.currency.appengine.utils.pdf.PDFUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
CommonMapper commonMapper;
@PostMapping("/test")
public Result test(@RequestBody String json, HttpServletResponse response) {
// Map map = JsonUtil.parseObject(json, Map.class);
// PDFUtil.genPdf(map, response);
JSONObject jsonObject = new JSONObject();
jsonObject.put("xxx", "\"");
String jsonStr = JSONUtil.toJsonStr(jsonObject);
Map<String, Object> params = new HashMap<>();
params.put("customerName", "迪蒙");
String sql = "select user_name from sys_user";
return Result.suc(commonMapper.count("mini_customer_info", "customer_name = #{customerName}", params));
}
@PostMapping("/swagger")
public Result swaggerTest(@RequestBody Map map) {
return Result.suc();
}
}

@ -0,0 +1,85 @@
package com.currency.appengine.controller.dev;
import cn.hutool.core.util.ZipUtil;
import com.currency.appengine.config.GlobalData;
import com.currency.appengine.utils.AesEncryptUtils;
import com.currency.appengine.utils.Result;
import com.currency.appengine.utils.StringUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
@RestController
@RequestMapping("/dev")
public class DevController {
private static Logger logger = LoggerFactory.getLogger(DevController.class);
@Autowired
GlobalData globalData;
@Value("${project.env}")
private String projectEnv;
@RequestMapping("/deployfront")
public Result deployFront(@RequestParam MultipartFile[] files, @RequestParam String distkey) {
if (!"dev".equals(projectEnv)) {
return Result.fail(-1, "仅支持测试环境部署");
}
logger.info("部署key{}", distkey);
if (!StringUtil.notEmpty(distkey)) {
return Result.fail(-1, "密钥不能为空");
}
// 密钥匹配
String frontKey = AesEncryptUtils.decryptByFront(distkey, globalData.getEnv("deployfront.aes-key"));
if (!globalData.getEnv("deployfront.plaintext").equals(frontKey)) {
return Result.fail(-1, "密钥不正确");
}
logger.info("部署key明文{}", frontKey);
MultipartFile multipartFile = files[0];
ApplicationHome home = new ApplicationHome(getClass());
File jarFile = home.getSource();
// 文件保存路径
String filePath = new File(jarFile.getParent()).getParent();
logger.info("部署目录:{}", filePath);
// 文件名
File file = new File(filePath +File.separator + "dist.zip");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
IOUtils.copy(multipartFile.getInputStream(),fileOutputStream);
File unzip = ZipUtil.unzip(filePath +File.separator + "dist.zip", filePath);
logger.info("解压目录:{}", unzip.getPath());
} catch (FileNotFoundException e) {
e.printStackTrace();
return Result.fail(-1, "部署失败");
} catch (IOException e) {
e.printStackTrace();
return Result.fail(-1, "部署失败");
}finally {
try {
// 关闭
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
logger.error("文件关闭错误",e);
return Result.fail(-1, "部署失败");
}
}
return Result.suc();
}
}

@ -0,0 +1,39 @@
package com.currency.appengine.controller.export;
import com.currency.appengine.domain.export.UserInfoExport;
import com.currency.appengine.export.ExportServer;
import com.currency.appengine.export.impl.ExportServerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.util.PendingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
@RestController
@RequestMapping("/web/export")
public class ExportController {
@Autowired
private ExportServerImpl<UserInfoExport> uiExportServer;
@Autowired
private ExportServer exportServer;
//用户信息导出
@PostMapping("/userInfo")
public void userExport(@RequestBody Map<String, Object> map){
uiExportServer.exportDefaultServer("用户信息", UserInfoExport.class, map, 0);
}
@PostMapping(value = "/exportExpertWord")
public void exportExpertWord(@RequestBody String json, HttpServletRequest request, HttpServletResponse response) throws PendingException {
exportServer.exportExpertWord(json, request, response);
}
}

@ -0,0 +1,33 @@
package com.currency.appengine.controller.importFile;
import com.currency.appengine.controller.importFile.entity.MiniDataEntity;
import com.currency.appengine.service.importFile.ImportFileService;
import com.currency.appengine.service.importFile.impl.ImportFileServiceImpl;
import com.currency.appengine.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@RestController
@RequestMapping("/api/import")
public class ImportController {
@Autowired
ImportFileService importExcelService;
@PostMapping("/importExcel")
public Result importExcel(@RequestPart("file") MultipartFile file){
return importExcelService.importExcel(file);
}
@PostMapping("/importExcelCommon")
public Result importExcelCommon(@RequestPart("file") MultipartFile file, String type){
return importExcelService.importExcelCommon(file, type);
}
}

@ -0,0 +1,32 @@
package com.currency.appengine.controller.importFile.entity;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false)
public class MiniDataEntity {
@Excel(name = "邮件号码")
private String email;
@Excel(name = "寄件人姓名")
private String senderName;
@Excel(name = "寄件人电话")
private String senderPhone;
@Excel(name = "寄件人地址")
private String senderAddress;
@Excel(name = "收个人姓名")
private String recipientName;
@Excel(name = "收件人电话")
private String recipientPhone;
@Excel(name = "收件人地址")
private String recipientAddress;
}

@ -0,0 +1,108 @@
package com.currency.appengine.controller.importFile.entity;
import java.util.Date;
import java.math.BigDecimal;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Data;
/**
*
*/
@Data
public class MiniProductMaterialsImport {
/**
*
*/
@Excel(name = "产品代码", width = 10)
private String materialCode;
/**
*
*/
@Excel(name = "型材型号", width = 10)
private String profileModel;
/**
*
*/
@Excel(name = "物料名称", width = 10)
private String materialName;
/**
* (MM)
*/
@Excel(name = "规格型号(MM)", width = 10)
private String specification;
/**
*
*/
@Excel(name = "壁厚(mm)", width = 10)
private String thickness;
/**
* (kg/m)
*/
@Excel(name = "米重(kg/m)", width = 10)
private String weight;
/**
* /
*/
@Excel(name = "支/扎", width = 10)
private String piecesBundle;
/**
* /
*/
@Excel(name = "物料/产品分类", width = 10)
private String materialCategory;
/**
* (m)
*/
@Excel(name = "默认长度(m)", width = 10)
private String defaultLength;
/**
*
*/
@Excel(name = "包装方式", width = 10)
private String packagingMethod;
/**
*
*/
@Excel(name = "来源", width = 10)
private String source;
/**
* (01)
*/
@Excel(name = "是否启用", width = 10)
private String status;
/**
*
*/
@Excel(name = "设置安全库存", width = 10)
private String safetyStock;
/**
*
*/
@Excel(name = "库存单位", width = 10)
private String inventoryUnit;
/**
*
*/
@Excel(name = "单位", width = 10)
private String unit;
/**
*
*/
@Excel(name = "备注", width = 10)
private String remarks;
}

@ -0,0 +1,39 @@
package com.currency.appengine.controller.upload;
import com.currency.appengine.domain.upload.FileUpload;
import com.currency.appengine.service.upload.UploadService;
import com.currency.appengine.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@Api(tags="上传文件")
@RestController
@RequestMapping("/api/upload")
public class UploadController {
@Autowired
private UploadService uploadService;
@ApiOperation(value="上传",notes="响应文件地址")
@ApiImplicitParam(name = "file",value="文件",dataType = "Object")
@PostMapping("/file")
// @CheckToken
public Result uploadFile(HttpServletRequest request, FileUpload obj){
// String userId = StringUtil.objectToString(request.getAttribute("openid"));
// if(StringUtil.isBlank(userId)){
// return Result.fail(-2, "登录异常,请重新登录");
// }
// obj.setUserId(userId);
return uploadService.uploadFile(obj);
}
}

@ -0,0 +1,41 @@
package com.currency.appengine.controller.user;
import com.currency.appengine.service.user.UserService;
import com.currency.appengine.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
private UserService userService;
//验证注册
@PostMapping("/sms/validRegister")
public Result validRegister(@RequestBody Map<String, Object> map){
return userService.validRegister(map);
}
//手机号登录
@PostMapping("/sms/validLogin")
public Result validLogin(@RequestBody Map<String, Object> map){
return userService.validLogin(map);
}
//手机或邮箱密码登录
@PostMapping("/sms/validPwdLogin")
public Result validPwdLogin(@RequestBody Map<String, Object> map){
return userService.validPwdLogin(map);
}
}

@ -0,0 +1,19 @@
package com.currency.appengine.convenient.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FileUploadEntity {
private String fileCompleteFolder; //文件存储完整目录
private String filePath; //文件访问地址
private String fileFolder; //文件存储目录
private String fileName; //文件名
private long fileSize; //文件大小
private int pageNum; //页数
private Integer wayType; // 上传类型 1-oss 2-本地上传
}

@ -0,0 +1,276 @@
package com.currency.appengine.convenient.modules;
import com.aliyun.oss.OSSClient;
import com.currency.appengine.config.GlobalData;
import com.currency.appengine.convenient.entity.FileUploadEntity;
import com.currency.appengine.convenient.service.OSSConfigService;
import com.currency.appengine.enums.ParamCodeEnum;
import com.currency.appengine.handler.exception.MyException;
import com.currency.appengine.utils.StringUtil;
import com.currency.appengine.utils.file.WordToPdfUtil;
import com.currency.appengine.utils.generate.R;
import com.currency.appengine.utils.oss.AliyunOSSClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@Component
public class FileUploadModule {
private static Boolean DEFAULT_UPLOAD_MODE_BOOL = Boolean.FALSE; //文件上传方式(本地、阿里云OSS) 默认 false 上传本地
private static Boolean READ_FILE_PAGE_NUM_BOOL = Boolean.FALSE; //是否读取文件页数 默认 false
private static String FILE_FOLDER = null; //当前上传文件目录
private static String FILE_PATH = null; //当前文件访问地址
private static OSSClient ossClient = null;
private static String BACKET_NAME = null;
@Autowired
GlobalData globalData;
@Autowired
private OSSConfigService ossConfigService;
/**
*
* @param configs [0]
* @return
*/
public FileUploadModule config(Boolean... configs) {
if (Objects.nonNull(configs)) {
Boolean[] bools = Arrays.asList(configs).toArray(new Boolean[0]);
switch (bools.length) {
case 1:
READ_FILE_PAGE_NUM_BOOL = bools[0];
break;
}
}
this.init();
return this;
}
/**
*
*
* @param file
* @param fileName
*/
public FileUploadEntity upload(MultipartFile file, String fileName) {
return this.run(file, null, fileName, null);
}
public FileUploadEntity upload(MultipartFile file, String fileName, Integer wayType) {
if (wayType == null || (wayType != 1 && wayType != 2)) wayType = null;
return this.run(file, null, fileName, null);
}
/**
*
*
* @param file
* @param fileFolder fileFolder (fileFolder /ossFileFolder ) + fileFolder
* @param fileName null
*/
public FileUploadEntity upload(MultipartFile file, String fileFolder, String fileName) {
return this.run(file, fileFolder, fileName, null);
}
public FileUploadEntity upload(MultipartFile file, String fileFolder, String fileName, Integer wayType) {
if (wayType == null || (wayType != 1 && wayType != 2)) wayType = null;
return this.run(file, fileFolder, fileName, wayType);
}
private FileUploadEntity run(MultipartFile file, String fileFolder, String fileName, Integer wayType) {
if (Objects.isNull(file)) {
throw new MyException("上传失败,文件不能为空");
}
String tempFileFolder = StringUtil.notBlank(fileFolder) ? (FILE_FOLDER + fileFolder) : FILE_FOLDER;
if (StringUtil.isBlank(fileName)) {
fileName = this.getNewFileName(file.getOriginalFilename());
}
try {
Boolean isOss = DEFAULT_UPLOAD_MODE_BOOL;
if (wayType != null) {
if (wayType == 1) {
isOss = true;
} else {
isOss = false;
}
}
if (isOss) {
wayType = 1;
AliyunOSSClientUtil.uploadFile(ossClient, file, fileName, BACKET_NAME, tempFileFolder);
} else {
wayType = 2;
File fileDir = new File(tempFileFolder);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
InputStream in = file.getInputStream();
FileOutputStream out = new FileOutputStream(tempFileFolder + fileName);
byte buffer[] = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
out.close();
}
int pageNum = -1;
if (READ_FILE_PAGE_NUM_BOOL) {
if (StringUtil.isBlank(FILE_PATH)) {
throw new MyException("请先后台配置本地存储文件访问地址(filePath)或阿里云存储文件访问地址(ossFilePath)");
}
pageNum = WordToPdfUtil.documents4jWordToPdf(StringUtil.isBlank(fileFolder) ? (FILE_PATH + fileName) : (FILE_PATH + fileFolder + fileName));
}
return new FileUploadEntity(tempFileFolder+fileName, StringUtil.isBlank(fileFolder) ? (FILE_PATH) : (FILE_PATH + fileFolder), tempFileFolder, fileName, file.getSize(), pageNum, wayType);
} catch (Exception e) {
e.printStackTrace();
throw new MyException("上传失败");
}
}
public void delFile(String fileFolder, String fileName){
this.delDeal(fileFolder, fileName, null);
}
public void delFile(String fileName){
String fileFolder = globalData.getFileFolder();
String filePath = globalData.getFilePath();
fileName = fileName.replaceAll(filePath,"");
this.delDeal(fileFolder, fileName, null);
}
public void delFile(String fileFolder, String fileName, Integer wayType){
if (wayType == null || (wayType != 1 && wayType != 2)) wayType = null;
this.delDeal(fileFolder, fileName, wayType);
}
public Boolean delFile(String fileName, Integer wayType){
if (!Objects.nonNull(fileName)) {
return false;
}
String fileFolder = globalData.getFileFolder();
String filePath = globalData.getFilePath();
fileName = fileName.replaceAll(filePath,"");
if (wayType == null || (wayType != 1 && wayType != 2)) wayType = null;
this.delDeal(fileFolder, fileName, wayType);
return true;
}
public Boolean delFileByFilePath(String filePath, Integer wayType){
if (!Objects.nonNull(filePath)) {
return false;
}
if (wayType == null || (wayType != 1 && wayType != 2)) wayType = null;
this.delDealByPath(filePath, wayType);
return true;
}
public void delDealByPath(String filePath, Integer wayType) {
Boolean isOss = DEFAULT_UPLOAD_MODE_BOOL;
if (wayType != null) {
if (wayType == 1) {
isOss = true;
} else {
isOss = false;
}
}
if (isOss) {
if(ossClient == null)
this.init();
AliyunOSSClientUtil.deleteFileByPath(ossClient, BACKET_NAME, filePath);
}else{
File file = new File(filePath);
if (file.exists()) {
file.delete();
}
}
}
public void delDeal(String fileFolder, String fileName, Integer wayType) {
Boolean isOss = DEFAULT_UPLOAD_MODE_BOOL;
if (wayType != null) {
if (wayType == 1) {
isOss = true;
} else {
isOss = false;
}
}
if (isOss) {
if(ossClient == null)
this.init();
AliyunOSSClientUtil.deleteFile(ossClient, BACKET_NAME, fileFolder, fileName);
}else{
File file = new File(fileFolder + fileName);
if (file.exists()) {
file.delete();
}
}
}
public void delRicTextDeal(String replacePre, List<String> urls, Integer wayType) {
for (int i = 0, len = urls.size(); i < len; i ++) {
String uri = urls.get(i).replace(replacePre, "");
if (DEFAULT_UPLOAD_MODE_BOOL) {
if(ossClient == null)
this.init();
AliyunOSSClientUtil.deleteFileByPath(ossClient, BACKET_NAME, uri);
} else {
File file = new File(uri);
if (file.exists()) {
file.delete();
}
}
}
return;
}
private void init() {
String fileUploadMode = globalData.getSysParams(ParamCodeEnum.fileUploadMode.toString());
if (StringUtil.notBlank(fileUploadMode) && "ON".equals(fileUploadMode)) {
FILE_FOLDER = globalData.getSysParams(ParamCodeEnum.ossFileFolder.toString());
FILE_PATH = globalData.getSysParams(ParamCodeEnum.ossFilePath.toString());
DEFAULT_UPLOAD_MODE_BOOL = Boolean.TRUE;
ossClient = ossConfigService.getOSSClient();
BACKET_NAME = ossConfigService.getBacketName();
} else {
FILE_FOLDER = globalData.getSysParams(ParamCodeEnum.fileFolder.toString());
FILE_PATH = globalData.getSysParams(ParamCodeEnum.filePath.toString());
DEFAULT_UPLOAD_MODE_BOOL = Boolean.FALSE;
}
if (StringUtil.isBlank(FILE_FOLDER)) {
throw new MyException("请先后台配置上传本地存储目录(fileFolder)或上传阿里云存储目录(ossFileFolder)");
}
}
private String getNewFileName(String fileName) {
// return R.UU16() + '.' + fileName.split("\\.")[1];
String[] ar = fileName.split("\\.");
return R.UU16() + '.' + ar[ar.length - 1];
}
public static void main(String[] args) {
}
}

@ -0,0 +1,13 @@
package com.currency.appengine.convenient.service;
import com.aliyun.oss.OSSClient;
import java.util.Map;
public interface OSSConfigService {
Map<String, Object> getOSSConfig();
OSSClient getOSSClient();
String getBacketName();//BACKET_NAME
}

@ -0,0 +1,66 @@
package com.currency.appengine.convenient.service.impl;
import com.aliyun.oss.OSSClient;
import com.currency.appengine.config.GlobalData;
import com.currency.appengine.convenient.service.OSSConfigService;
import com.currency.appengine.utils.oss.AliyunOSSClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service(value = "oSSConfigServiceImpl")
public class OSSConfigServiceImpl implements OSSConfigService {
private static Logger logger = LoggerFactory.getLogger(OSSConfigServiceImpl.class);
@Autowired
GlobalData globalData;
private Map<String, Object> config = null;
@Override
public Map<String, Object> getOSSConfig() {
return GlobalData.sysParamsMap;
}
@Override
public OSSClient getOSSClient() {
Map<String,Object> oosConfig = getOSSConfig();
setConfig(oosConfig);
String ENDPOINT = (String)oosConfig.get("ENDPOINT");
String ACCESS_KEY_ID = (String)oosConfig.get("ACCESS_KEY_ID");
String ACCESS_KEY_SECRET = (String)oosConfig.get("ACCESS_KEY_SECRET");
// String BACKET_NAME = oosConfig.get("BACKET_NAME");
return AliyunOSSClientUtil.getOSSClient(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
}
@Override
public String getBacketName() {
if(config!=null)
return (String)config.get("BACKET_NAME");
return null;
}
public Map<String, Object> getConfig() {
return config;
}
public void setConfig(Map<String, Object> config) {
this.config = config;
}
}

@ -0,0 +1,16 @@
package com.currency.appengine.domain;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.util.Map;
@Data
@Setter
@Getter
public class LocalHttpResponse {
private Integer code;
private String msg;
private Map data;
}

@ -0,0 +1,41 @@
package com.currency.appengine.domain.export;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserInfoExport {
/**
*
*/
@Excel(name = "头像", width = 20, orderNum = "1")
private String userImg; // 头像
/**
* ID
*/
@Excel(name = "用户ID", width = 20, orderNum = "5")
private String userId; // 用户ID
/**
*
*/
@Excel(name = "昵称", width = 20, orderNum = "10")
private String nickName; // 昵称
/**
*
*/
@Excel(name = "创建时间", width = 20, orderNum = "15")
private String createTime; // 创建时间
/**
*
*/
@Excel(name = "状态", replace = {"禁用_0","正常_1"}, width = 20, orderNum = "20")
private String status;
}

@ -0,0 +1,10 @@
package com.currency.appengine.domain.system;
import java.util.List;
public class RoleListItem {
private String id;
private String label;
private String alias;
private List<RoleListItem> children;
}

@ -0,0 +1,29 @@
package com.currency.appengine.domain.system;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Router {
@JsonIgnore
private String menuId;
@JsonIgnore
private String createTime;
private String parent;
private String name;
private String path;
private String component;
private String redirect;
private RouterMeta meta;
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<Router> children;
}

@ -0,0 +1,19 @@
package com.currency.appengine.domain.system;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RouterMeta {
private String title;
private boolean hidden;
private String affix;
private String icon;
private String type;
private boolean hiddenBreadcrumb;
private String active;
private String color;
}

@ -0,0 +1,18 @@
package com.currency.appengine.domain.system;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
@Data
public class SysParam {
private Integer sysParamId;
private String paramCode;
private String paramNm;
private String paramValue;
private String remark;
private String useFg;
private String sysFg;
}

@ -0,0 +1,23 @@
package com.currency.appengine.domain.system;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SysRole {
private String parentId;
private String id;
private String label;
private String alias;
private String sort;
@JsonInclude(JsonInclude.Include.NON_NULL)
private List<SysRole> children;
}

@ -0,0 +1,22 @@
package com.currency.appengine.domain.system;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SysUser {
private String id;
private String userName; // 账号
@JsonIgnore
private String password;
private String name; // 昵称
private String date;
private String group; // 角色组
private String groupName; // 角色组中文名
}

@ -0,0 +1,29 @@
package com.currency.appengine.domain.upload;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.multipart.MultipartFile;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class FileData {
private String name;
private String fileName;
private long size;
private long chunkSize;
private long currentChunkSize;
private long totalChunks;
private long chunkNumber;
private MultipartFile file;
private String userId;
private String teamId;
private String season;
private String matchAlias;
private String identifier;
private String relativePath;
}

@ -0,0 +1,20 @@
package com.currency.appengine.domain.upload;
import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@Data
public class FileUpload {
private String type;
private String fileName;
private String userId;
private MultipartFile[] file;
public void setFileToList(List<MultipartFile> multipartFileList) {
this.file = multipartFileList.toArray(new MultipartFile[multipartFileList.size()]);
}
}

@ -0,0 +1,12 @@
package com.currency.appengine.domain.upload;
import lombok.Data;
@Data
public class MiniUploadFile {
private Long id;
private String fileName;
private String filePath;
private Integer wayType;
private String useStatus;
}

@ -0,0 +1,19 @@
package com.currency.appengine.dto;
import lombok.Data;
/**
* TODO
*
* @Author: kang
* @Date: 2022/11/23/15:56
*/
@Data
public class CreateDeploymentDTO {
private String uid;
private String resultsUrl;
private String returnUrl;
private String track;
private String pythonUrl;
private String containerResultsUrl;
}

@ -0,0 +1,15 @@
package com.currency.appengine.dto;
import lombok.Data;
/**
* TODO
*
* @Author: kang
* @Date: 2022/11/23/16:33
*/
@Data
public class DeleteDeploymentDTO {
private String uid;
private String track;
}

@ -0,0 +1,28 @@
package com.currency.appengine.enums;
public enum CodeEnum {
CustomerCode("客户编码", "CustomerCode"), // 客户编码
SupplierCode("供应商编码", "SupplierCode"), // 供应商编码
SalesOrderNumber("销售单号", "SalesOrderNumber"), // 销售单号
OrderNumber("订单编号", "OrderNumber"), // 订单编号
ProductionPlan("生产计划", "ProductionPlan"), // 生产计划
ProductionSchedulingNumber("排产编号", "ProductionSchedulingNumber"), // 排产编号
ProductionOrderNumber("排产单号", "ProductionOrderNumber"), // 排产单号
PurchaseNumber("采购编号", "PurchaseNumber"); // 采购编号
private String tip;
private String type;
CodeEnum(String tip, String type) {
this.tip = tip;
this.type = type;
}
public String type() {
return type;
}
public String tip() {
return tip;
}
}

@ -0,0 +1,49 @@
package com.currency.appengine.enums;
import java.util.HashMap;
import java.util.Map;
public enum EnvEnum {
pageSize("默认分页大小","project.list.pageSize.default"),
env("当前环境","project.env"),
apiPackage("自动路由地址","project.api-package"),
pswdKey("数据库密码加密key","project.pswd-key"),
frontAesKey("前端请求密码加密key","project.front-aes-key"),
resetPasswordAesKey("重置密码加密key","project.reset-password-aes-key"),
inviteuserAesKey("邀请用户加密key","project.inviteuser-aes-key"),
smsSecretId("短信应用id","project.config.tencent-cloud.sms.SecretId"),
smsSecretKey("短信应用密钥","project.config.tencent-cloud.sms.SecretKey"),
smsSdkAppID("短信应用sdkid","project.config.tencent-cloud.sms.SDKAppID"),
smsSignName("短信应用签名","project.config.tencent-cloud.sms.signName");
private String key;
private String desc;
private static final Map<String, String> KEYS = new HashMap<>();
static {
for (EnvEnum envEnum : values()) {
KEYS.put(envEnum.name(), envEnum.key);
}
}
EnvEnum(String desc, String key) {
this.key = key;
this.desc = desc;
}
public String key() {
return key;
}
public String desc() {
return desc;
}
public static String getKey(String name) {
return KEYS.get(name).toString();
}
}

@ -0,0 +1,13 @@
package com.currency.appengine.enums;
public enum ParamCodeEnum {
fileUploadMode,//文件上传方式 OFF 本地/ON 阿里云
fileFolder, //文件上传目录
filePath, //文件访问地址
ossFileFolder, //阿里云存储文件上传目录
ossFilePath, //阿里云存储文件访问地址
}

@ -0,0 +1,31 @@
package com.currency.appengine.enums;
import com.currency.appengine.utils.I18NUtil;
import com.currency.appengine.utils.StringUtil;
public enum ResultCode {
SUCCESS(0, "result.success"),
FAIL(-1, "result.fail"),
NOT_TOKEN(-2, "result.not_token"),
TOKEN_IS_INVALID(-3, "result.token_is_invalid"),
NOT_RWALNAME_AUTHENT(-10, "result.not_rwalname_authent"),
SYSTEM_ERROR(-10000, "result.system_error"),
PARAM_IS_INVALID(-10001, "result.param_is_invalid");
private Integer code;
private String message;
ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer code() {
return code;
}
public String message() {
return StringUtil.notEmpty(message) ?I18NUtil.getMessage(message):message;
}
}

@ -0,0 +1,17 @@
package com.currency.appengine.enums;
public enum SmsConfigEnum {
/* public static SmsConfigEnum transform(String name){
SmsConfigEnum[] values = SmsConfigEnum.values();
for(SmsConfigEnum value:values){
if(value.name().equals(name)){
return value;
}
}
return null;
}*/
}

@ -0,0 +1,16 @@
package com.currency.appengine.export;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public interface ExportServer {
// 默认导出
void exportDefaultServer(String title, Class clazz, Map map, int method);
// 自定义样式导出
void exportCustomStyleServer(String title, Class clazz, Map map, int method);
void exportExpertWord(String json, HttpServletRequest request, HttpServletResponse response);
}

@ -0,0 +1,194 @@
package com.currency.appengine.export.impl;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.handler.inter.IExcelExportServer;
import com.currency.appengine.export.ExportServer;
import com.currency.appengine.service.export.ExportDataPageService;
import com.currency.appengine.utils.JsonUtil;
import com.currency.appengine.utils.WordUtil;
import com.currency.appengine.utils.export.poi.ExcelExportUtil;
import com.currency.appengine.utils.export.poi.PoiUtil;
import com.currency.appengine.utils.export.poi.WriteExcelDataDelegated;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.ssssssss.magicapi.core.context.RequestContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Service
public class ExportServerImpl<T> implements ExportServer {
final static int SIZE = 10000;
// @Autowired
// private ExportMapper exportMapper;
@Autowired
private ExportDataPageService exportDataPageService;
@Override
public void exportDefaultServer(String title, Class clazz, Map map, int method) {
new MyExcelExportServer<T>(map, method).runExport(title, clazz);
}
@Override
public void exportCustomStyleServer(String title, Class clazz, Map map, int method) {
new MyExcelExportPoiServer<T>(map, method).runExport(title, clazz);
}
@Override
public void exportExpertWord(String json, HttpServletRequest request, HttpServletResponse response) {
// 读取模板
ClassPathResource classPathResource = new ClassPathResource("templates/expertWord.docx");
InputStream templatePath = null;
try {
templatePath = classPathResource.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
// 实体转Map
Map map = JsonUtil.parseObject(json, Map.class);
// 导出word
WordUtil.exportWord(map, templatePath, System.getProperty("java.io.tmpdir") + File.separator, request, response);
}
class MyExcelExportServer<T> {
IExcelExportServer server;
Map map;
int method;
List<T> temps;
public MyExcelExportServer(Map map, int method) {
map.put("size", SIZE);
this.map = map;
this.method = method;
this.server = myExportServer();
}
public IExcelExportServer myExportServer() {
int size = Integer.valueOf(this.map.get("size") + "");
return new IExcelExportServer() {
Map<String, Object> params = map;
@Override
// 分页查询 obj 总页数 page 第几页
public List<Object> selectListForExcelExport(Object obj, int page) {
params.put("limit", (page - 1) * size);
// System.out.println("=====>>>" + params);
List<T> maps = getPage(params);
List<Object> list = new ArrayList<>();
// list.addAll(JsonUtil.myParseList(maps, Customer.class));
if(!CollectionUtils.isEmpty(maps))
temps = maps;
list.addAll(maps);
return list;
}
};
}
private List<T> getPage(Map<String, Object> params) {
return (List<T>) exportDataPageService.findPage(params, this.method);
}
public MyExcelExportServer<T> runExport(String title, Class claz) {
int count = exportDataPageService.findCount(this.map, this.method);//Integer.valueOf(this.map.get("count") + "");
this.myExportBigEasyPoi(title, claz, this.server, count);
return this;
}
/*public MyExcelExportServer<T> runExport2(String title, Class claz) {
int count = Integer.valueOf(this.map.get("count") + "");
int page = 1;
int var6 = page + 1;
IExcelExportServer iExcelExportServer = this.myExportServer();
for (List list =iExcelExportServer.selectListForExcelExport(count, page); list != null && list.size() > 0; list = iExcelExportServer.selectListForExcelExport(count, var6++)) {
if (!CollectionUtils.isEmpty(list)) {
AlibabaEasyExcelUtil.export(list, claz, title);
}
}
return this;
}*/
private void myExportBigEasyPoi(String title, Class claz, IExcelExportServer iExcelExportServer, int count) {
ExportParams exportParams = new ExportParams(title, title);
ExcelExportUtil.exportBigEasyPoi(this.getResponse(), exportParams, title, claz, iExcelExportServer, count);
}
private HttpServletResponse getResponse() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return requestAttributes instanceof ServletRequestAttributes ? ((ServletRequestAttributes) requestAttributes).getResponse() : RequestContext.getHttpServletResponse().getResponse();
}
}
class MyExcelExportPoiServer<T> {
Map map;
int method;
public MyExcelExportPoiServer(Map map, int method) {
map.put("size", SIZE);
this.map = map;
this.method = method;
}
public MyExcelExportPoiServer<T> runExport(String title, Class claz) {
int count = exportDataPageService.findCount(this.map, this.method);//Integer.valueOf(this.map.get("count") + "");
this.myExportBigPoi(title, claz, count);
return this;
}
private void myExportBigPoi(String title, Class claz, int count) {
try {
PoiUtil.exportExcelToWebsite(this.getResponse(), count, title, claz, new WriteExcelDataDelegated() {
@Override
public void writeExcelData(SXSSFWorkbook wb, SXSSFSheet eachSheet, Integer startRowCount, Integer endRowCount, Integer currentPage, Integer pageSize) throws Exception {
//此处进行分批次查询,
map.put("limit", (currentPage) * pageSize);
exportDataPageService.setWorkbook(wb, eachSheet, startRowCount, endRowCount, getPage(map), method);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private List<T> getPage(Map<String, Object> params) {
return (List<T>) exportDataPageService.findPage(params, this.method);
}
private HttpServletResponse getResponse() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return requestAttributes instanceof ServletRequestAttributes ? ((ServletRequestAttributes) requestAttributes).getResponse() : RequestContext.getHttpServletResponse().getResponse();
}
}
}

@ -0,0 +1,90 @@
package com.currency.appengine.fastloader.common;
/**
*
*
* @author
*
*/
public interface HttpStatus
{
/**
*
*/
public static final int SUCCESS = 200;
/**
*
*/
public static final int CREATED = 201;
/**
*
*/
public static final int ACCEPTED = 202;
/**
*
*/
public static final int NO_CONTENT = 204;
/**
*
*/
public static final int MOVED_PERM = 301;
/**
*
*/
public static final int SEE_OTHER = 303;
/**
*
*/
public static final int NOT_MODIFIED = 304;
/**
*
*/
public static final int BAD_REQUEST = 400;
/**
*
*/
public static final int UNAUTHORIZED = 401;
/**
* 访
*/
public static final int FORBIDDEN = 403;
/**
*
*/
public static final int NOT_FOUND = 404;
/**
* http
*/
public static final int BAD_METHOD = 405;
/**
*
*/
public static final int CONFLICT = 409;
/**
*
*/
public static final int UNSUPPORTED_TYPE = 415;
/**
*
*/
public static final int ERROR = 500;
/**
*
*/
public static final int NOT_IMPLEMENTED = 501;
}

@ -0,0 +1,323 @@
package com.currency.appengine.fastloader.util;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class DateUtil {
// 获取当天的开始时间
public static Date getDayBegin() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
// 获取当天的结束时间
public static Date getDayEnd() {
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
return cal.getTime();
}
// 获取昨天的开始时间
public static Date getBeginDayOfYesterday() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayBegin());
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
// 获取昨天的结束时间
public static Date getEndDayOfYesterDay() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayEnd());
cal.add(Calendar.DAY_OF_MONTH, -1);
return cal.getTime();
}
// 获取明天的开始时间
public static Date getBeginDayOfTomorrow() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayBegin());
cal.add(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
// 获取明天的结束时间
public static Date getEndDayOfTomorrow() {
Calendar cal = new GregorianCalendar();
cal.setTime(getDayEnd());
cal.add(Calendar.DAY_OF_MONTH, 1);
return cal.getTime();
}
// 获取本周的开始时间
@SuppressWarnings("unused")
public static Date getBeginDayOfWeek() {
Date date = new Date();
if (date == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek);
return getDayStartTime(cal.getTime());
}
// 获取本周的结束时间
public static Date getEndDayOfWeek() {
Calendar cal = Calendar.getInstance();
cal.setTime(getBeginDayOfWeek());
cal.add(Calendar.DAY_OF_WEEK, 6);
Date weekEndSta = cal.getTime();
return getDayEndTime(weekEndSta);
}
// 获取上周的开始时间
@SuppressWarnings("unused")
public static Date getBeginDayOfLastWeek() {
Date date = new Date();
if (date == null) {
return null;
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek - 7);
return getDayStartTime(cal.getTime());
}
// 获取上周的结束时间
public static Date getEndDayOfLastWeek() {
Calendar cal = Calendar.getInstance();
cal.setTime(getBeginDayOfLastWeek());
cal.add(Calendar.DAY_OF_WEEK, 6);
Date weekEndSta = cal.getTime();
return getDayEndTime(weekEndSta);
}
// 获取本月的开始时间
public static Date getBeginDayOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(getNowYear(), getNowMonth() - 1, 1);
return getDayStartTime(calendar.getTime());
}
// 获取本月的结束时间
public static Date getEndDayOfMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(getNowYear(), getNowMonth() - 1, 1);
int day = calendar.getActualMaximum(5);
calendar.set(getNowYear(), getNowMonth() - 1, day);
return getDayEndTime(calendar.getTime());
}
// 获取上月的开始时间
public static Date getBeginDayOfLastMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(getNowYear(), getNowMonth() - 2, 1);
return getDayStartTime(calendar.getTime());
}
// 获取上月的结束时间
public static Date getEndDayOfLastMonth() {
Calendar calendar = Calendar.getInstance();
calendar.set(getNowYear(), getNowMonth() - 2, 1);
int day = calendar.getActualMaximum(5);
calendar.set(getNowYear(), getNowMonth() - 2, day);
return getDayEndTime(calendar.getTime());
}
// 获取本年的开始时间
public static Date getBeginDayOfYear() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, getNowYear());
// cal.set
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DATE, 1);
return getDayStartTime(cal.getTime());
}
// 获取本年的结束时间
public static Date getEndDayOfYear() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, getNowYear());
cal.set(Calendar.MONTH, Calendar.DECEMBER);
cal.set(Calendar.DATE, 31);
return getDayEndTime(cal.getTime());
}
// 获取某个日期的开始时间
public static Timestamp getDayStartTime(Date d) {
Calendar calendar = Calendar.getInstance();
if (null != d)
calendar.setTime(d);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 0,
0, 0);
calendar.set(Calendar.MILLISECOND, 0);
return new Timestamp(calendar.getTimeInMillis());
}
// 获取某个日期的结束时间
public static Timestamp getDayEndTime(Date d) {
Calendar calendar = Calendar.getInstance();
if (null != d)
calendar.setTime(d);
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), 23,
59, 59);
calendar.set(Calendar.MILLISECOND, 999);
return new Timestamp(calendar.getTimeInMillis());
}
// 获取今年是哪一年
public static Integer getNowYear() {
Date date = new Date();
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(date);
return Integer.valueOf(gc.get(1));
}
// 获取本月是哪一月
public static int getNowMonth() {
Date date = new Date();
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(date);
return gc.get(2) + 1;
}
// 两个日期相减得到的天数
public static int getDiffDays(Date beginDate, Date endDate) {
if (beginDate == null || endDate == null) {
throw new IllegalArgumentException("getDiffDays param is null!");
}
long diff = (endDate.getTime() - beginDate.getTime()) / (1000 * 60 * 60 * 24);
int days = Long.valueOf(diff).intValue();
return days;
}
// 两个日期相减得到的毫秒数
public static long dateDiff(Date beginDate, Date endDate) {
long date1ms = beginDate.getTime();
long date2ms = endDate.getTime();
return date2ms - date1ms;
}
// 获取两个日期中的最大日期
public static Date max(Date beginDate, Date endDate) {
if (beginDate == null) {
return endDate;
}
if (endDate == null) {
return beginDate;
}
if (beginDate.after(endDate)) {
return beginDate;
}
return endDate;
}
// 获取两个日期中的最小日期
public static Date min(Date beginDate, Date endDate) {
if (beginDate == null) {
return endDate;
}
if (endDate == null) {
return beginDate;
}
if (beginDate.after(endDate)) {
return endDate;
}
return beginDate;
}
// 返回某月该季度的第一个月
public static Date getFirstSeasonDate(Date date) {
final int[] SEASON = { 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4 };
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int sean = SEASON[cal.get(Calendar.MONTH)];
cal.set(Calendar.MONTH, sean * 3 - 3);
return cal.getTime();
}
// 返回某个日期下几天的日期
public static Date getNextDay(Date date, int i) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.DATE, cal.get(Calendar.DATE) + i);
return cal.getTime();
}
// 返回某个日期前几天的日期
public static Date getFrontDay(Date date, int i) {
Calendar cal = new GregorianCalendar();
cal.setTime(date);
cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);
return cal.getTime();
}
// 获取某年某月到某年某月按天的切片日期集合(间隔天数的集合)
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List getTimeList(int beginYear, int beginMonth, int endYear, int endMonth, int k) {
List list = new ArrayList();
if (beginYear == endYear) {
for (int j = beginMonth; j <= endMonth; j++) {
list.add(getTimeList(beginYear, j, k));
}
} else {
{
for (int j = beginMonth; j < 12; j++) {
list.add(getTimeList(beginYear, j, k));
}
for (int i = beginYear + 1; i < endYear; i++) {
for (int j = 0; j < 12; j++) {
list.add(getTimeList(i, j, k));
}
}
for (int j = 0; j <= endMonth; j++) {
list.add(getTimeList(endYear, j, k));
}
}
}
return list;
}
// 获取某年某月按天切片日期集合(某个月间隔多少天的日期集合)
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List getTimeList(int beginYear, int beginMonth, int k) {
List list = new ArrayList();
Calendar begincal = new GregorianCalendar(beginYear, beginMonth, 1);
int max = begincal.getActualMaximum(Calendar.DATE);
for (int i = 1; i < max; i = i + k) {
list.add(begincal.getTime());
begincal.add(Calendar.DATE, k);
}
begincal = new GregorianCalendar(beginYear, beginMonth, max);
list.add(begincal.getTime());
return list;
}
}

@ -0,0 +1,78 @@
package com.currency.appengine.fastloader.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.*;
/**
*
* @author
*
*/
public class FileInfoUtils {
private final static Logger logger = LoggerFactory.getLogger(FileInfoUtils.class);
/**
*
*
* @param
* @param folder
*/
public static String merge(String file, String folder, String filename){
//默认合并成功
String rlt = "200";
try {
//先判断文件是否存在
if(fileExists(file)) {
//文件已存在
rlt = "300";
}else {
//不存在的话,进行合并
Files.createFile(Paths.get(file));
Files.list(Paths.get(folder))
.filter(path -> !path.getFileName().toString().equals(filename))
.sorted((o1, o2) -> {
String p1 = o1.getFileName().toString();
String p2 = o2.getFileName().toString();
int i1 = p1.lastIndexOf("-");
int i2 = p2.lastIndexOf("-");
return Integer.valueOf(p2.substring(i2)).compareTo(Integer.valueOf(p1.substring(i1)));
})
.forEach(path -> {
try {
//以追加的形式写入文件
Files.write(Paths.get(file), Files.readAllBytes(path), StandardOpenOption.APPEND);
//合并后删除该块
Files.delete(path);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
});
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
//合并失败
rlt = "400";
}
return rlt;
}
/**
*
* @param file
* @return
*/
public static boolean fileExists(String file) {
boolean fileExists = false;
Path path = Paths.get(file);
fileExists = Files.exists(path,new LinkOption[]{ LinkOption.NOFOLLOW_LINKS});
return fileExists;
}
}

@ -0,0 +1,41 @@
package com.currency.appengine.fastloader.util;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
/**
* Servlet
*
* @author
*/
public class ServletUtils {
/**
*
* @param request http
* @param response http
* @param fileName
*/
public static void setFileDownloadHeader(HttpServletRequest request,
HttpServletResponse response, String fileName) {
try {
String encodedFileName = null;
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 != agent.indexOf("MSIE")) {
encodedFileName = URLEncoder.encode(fileName, "UTF-8");
} else if (null != agent && -1 != agent.indexOf("Mozilla")) {
encodedFileName = new String(fileName.getBytes("UTF-8"),
"iso-8859-1");
} else {
encodedFileName = URLEncoder.encode(fileName, "UTF-8");
}
response.setHeader("Content-Disposition", "attachment; filename=\""
+ encodedFileName + "\"");
} catch (Exception e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,149 @@
package com.currency.appengine.fastloader.util;
/**
* uuid
*
* @author
*/
public class SnowflakeIdWorker {
// ==============================Fields===========================================
/** 开始时间截 (2015-01-01) */
private final long twepoch = 1420041600000L;
/** 机器id所占的位数 */
private final long workerIdBits = 5L;
/** 数据标识id所占的位数 */
private final long datacenterIdBits = 5L;
/** 支持的最大机器id结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
/** 支持的最大数据标识id结果是31 */
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
/** 序列在id中占的位数 */
private final long sequenceBits = 12L;
/** 机器ID向左移12位 */
private final long workerIdShift = sequenceBits;
/** 数据标识id向左移17位(12+5) */
private final long datacenterIdShift = sequenceBits + workerIdBits;
/** 时间截向左移22位(5+5+12) */
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
/** 生成序列的掩码这里为4095 (0b111111111111=0xfff=4095) */
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
/** 工作机器ID(0~31) */
private long workerId;
/** 数据中心ID(0~31) */
private long datacenterId;
/** 毫秒内序列(0~4095) */
private long sequence = 0L;
/** 上次生成ID的时间截 */
private long lastTimestamp = -1L;
// ==============================Constructors=====================================
/**
*
*
* @param workerId
* ID (0~31)
* @param datacenterId
* ID (0~31)
*/
public SnowflakeIdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(
String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(
String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
// ==============================Methods==========================================
/**
* ID (线)
*
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
// 如果当前时间小于上一次ID生成的时间戳说明系统时钟回退过这个时候应当抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format(
"Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
// 如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
// 毫秒内序列溢出
if (sequence == 0) {
// 阻塞到下一个毫秒,获得新的时间戳
timestamp = tilNextMillis(lastTimestamp);
}
}
// 时间戳改变,毫秒内序列重置
else {
sequence = 0L;
}
// 上次生成ID的时间截
lastTimestamp = timestamp;
// 移位并通过或运算拼到一起组成64位的ID
return ((timestamp - twepoch) << timestampLeftShift) //
| (datacenterId << datacenterIdShift) //
| (workerId << workerIdShift) //
| sequence;
}
/**
*
*
* @param lastTimestamp
* ID
* @return
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
*
*
* @return ()
*/
protected long timeGen() {
return System.currentTimeMillis();
}
/**
* UUID
*
* @return
*/
public static String getUUID() {
SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0, 0);
long id = idWorker.nextId();
return String.valueOf(id);
}
}

@ -0,0 +1,45 @@
package com.currency.appengine.handler;
import com.currency.appengine.annotation.NoResult;
import com.currency.appengine.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@RestControllerAdvice(basePackages = "com.currency.appengine.controller")
public class ControllerResponseHandler implements ResponseBodyAdvice<Object> {
private static Logger log = LoggerFactory.getLogger(ControllerResponseHandler.class);
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if(request.getURI().toString().indexOf("/notify/order")!=-1 ||
request.getURI().toString().indexOf("/kaptcha")!=-1
){
return body;
}
if (returnType.getMethodAnnotation(NoResult.class) != null) {
return body;
}
if (!(body instanceof Result)) {
body = success(body);
}
return body;
}
private <T> Result<T> success(T data) {
return Result.suc(data);
}
}

@ -0,0 +1,119 @@
package com.currency.appengine.handler;
import com.currency.appengine.annotation.CustomParam;
import com.currency.appengine.utils.ObjectMapperUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.annotation.ValueConstants;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@Slf4j
public class CustomMethodArgumentResolver implements HandlerMethodArgumentResolver {
private static final String POST = "post";
private static final String APPLICATION_JSON = "application/json";
/**
*
*
* @param parameter the method parameter to check
* @return {@code true} if this resolver supports the supplied parameter;
* {@code false} otherwise
*/
@Override
public boolean supportsParameter(MethodParameter parameter) {
// 只处理带有@CustomParam注解的参数
return parameter.hasParameterAnnotation(CustomParam.class);
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
String contentType = Objects.requireNonNull(servletRequest).getContentType();
if (contentType == null || !contentType.contains(APPLICATION_JSON)) {
log.error("解析参数异常contentType需为{}", APPLICATION_JSON);
throw new RuntimeException("解析参数异常contentType需为application/json");
}
if (!POST.equalsIgnoreCase(servletRequest.getMethod())) {
log.error("解析参数异常请求类型必须为post");
throw new RuntimeException("解析参数异常请求类型必须为post");
}
return bindRequestParams(parameter, servletRequest);
}
private Object bindRequestParams(MethodParameter parameter, HttpServletRequest servletRequest) {
CustomParam customParam = parameter.getParameterAnnotation(CustomParam.class);
Class<?> parameterType = parameter.getParameterType();
String requestBody = getRequestBody(servletRequest);
Map<String, Object> params = ObjectMapperUtil.str2Obj(requestBody, new TypeReference<Map<String, Object>>() {
});
params = MapUtils.isEmpty(params) ? new HashMap<>(0) : params;
String name = StringUtils.isBlank(customParam.value()) ? parameter.getParameterName() : customParam.value();
Object value = params.get(name);
if (parameterType.equals(String.class)) {
if (value==null || StringUtils.isBlank(String.valueOf(value))) {
log.error("参数解析异常,String类型参数不能为空");
throw new RuntimeException("参数解析异常,String类型参数不能为空");
}
}
if (customParam.required()) {
if (value == null) {
log.error("参数解析异常,require=true,值不能为空");
throw new RuntimeException("参数解析异常,require=true,值不能为空");
}
} else {
if (customParam.defaultValue().equals(ValueConstants.DEFAULT_NONE)) {
log.error("参数解析异常,require=false,必须指定默认值");
throw new RuntimeException("参数解析异常,require=false,必须指定默认值");
}
if (value == null) {
value = customParam.defaultValue();
}
}
return ConvertUtils.convert(value, parameterType);
}
/**
* body
*
* @param servletRequest request
* @return body
*/
private String getRequestBody(HttpServletRequest servletRequest) {
StringBuilder stringBuilder = new StringBuilder();
try {
BufferedReader reader = servletRequest.getReader();
char[] buf = new char[1024];
int length;
while ((length = reader.read(buf)) != -1) {
stringBuilder.append(buf, 0, length);
}
} catch (IOException e) {
log.error("读取流异常", e);
throw new RuntimeException("读取流异常");
}
return stringBuilder.toString();
}
}

@ -0,0 +1,149 @@
package com.currency.appengine.handler;
import com.currency.appengine.annotation.CheckToken;
import com.currency.appengine.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.ssssssss.magicapi.core.config.MagicAPIProperties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
/**
* Interceptor verification token
*/
@Component
public class GlobalInterceptor implements HandlerInterceptor {
private static Logger log = LoggerFactory.getLogger(GlobalInterceptor.class);
@Autowired
private MagicAPIProperties properties;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if ("/magic/web/config-js".equals(request.getRequestURI())) {
String editorConfig = properties.getEditorConfig();
String jsInfo = readJsonFile(editorConfig, this.getClass());
HttpUtil.returnJson(response, jsInfo);
return false;
}
log.info(">>>>>>>CheckTokenInterceptor >> start");
request.setAttribute("language", "en".equals(request.getHeader("language"))?"en":request.getHeader("language"));
log.info("language{}", request.getHeader("language"));
// 请求开始时间
long begin_nao_time = System.nanoTime();
request.setAttribute("begin_nao_time", begin_nao_time);
boolean haveAnnotataion = handler.getClass().isAssignableFrom(HandlerMethod.class);
if (haveAnnotataion) {
// Check whether there is @CheckToken annotation
CheckToken checkToken = ((HandlerMethod) handler).getMethodAnnotation(CheckToken.class);
if (checkToken != null) {
// @CheckToken annotation
log.info(">>>>>>>Call before request processing (check token) ");
Map<String, String> headers = HttpUtil.getHeadersInfo(request);
String token = headers.get("authorization");;
if (token == null || token.isEmpty()) {
HttpUtil.returnJson(response, JsonUtil.generate(Result.fail(-2, "result.not_token")));
log.info(">>>>>>>check token fail");
log.info(">>>>>>>CheckTokenInterceptor >> end ");
return false;
}
// check token
TokenUtil tokenUtil = new TokenUtil();
Map<String,Object> tokenInfo = tokenUtil.deToken(token);
Boolean flag = (Boolean) tokenInfo.get("flag");
Map data = JsonUtil.parse(tokenInfo.get("data"), Map.class);
if (flag && StringUtil.notEmpty(data.get("openid"))) {
String acccount = String.valueOf(data.get("openid"));
request.setAttribute("openid", acccount);
log.info("openid : [ {} ]", acccount);
log.info(">>>>>>>check token success");
} else {
HttpUtil.returnJson(response, JsonUtil.generate(Result.fail(-2, "result.not_token")));
log.info(">>>>>>>check token fail");
log.info(">>>>>>>CheckTokenInterceptor >> end ");
return false;
}
log.info("request token : [ {} ]", token);
// >>>>>>>check token fail
}
}
log.info(">>>>>>>CheckTokenInterceptor >> end ");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// 响应时间
long begin_nao_time = (Long) request.getAttribute("begin_nao_time");
long interval = System.nanoTime() - begin_nao_time;
log.info(">>>>>>>响应时间 {} ms", interval / 1_000_000);
request.removeAttribute("begin_nao_time");
request.removeAttribute("openid");
log.info(">>>>>>>remove request attributes");
}
/**
* return json data
*
* @param response
* @param json
* @throws Exception
*/
@SuppressWarnings("unused")
private void returnJson(HttpServletResponse response, Object json) throws Exception {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
try {
writer = response.getWriter();
writer.print(json);
log.info(">>>>>>>response: {}", json);
} catch (IOException e) {
} finally {
if (writer != null)
writer.close();
}
}
/**
* 使resourcesjs
* @param z
* @return
*/
public String readJsonFile(String path, Class z) {
String jsonStr = "";
try {
InputStream inputStream = z.getResourceAsStream(path);
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
int ch = 0;
StringBuilder sb = new StringBuilder();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
return sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}

@ -0,0 +1,58 @@
package com.currency.appengine.handler.exception;
import com.currency.appengine.handler.GlobalInterceptor;
import com.currency.appengine.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* Exception
* @param request
* @param e
* @return
*/
@ExceptionHandler(value = MyException.class)
public Result handleException(HttpServletRequest request, MyException e){
String reqUrl = request.getRequestURI();
String method = request.getMethod();
log.info("=============================自定义ERROR====================================");
log.info("接口:"+reqUrl);
log.info("方法:"+method);
log.error(e.getMessage());
// e.printStackTrace();
return Result.fail(e.getCode(), e.getMsg());
}
/**
* Exception
* @param request
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
public Result handleException(HttpServletRequest request, Exception e){
String reqUrl = request.getRequestURI();
if ("/magic/web/config-js".equals(reqUrl)) {
return null;
}
String method = request.getMethod();
log.info("=============================统一ERROR====================================");
log.info("接口:"+reqUrl);
log.info("方法:"+method);
log.error(e.getMessage());
// e.printStackTrace();
return Result.fail(-1, e.getMessage());
}
}

@ -0,0 +1,17 @@
package com.currency.appengine.handler.exception;
import lombok.Data;
@Data
public class MyException extends RuntimeException {
public MyException(String msg) {
this.code = -1;
this.msg = msg;
}
private int code;
private String msg;
}

@ -0,0 +1,54 @@
package com.currency.appengine.handler.magic;
import com.currency.appengine.utils.I18NUtil;
import com.currency.appengine.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.ResultProvider;
import org.ssssssss.magicapi.modules.db.model.Page;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class CustomJsonValueProvider implements ResultProvider {
/**
* JsonBean
*/
@Override
public Object buildResult(RequestEntity requestEntity, int code, String message, Object data) {
// 如果对分页格式有要求的话可以对data的类型进行判断进而返回不同的格式
Map result = new HashMap<String,Object>(){
{
put("code", code);
put("message", StringUtil.notEmpty(message) ?I18NUtil.getMessage(message):message);
put("data", data);
}
};
return result;
}
/**
* Json
* PageResult
*/
@Override
public Object buildPageResult(RequestEntity requestEntity, Page page, long total, List<Map<String, Object>> data) {
return new HashMap<String,Object>(){
{
put("count", total);
if (data==null) {
put("list", new ArrayList<>());
} else {
put("list", data);
}
}
};
}
}

@ -0,0 +1,40 @@
package com.currency.appengine.handler.magic;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.modules.db.model.Page;
import org.ssssssss.magicapi.modules.db.provider.PageProvider;
import org.ssssssss.script.runtime.RuntimeContext;
import java.util.Objects;
/**
*
* https://ssssssss.org/guide/custom/page.html
* @see PageProvider
*/
@Component
public class CustomPageProvider implements PageProvider {
@Value("${project.list.pageSize.default}")
private Integer listDefaultPageSize;
@Override
public Page getPage(RuntimeContext context) {
// 从Request中提取page以及pageSize
String method = Objects.toString(context.eval("request.get().getMethod()"));
String page = Objects.toString(context.eval("page"), "");
String size = Objects.toString(context.eval("size"), "");
if ("post".equals(method.toLowerCase())) {
// post
page = Objects.toString(context.eval("body.page"), "");
size = Objects.toString(context.eval("body.size"), "");
}
// 从Request中提取page以及pageSize
long pageNum = NumberUtils.toLong(page, 1);
long pageSize = NumberUtils.toLong(size, listDefaultPageSize);
return new Page(pageSize, (pageNum - 1) * pageSize);
}
}

@ -0,0 +1,130 @@
package com.currency.appengine.handler.magic;
import com.currency.appengine.service.log.LogService;
import com.currency.appengine.utils.JsonUtil;
import com.currency.appengine.utils.StringUtil;
import com.currency.appengine.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.core.interceptor.RequestInterceptor;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.model.JsonBean;
import org.ssssssss.magicapi.core.model.Options;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletResponse;
import org.ssssssss.script.MagicScriptContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
/**
*
* https://ssssssss.org/guide/custom/interceptor.html
*/
@Component
public class CustomRequestInterceptor implements RequestInterceptor {
private static final Logger logger = LoggerFactory.getLogger(CustomRequestInterceptor.class);
@Autowired
private LogService logService;
@Value("${project.env}")
private String projectEnv;
/**
*
* @param info
* @param context
*/
public Object preHandle(RequestEntity requestEntity, ApiInfo info, MagicScriptContext context, MagicHttpServletRequest magicRequest, MagicHttpServletResponse magicResponse) throws Exception {
HttpServletRequest request = magicRequest.getRequest();
HttpServletResponse response = magicResponse.getResponse();
Object user = null; // = XXXUtils.getUser(request);
// logger.info("{} 请求接口:{}", user, info.getName());
logger.info(">>>>>>>CustomRequestInterceptor >> start");
if ("true".equals(info.getOptionValue("log_behavior"))) {
// 日志留痕 额外
}
String requestURI = request.getRequestURI();
// 接口日志
logService.appendInterfaceLog(request, info.getName());
// request.setAttribute("language", "en".equals(request.getHeader("language"))?"en":request.getHeader("language"));
// logger.info("language{}", request.getHeader("language"));
if ("true".equals(info.getOptionValue(Options.REQUIRE_LOGIN))) {
// Check whether there is @CheckToken annotation
// @CheckToken annotation
logger.info(">>>>>>>Call before request processing (check token) ");
String token = request.getHeader("authorization");
if (token == null || token.isEmpty()) {
logger.info(">>>>>>>check token fail");
logger.info(">>>>>>>CustomRequestInterceptor >> end ");
return new JsonBean<>(-2, "请传入token");
}
// check token
TokenUtil tokenUtil = new TokenUtil();
Map<String, Object> tokenInfo = tokenUtil.deToken(token);
Boolean flag = (Boolean) tokenInfo.get("flag");
Map data = JsonUtil.parse(tokenInfo.get("data"), Map.class);
if (flag && StringUtil.notEmpty(data.get("openid"))) {
String acccount = String.valueOf(data.get("openid"));
request.setAttribute("openid", acccount);
logger.info("访问用户openid : [ {} ]", acccount);
logger.info(">>>>>>>check token success");
// token校验成功后执行redis处理
} else {
logger.info(">>>>>>>check token fail");
logger.info(">>>>>>>CustomRequestInterceptor >> end ");
return new JsonBean<>(-2, "token无效");
}
logger.info("request token : [ {} ]", token);
// >>>>>>>check token fail
} else {
// 不需要token校验执行redis处理
}
logger.info(">>>>>>>CustomRequestInterceptor >> end ");
return null;
}
@Override
public Object preHandle(RequestEntity requestEntity) throws Exception {
HttpServletResponse response = requestEntity.getResponse().getResponse();
if (!"local".equals(projectEnv) && requestEntity.getRequest().getRequestURI().startsWith("/devapi")) {
return new JsonBean<>(404, "抱歉,未找到可访问资源!");
}
return this.preHandle(requestEntity, requestEntity.getApiInfo(), requestEntity.getMagicScriptContext(), requestEntity.getRequest(), requestEntity.getResponse());
}
/**
*
* @param info
* @param context
* @param value
*/
@Override
public Object postHandle(ApiInfo info, MagicScriptContext context, Object value, MagicHttpServletRequest magicRequest, MagicHttpServletResponse magicResponse) throws Exception {
HttpServletRequest request = magicRequest.getRequest();
request.removeAttribute("openid");
logger.info("{} 执行完毕", info.getName());
// logger.info("{} 执行完毕,返回结果:{}", info.getName(), value);
return null;
}
}

@ -0,0 +1,60 @@
package com.currency.appengine.handler.magic;
import com.currency.appengine.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.ssssssss.magicapi.core.context.RequestEntity;
import org.ssssssss.magicapi.modules.db.BoundSql;
import org.ssssssss.magicapi.modules.db.inteceptor.SQLInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Component
public class DevInterceptor implements SQLInterceptor, HandlerInterceptor {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${project.env}")
private String projectEnv;
/***
* SQL,sql
* @param boundSql
* @param requestEntity
*/
@Override
public void preHandle(BoundSql boundSql, RequestEntity requestEntity) {
logger.warn("执行的SQL===> " + boundSql.getSql());
logger.warn("执行的SQL参数===> " + Arrays.toString(boundSql.getParameters()));
}
/**
* 使
*
* @param request
* @param response
* @param handler
* @return
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
if (!"local".equals(projectEnv)) {
Map<String, Object> result = new HashMap<>();
result.put("msg", "抱歉,未找到可访问资源!");
result.put("status", false);
response.setCharacterEncoding("utf-8");
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.getWriter().write(JsonUtil.generate(result));
return false;
}
return true;
}
}

@ -0,0 +1,96 @@
package com.currency.appengine.handler.magic;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
@Component
public class MagicResourceCopyRunner {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${project.env}")
private String projectEnv;
private boolean finished = false;
@PostConstruct
public void init() throws Exception {
if ("dev".equals(projectEnv)) {
String classpath = System.getProperty("java.class.path");
logger.info("classpath: {}", classpath);
boolean isJar = classpath.contains(".jar");
if (isJar) {
logger.info("jar包中运行");
copyDirectory("api_file");
} else {
finished = true;
logger.info("非jar包中运行");
}
} else {
finished = true;
}
}
private void copyDirectory(String target) throws IOException {
String targetNew = "BOOT-INF/classes/" + target + "/";
String jarFilePath = getJarFilePath();
String targetPath = new File(jarFilePath).getParent() + File.separator +
"magic_api" + File.separator + target;
JarFile jarFile = new JarFile(jarFilePath);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
if (entryName.startsWith(targetNew)) {
String pathName= targetPath + File.separator + entryName.substring(targetNew.length());
if (entry.isDirectory()) {
new File(pathName).mkdirs();
} else {
InputStream inputStream = jarFile.getInputStream(entry);
File targetFile = new File(pathName);
targetFile.getParentFile().mkdirs();
FileOutputStream outputStream = new FileOutputStream(targetFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
}
}
jarFile.close();
finished = true;
}
private String getJarFilePath() {
ApplicationHome home = new ApplicationHome(getClass());
File jarFile = home.getSource();
return jarFile.toString();
}
public boolean isFinished() {
return finished;
}
}

@ -0,0 +1,104 @@
package com.currency.appengine.handler.magic.module;
import org.springframework.http.HttpInputMessage;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartRequest;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.magicapi.core.servlet.MagicCookie;
import org.ssssssss.magicapi.core.servlet.MagicHttpServletRequest;
import org.ssssssss.magicapi.core.servlet.MagicHttpSession;
import org.ssssssss.magicapi.modules.servlet.RequestModule;
import java.io.IOException;
import java.io.InputStream;
import java.security.Principal;
import java.util.Enumeration;
@Component
@MagicModule("req")
public class RequestExtendFunction {
public String getHeader(String s) {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getHeader(s);
}
public Enumeration<String> getHeaders(String s) {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getHeaders(s);
}
public String getRequestURI() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getRequestURI();
}
public String getMethod() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getMethod();
}
public void setAttribute(String s, Object o) {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
magicHttpServletRequest.setAttribute(s, o);
}
public String[] getParameterValues(String s) {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getParameterValues(s);
}
public Object getAttribute(String s) {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getAttribute(s);
}
public HttpInputMessage getHttpInputMessage() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getHttpInputMessage();
}
public String getContentType() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getContentType();
}
public MagicHttpSession getSession() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getSession();
}
public MagicCookie[] getCookies() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getCookies();
}
public InputStream getInputStream() throws IOException {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getInputStream();
}
public boolean isMultipart() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.isMultipart();
}
public String getRemoteAddr() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getRemoteAddr();
}
public MultipartRequest resolveMultipart() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.resolveMultipart();
}
public Principal getUserPrincipal() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getUserPrincipal();
}
public <T> T getRequest() {
MagicHttpServletRequest magicHttpServletRequest = RequestModule.get();
return magicHttpServletRequest.getRequest();
}
}

@ -0,0 +1,67 @@
package com.currency.appengine.handler.magic.module;
import com.currency.appengine.config.GlobalData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.core.annotation.MagicModule;
import org.ssssssss.script.annotation.Comment;
import java.util.Objects;
@Component
@MagicModule("sql")
public class SqlFunction {
@Autowired
GlobalData globalData;
/**
* %Y-%m-%d %H:%i:%S
*/
@Comment("日期格式,默认格式%Y-%m-%d %H:%i:%S")
public String date(@Comment("字段字符串") String value) {
return this.date(value, "%Y-%m-%d %H:%i:%S");
}
/**
*
*/
@Comment("日期格式,自定义格式")
public String date(@Comment("字段字符串") String value, @Comment("字段字符串") String format) {
if (!Objects.nonNull(format) || "".equals(format)) {
format = "%Y-%m-%d %H:%i:%S";
}
StringBuffer str = new StringBuffer();
str.append("date_format(")
.append(value)
.append(", '")
.append(format)
.append("')");
return str.toString();
}
@Comment("拼接文件路径")
public String file(@Comment("字段字符串") String value) {
// concat(#{filePath}, file_path)
String filePath = globalData.getFilePath();
StringBuffer str = new StringBuffer();
str.append("concat('")
.append(filePath)
.append("', ")
.append(value)
.append(")");
return str.toString();
}
@Comment("文件路径移除前缀")
public String file_rm_pre(@Comment("需要修改的文件路径") String value) {
// concat(#{filePath}, file_path)
String filePath = globalData.getFilePath();
StringBuffer str = new StringBuffer();
str.append("replace('")
.append(value)
.append("', '")
.append(filePath)
.append("','')");
return str.toString();
}
}

@ -0,0 +1,73 @@
package com.currency.appengine.handler.mybatis;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@MappedJdbcTypes(JdbcType.VARCHAR)
public class MySqlJsonHandler<T extends Object> extends BaseTypeHandler<T> {
private static ObjectMapper objectMapper;
private Class<T> type;
static {
objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public MySqlJsonHandler(Class<T> type) {
if (null == type) {
throw new PersistenceException("Type argument cannot be null");
}
this.type = type;
}
private T parse(String json) {
try {
if (json == null || json.length() == 0) {
return null;
}
return objectMapper.readValue(json, type);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private String toJsonString(T obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
return parse(rs.getString(columnName));
}
@Override
public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return parse(rs.getString(columnIndex));
}
@Override
public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return parse(cs.getString(columnIndex));
}
@Override
public void setNonNullParameter(PreparedStatement ps, int columnIndex, T parameter, JdbcType jdbcType)
throws SQLException {
ps.setString(columnIndex, toJsonString(parameter));
}
}

@ -0,0 +1,111 @@
package com.currency.appengine.kubernetes;
import com.currency.appengine.config.GlobalData;
import com.currency.appengine.dto.CreateDeploymentDTO;
import com.currency.appengine.dto.DeleteDeploymentDTO;
import com.currency.appengine.utils.HttpUtil;
import com.currency.appengine.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;
@Configuration
public class Deployment {
private Logger log = LoggerFactory.getLogger(Deployment.class);
@Autowired
GlobalData globalData;
/**
* deployment
*
* @param uid
* @param resultsUrl
* @param returnUrl
* @param track
* @param pythonUrl
* @return
*/
@Transactional
public void createDeployment(String uid, String resultsUrl, String returnUrl, String track, String pythonUrl) {
if (uid == null || resultsUrl == null || returnUrl == null || track == null || pythonUrl == null) {
log.error("createDeployment-参数不全");
return;
}
// 更新计算状态
/* MiniInfoQuery miniInfoQuery = new MiniInfoQuery().where.unionKey().eq(uid).end();
MiniInfoEntity miniInfoEntity = miniInfoMapper.findOne(miniInfoQuery);
miniInfoEntity.setCalculationStatus("running");
miniInfoMapper.updateById(miniInfoEntity);*/
// 提交计算到k8s
try {
String containerResultsUrl = globalData.getSysParams("containerResultsUrl");
CreateDeploymentDTO params = new CreateDeploymentDTO();
params.setPythonUrl(pythonUrl);
params.setUid(uid);
params.setResultsUrl(resultsUrl);
params.setReturnUrl(returnUrl);
params.setContainerResultsUrl(containerResultsUrl);
params.setTrack(track);
/*JSONObject params = new JSONObject();
params.put("uid", uid);
params.put("resultsUrl", resultsUrl);
params.put("returnUrl", returnUrl);
params.put("track", track);
params.put("pythonUrl", pythonUrl);
params.put("containerResultsUrl", containerResultsUrl);
*/
String rancherUrl = globalData.getSysParams("rancherUrl");
rancherUrl += "/createDeployment";
log.info("createDeployment-调用创建deployment参数:" + rancherUrl + "---" + JsonUtil.ObjectToString(params));
String result = HttpUtil.post(rancherUrl, JsonUtil.ObjectToString(params));
log.info("createDeployment-接收创建deployment结果:" + result);
} catch (Exception e) {
log.error("createDeployment-异常", e);
}
}
/**
* deployment
*
* @param uid
* @param track
*/
public void deleteDeployment(String uid, String track) {
try {
DeleteDeploymentDTO params = new DeleteDeploymentDTO();
params.setTrack(track);
params.setUid(uid);
/*JSONObject params = new JSONObject();
params.put("uid", uid);
params.put("track", track);*/
String rancherUrl = globalData.getSysParams("rancherUrl");
rancherUrl += "/deleteDeployment";
log.info("deleteDeployment-调用删除deployment参数,rancherUrl:{},params:{}", rancherUrl, JsonUtil.ObjectToString(params));
String result = HttpUtil.post(rancherUrl, JsonUtil.ObjectToString(params));
log.info("deleteDeployment-接收删除deployment结果,result:{}", result);
} catch (Exception e) {
log.error("deleteDeployment-异常", e);
}
}
}

@ -0,0 +1,32 @@
package com.currency.appengine.mapper.auto;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface TableInfoMapper {
@Select({"<script>",
"select table_name as tablename, table_comment as tablecomment",
" from information_schema.tables where table_schema=(select database()) and table_name in ",
"<foreach item='item' index='index' collection='list' open='(' separator=',' close=')'>",
"#{item}",
"</foreach>",
"</script>"
})
List<Map> listTable(List list);
@Select({"<script>",
"select table_name as tablename, column_name as columnname, is_nullable as isnullable, data_type as datatype, column_type as columntype, column_key as columnkey, column_comment as columncomment",
" from information_schema.columns where table_schema=(select database()) and table_name in ",
"<foreach item='item' index='index' collection='list' open='(' separator=',' close=')'>",
"#{item}",
"</foreach>",
"</script>"
})
List<Map> listTableCloumns(List list);
@Select("select column_name, table_name from information_schema.columns where table_schema = (select database()) and data_type in ('varchar', 'text', 'longtext')")
List<Map> listTableCloumnsByStrType();
}

@ -0,0 +1,38 @@
package com.currency.appengine.mapper.common;
import com.currency.appengine.mapper.common.provider.SqlProvider;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.UpdateProvider;
import java.util.List;
import java.util.Map;
public interface CommonMapper {
/**
* sql
* @param sql
* @param params
* @return
*/
@SelectProvider(type = SqlProvider.class, method = "find")
List<Map<String, Object>> find(String sql, @Param("params") Map<String, Object> params);
@SelectProvider(type = SqlProvider.class, method = "findOne")
Map<String, Object> findOne(String sql, @Param("params") Map<String, Object> params);
@SelectProvider(type = SqlProvider.class, method = "find")
int findInt(String sql, @Param("params") Map<String, Object> params);
@SelectProvider(type = SqlProvider.class, method = "findOne")
String findValue(String sql, @Param("params") Map<String, Object> params);
/**
* sql
*/
@SelectProvider(type = SqlProvider.class, method = "count")
int count(String table, String where, @Param("params") Map<String, Object> params);
}

@ -0,0 +1,14 @@
package com.currency.appengine.mapper.common;
import com.currency.appengine.domain.system.SysParam;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface DicMapper {
@Select("select type, code as value, dictionary as label from mini_dictionary where status=1 order by sort")
List<Map<String, String>> getDic();
}

@ -0,0 +1,46 @@
package com.currency.appengine.mapper.common.provider;
import com.currency.appengine.utils.PrintUtil;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.jdbc.SQL;
import java.util.Map;
import java.util.Objects;
public class SqlProvider {
public String find(String sql, Map<String, Object> params) {
PrintUtil.println(params);
// 动态生成 SQL 语句
String regex = "#\\{(\\w+)\\}";
sql = sql.replaceAll(regex, "#{params.$1}");
return sql;
}
public String findOne(String sql, Map<String, Object> params) {
PrintUtil.println(params);
// 动态生成 SQL 语句
String regex = "#\\{(\\w+)\\}";
sql = sql.replaceAll(regex, "#{params.$1}");
sql = sql + " limit 1";
return sql;
}
public String count(String table, String where, Map<String, Object> params) {
PrintUtil.println(params);
// 动态生成 SQL 语句
SQL sql = new SQL() {
{
SELECT("count(1)");
FROM(table);
}
};
if (Objects.nonNull(where)) {
String regex = "#\\{(\\w+)\\}";
where = where.replaceAll(regex, "#{params.$1}");
sql.WHERE(where);
}
return sql.toString();
}
}

@ -0,0 +1,36 @@
package com.currency.appengine.mapper.data;
import com.currency.appengine.controller.importFile.entity.MiniDataEntity;
import com.currency.appengine.controller.importFile.entity.MiniProductMaterialsImport;
import com.currency.appengine.domain.upload.MiniUploadFile;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
import java.util.Map;
public interface DataMapper {
@Insert("INSERT INTO mini_data (email, sender_name, sender_phone, sender_address, recipient_name, recipient_phone, recipient_address) VALUES (#{email}, #{senderName}, #{senderPhone}, #{senderAddress}, #{recipientName}, #{recipientPhone}, #{recipientAddress})")
int insert(MiniDataEntity miniDataEntity);
@Insert({"<script>",
"INSERT INTO mini_data (email, sender_name, sender_phone, sender_address, recipient_name, recipient_phone, recipient_address) VALUES ",
"<foreach item='item' index='index' collection='miniDataEntityList' separator=','>",
"(#{item.email}, #{item.senderName}, #{item.senderPhone}, #{item.senderAddress}, #{item.recipientName}, #{item.recipientPhone}, #{item.recipientAddress})",
"</foreach>",
"</script>"
})
int batchInsert(List<MiniDataEntity> miniDataEntityList);
@Insert({"<script>",
"INSERT INTO mini_product_materials ( material_code, profile_model, material_name, specification, thickness, weight, pieces_bundle, material_category, default_length, packaging_method, source, status, safety_stock, inventory_unit, unit, remarks) VALUES ",
"<foreach item='item' index='index' collection='list' separator=','>",
"(#{item.materialCode},#{item.profileModel},#{item.materialName},#{item.specification},#{item.thickness},#{item.weight},#{item.piecesBundle},#{item.materialCategory},#{item.defaultLength},#{item.packagingMethod},#{item.source},#{item.status},#{item.safetyStock},#{item.inventoryUnit},#{item.unit},#{item.remarks})",
"</foreach>",
"</script>"
})
int batchInsertMiniProductMaterials(List<MiniProductMaterialsImport> list);
}

@ -0,0 +1,38 @@
package com.currency.appengine.mapper.export;
import com.currency.appengine.domain.export.UserInfoExport;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface ExportMapper {
/*"select id, user_id, status, date_format(create_time,'%Y-%m-%d %T') create_time, nick_name, user_img from mini_user where 1=1 ",
"<if test= 'userId!=null and userId!=\"\"'> and user_id like CONCAT('%',#{userId},'%') </if>",
"<if test= 'nickName!=null and nickName!=\"\"'> and nick_name like CONCAT('%',#{nickName},'%') </if>",
"<if test= 'status!=null and status!=\"\"'> and status = #{status} </if>",*/
@Results(id = "resultMap", value = {
@Result(property = "userId", column = "user_id"),
@Result(property = "nickName", column = "nick_name"),
@Result(property = "userImg", column = "user_img"),
@Result(property = "createTime", column = "create_time"),
@Result(property = "status", column = "status"),
})
@Select({"<script>",
" ${sql} ",
" limit #{limit},#{size}",
"</script>"
})
List<UserInfoExport> findUserInfoPage(Map<String, Object> map);
@Select("select count(1) from ( ${sql} ) _t")
int findCount(String sql);
}

@ -0,0 +1,15 @@
package com.currency.appengine.mapper.log;
import org.apache.ibatis.annotations.Insert;
import java.util.Map;
public interface LoginLogMapper {
@Insert("INSERT INTO mini_login_log(user_id, ip) VALUES (#{userId}, #{ip})")
int insert(Map map);
}

@ -0,0 +1,71 @@
package com.currency.appengine.mapper.system;
import com.currency.appengine.domain.system.Router;
import com.currency.appengine.domain.system.RouterMeta;
import com.currency.appengine.handler.mybatis.MySqlJsonHandler;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface SysMenuMapper {
@Results(id = "sysMenu", value = {
@Result(property = "menuId", column = "menu_id"),
@Result(property = "parent", column = "parent"),
@Result(property = "name", column = "name"),
@Result(property = "path", column = "path"),
@Result(property = "component", column = "component"),
@Result(property = "redirect", column = "redirect"),
@Result(property = "meta", column = "meta",javaType=RouterMeta.class, typeHandler=MySqlJsonHandler.class),
@Result(property = "createTime", column = "create_time"),
})
@Select("select * from sys_menu where status='0' order by sort")
List<Router> findAll();
@Insert("insert into sys_menu(parent,\n" +
"name,\n" +
"path,\n" +
"component,\n" +
"redirect,\n" +
"meta,\n" +
"status) values(#{parent},\n" +
"#{name},\n" +
"#{path},\n" +
"#{component},\n" +
"#{redirect},\n" +
"#{meta,javaType=com.currency.appengine.domain.system.RouterMeta,typeHandler=com.currency.appengine.handler.mybatis.MySqlJsonHandler},\n" +
"0)")
int add(Router router);
@Select("select count(1) from sys_menu where name = #{name} limit 1")
boolean findByName(Object name);
@Delete({"<script>",
"delete from sys_menu where name in (",
"<foreach item='item' index='index' collection='split' separator=','>",
"#{item}",
"</foreach>",
")",
"</script>"
})
int mulDel(String[] split);
@Update("update sys_menu set parent = #{router.parent},\n" +
"path = #{router.path},\n" +
"component = #{router.component},\n" +
"redirect = #{router.redirect},\n" +
"meta = #{router.meta,javaType=com.currency.appengine.domain.system.RouterMeta,typeHandler=com.currency.appengine.handler.mybatis.MySqlJsonHandler}" +
" where name=#{oldName}")
int update(Router router, String oldName);
@Select({"<script>",
"select * from sys_menu where status='0' and name in (",
"<foreach item='item' index='index' collection='menuNames' separator=','>",
"#{item}",
"</foreach>",
")",
"order by case when parent is null or parent = '' then 1 else parent end, sort",
"</script>"
})
@ResultMap("sysMenu")
List<Router> findByMenuNames(List<String> menuNames);
}

@ -0,0 +1,90 @@
package com.currency.appengine.mapper.system;
import com.currency.appengine.domain.system.SysParam;
import com.currency.appengine.mapper.system.provider.SysParamProvider;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Map;
public interface SysParamMapper {
@Results(id = "sysParam", value = {
@Result(property = "sysParamId", column = "sys_param_id"),
@Result(property = "paramCode", column = "param_code"),
@Result(property = "paramNm", column = "param_nm"),
@Result(property = "paramValue", column = "param_value"),
@Result(property = "remark", column = "remark"),
@Result(property = "useFg", column = "use_fg"),
@Result(property = "sysFg", column = "sys_fg")
})
@Select("select * from sys_param where use_fg=1")
List<SysParam> sysParams();
@Select("select param_value from sys_param where param_code=#{paramCode}")
String getValueByCode(String paramCode);
@Insert(
"insert into sys_param(param_code,param_nm,param_value,remark,use_fg, sys_fg) values(#{paramCode},#{paramNm},#{paramValue},#{remark},#{useFg},#{sysFg})"
)
@Options(useGeneratedKeys = true, keyProperty = "sysParamId", keyColumn = "sys_param_id")
int save(SysParam sysParam);
@Update({"<script>",
"update sys_param",
"<set>",
"<if test= 'paramCode!=null'>param_code=#{paramCode},</if>",
"<if test= 'paramNm!=null'>param_nm=#{paramNm},</if>",
"<if test= 'paramValue!=null'>param_value=#{paramValue},</if>",
"<if test= 'remark!=null'>remark=#{remark},</if>",
"<if test= 'useFg!=null'>use_fg=#{useFg},</if>",
"<if test= 'sysFg!=null'>sys_fg=#{sysFg},</if>",
"</set>",
"where sys_param_id=#{sysParamId}",
"</script>"
})
int update(SysParam sysParam);
@SelectProvider(type = SysParamProvider.class, method = "pageList")
@ResultMap("sysParam")
List<SysParam> pageList(Map<String, Object> params);
@Select("select count(param_code) from sys_param where param_code=#{paramCode}")
int codeNum(String paramCode);
@Update({"<script>",
"delete from sys_param where sys_param_id in (",
"<foreach item='item' index='index' collection='sysParamIdArr' separator=','>",
"#{item}",
"</foreach>",
")",
"</script>"
})
int deleteById(String[] sysParamIdArr);
@Select(" select A.appid,B.secret,C.callbackUrl from (select 1 as id, param_value as appid from sys_param where param_code='appid') A LEFT JOIN (select 1 as id, param_value as secret from sys_param where param_code='secret' ) B on A.id = B.id left join ( select 1 as id, param_value as callbackUrl from sys_param where param_code='callbackUrl' ) C on A.id = C.id limit 1")
Map<String,String> getWxConfig();
@Select("select A.ENDPOINT,B.ACCESS_KEY_ID,C.ACCESS_KEY_SECRET,D.BACKET_NAME from (select 1 as id, param_value as ENDPOINT from sys_param where param_code='ENDPOINT') A \n" +
"LEFT JOIN\n" +
"( select 1 as id, param_value as ACCESS_KEY_ID from sys_param where param_code='ACCESS_KEY_ID' ) B on A.id = B.id \n" +
"LEFT JOIN\n" +
"( select 1 as id, param_value as ACCESS_KEY_SECRET from sys_param where param_code='ACCESS_KEY_SECRET' ) C on A.id = C.id \n" +
"LEFT JOIN\n" +
"( select 1 as id, param_value as BACKET_NAME from sys_param where param_code='BACKET_NAME' ) D on A.id = D.id LIMIT 1")
Map<String,String> getOSSConfig();
@Select(" select A.appid,B.mchId,C.mchKey,D.notifyUrl,E.body from (select 1 as id, param_value as appid from sys_param where param_code='appid') A LEFT JOIN \n" +
" ( select 1 as id, param_value as mchId from sys_param where param_code='mchId' ) B on A.id = B.id LEFT JOIN" +
" ( select 1 as id, param_value as mchKey from sys_param where param_code='mchKey' ) C on A.id = C.id LEFT JOIN" +
" ( select 1 as id, param_value as notifyUrl from sys_param where param_code='notifyUrl' ) D on A.id = D.id LEFT JOIN " +
" ( select 1 as id, param_value as body from sys_param where param_code='body' ) E on A.id = E.id limit 1")
Map<String,String> getPayConfig();
@Select("select A.imgFolder,B.imgSize,C.imgUnit from (select 1 as id, param_value as imgFolder from sys_param where param_code='imgFolder') A \n" +
"LEFT JOIN \n" +
"( select 1 as id, param_value as imgSize from sys_param where param_code='imgSize' ) B on A.id = B.id \n" +
"LEFT JOIN \n" +
"( select 1 as id, param_value as imgUnit from sys_param where param_code='imgUnit' ) C on A.id = C.id\n" +
"limit 1")
Map<String,String> getImgConfig();
}

@ -0,0 +1,55 @@
package com.currency.appengine.mapper.system;
import com.currency.appengine.domain.system.SysRole;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface SysRoleMapper {
@Results(id = "sysRole", value = {
@Result(property = "id", column = "role_id"),
@Result(property = "parentId", column = "parent_role_id"),
@Result(property = "label", column = "role_name"),
@Result(property = "alias", column = "alias"),
@Result(property = "sort", column = "sort"),
})
@Select("select * from sys_role where status='0' order by sort")
List<SysRole> findAll();
@Insert("insert into sys_role(parent_role_id,\n" +
"role_name,\n" +
"alias,\n" +
"sort) values(#{parentId}," +
"#{label}," +
"#{alias}," +
"#{sort})")
int add(SysRole role);
@Select("select count(1) from sys_role where alias = #{alias} limit 1")
boolean findByAlias(Object alias);
@Delete({"<script>",
"delete from sys_role where role_id in (",
"<foreach item='item' index='index' collection='split' separator=',' >",
"#{item}",
"</foreach>",
")",
"</script>"
})
int mulDel(String[] split);
@Update("update sys_role set parent_role_id = #{sysRole.parentId},\n" +
"role_name = #{sysRole.label},\n" +
"sort = #{sysRole.sort} where role_id=#{id}")
int update(SysRole sysRole, String id);
@Select({"<script>",
"select group_concat(role_name) from sys_role where role_id in (",
"<foreach item='item' index='index' collection='rolesList' separator=','>",
"#{item}",
"</foreach>",
")",
"</script>"
})
String findNameById(List<String> rolesList);
}

@ -0,0 +1,51 @@
package com.currency.appengine.mapper.system;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
public interface SysRoleMenuMapper {
@Insert({"<script>",
"replace into sys_role_menu(menu_name,is_last, role_id) values ",
"<foreach item='item' index='index' collection='split' separator=','>",
"(#{item.menu},#{item.isLast}, #{id})",
"</foreach>",
"</script>"
})
int add(String id, List<Map<String, String>> split);
@Delete({"<script>",
"delete from sys_role_menu where role_id in (",
"<foreach item='item' index='index' collection='split' separator=',' >",
"#{item}",
"</foreach>",
")",
"</script>"
})
int mulDel(String[] split);
@Select({"<script>",
"select distinct menu_name from sys_role_menu where role_id in (",
"<foreach item='item' index='index' collection='roles' separator=','>",
"#{item}",
"</foreach>",
")",
"</script>"})
List<String> findMenuByRole(List<String> roles);
@Select("select distinct menu_name from sys_role_menu where role_id=#{id} and is_last=1")
List<String> findMenuByRoleCheck(String id);
@Delete({"<script>",
"delete from sys_role_menu where menu_name in (",
"<foreach item='item' index='index' collection='split' separator=',' >",
"#{item}",
"</foreach>",
")",
"</script>"
})
int mulDelByName(String[] split);
}

@ -0,0 +1,62 @@
package com.currency.appengine.mapper.system;
import com.currency.appengine.domain.system.SysUser;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface SysUserMapper {
@Results(id = "sysuser", value = {
@Result(property = "id", column = "user_id"),
@Result(property = "userName", column = "account"),
@Result(property = "name", column = "user_name"),
@Result(property = "date", column = "create_time"),
@Result(property = "group", column = "roleIds"),
@Result(property = "groupName", column = "roleNames")
})
@Select("select su.user_id, su.user_name, su.account, su.create_time, GROUP_CONCAT(sur.role_id) AS roleIds,GROUP_CONCAT(sr.role_name) AS roleNames from sys_user su left join sys_user_role sur on sur.user_id=su.user_id left join sys_role sr on \n" +
"sr.role_id =sur.role_id group by su.account")
List<SysUser> findSysUserListAll();
@Select("select count(1) from sys_user where account=#{userName} limit 1")
boolean hasAccount(Object userName);
@Select("select * from sys_user where account=#{user}")
@Results(id = "sysUserAll", value = {
@Result(property = "id", column = "user_id"),
@Result(property = "userName", column = "account"),
@Result(property = "password", column = "password"),
@Result(property = "name", column = "user_name"),
@Result(property = "date", column = "create_time")
})
SysUser findByAccount(String user);
@Select("select * from sys_user where user_id=#{id}")
@ResultMap("sysUserAll")
SysUser findById(String id);
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "user_id")
@Insert("insert into sys_user(user_name,\n" +
"account,\n" +
"password) values(#{name},#{userName},#{password})")
int add(SysUser sysUser);
@Delete({"<script>",
"delete from sys_user where user_id in (",
"<foreach item='item' index='index' collection='split' separator=','>",
"#{item}",
"</foreach>",
")",
"</script>"
})
int mulDel(String[] split);
@Update("update sys_user set user_name=#{name} where user_id=#{id}")
int update(SysUser sysUser);
@Update("update sys_user set password=#{password} where user_id=#{id}")
int updatePassword(String id, String password);
@Update("update sys_user set user_name=#{name} where user_id=#{id}")
int updateName(String id, String name);
}

@ -0,0 +1,41 @@
package com.currency.appengine.mapper.system;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface SysUserRoleMapper {
@Insert({"<script>",
"replace into sys_user_role(user_id, role_id) values ",
"<foreach item='item' index='index' collection='group' separator=','>",
"(#{userId}, #{item})",
"</foreach>",
"</script>"
})
int add(String userId, String[] group);
@Delete({"<script>",
"delete from sys_user_role where user_id in (",
"<foreach item='item' index='index' collection='split' separator=','>",
"#{item}",
"</foreach>",
")",
"</script>"
})
int mulDel(String[] split);
@Select("select role_id from sys_user_role where user_id=#{id}")
List<String> findByUser(String id);
@Delete({"<script>",
"delete from sys_user_role where role_id in (",
"<foreach item='item' index='index' collection='split' separator=','>",
"#{item}",
"</foreach>",
")",
"</script>"
})
int mulDelByRoleId(String[] split);
}

@ -0,0 +1,43 @@
package com.currency.appengine.mapper.system.provider;
import com.currency.appengine.utils.StringUtil;
import java.util.Map;
public class SysParamProvider {
public String pageList(Map<String, Object> params) {
String paramNm = StringUtil.objectToString(params.get("paramNm"));
String paramCode = StringUtil.objectToString(params.get("paramCode"));
String paramValue = StringUtil.objectToString(params.get("paramValue"));
String remark = StringUtil.objectToString(params.get("remark"));
String useFg = StringUtil.objectToString(params.get("useFg"));
StringBuffer sql = new StringBuffer("select * from sys_param where sys_fg!=1 ");
if (StringUtil.notBlank(paramNm)) {
sql.append(" and param_nm like '%" + paramNm + "%' ");
}
if (StringUtil.notBlank(paramCode)) {
sql.append(" and param_code like '%" + paramCode + "%' ");
}
if (StringUtil.notBlank(paramValue)) {
sql.append(" and param_value like '%" + paramValue + "%' ");
}
if (StringUtil.notBlank(remark)) {
sql.append(" and remark like '%" + remark + "%' ");
}
if (StringUtil.notBlank(useFg)) {
sql.append(" and use_fg='" + useFg + "' ");
}
sql.append("order by sys_param_id desc");
return sql.toString();
}
}

@ -0,0 +1,30 @@
package com.currency.appengine.mapper.system.provider;
import com.currency.appengine.utils.StringUtil;
public class SysUserProvider {
public String findSysUserList(String account, String status, String createTmStart, String createTmEnd) {
StringBuffer sql = new StringBuffer("select * from sys_user where 1=1 and del_flag='0' ");
if (StringUtil.notBlank(account)) {
sql.append(" and account='" + account + "' ");
}
if (StringUtil.notBlank(status)) {
sql.append(" and status='" + status + "' ");
}
if (StringUtil.notBlank(createTmStart)) {
sql.append(" and create_time>='" + createTmStart + " 00:00:00' ");
}
if (StringUtil.notBlank(createTmEnd)) {
sql.append(" and create_time<='" + createTmEnd + " 23:59:59' ");
}
sql.append("order by create_time desc");
return sql.toString();
}
}

@ -0,0 +1,64 @@
package com.currency.appengine.mapper.upload;
import com.currency.appengine.domain.upload.MiniUploadFile;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
public interface UploadFileMapper {
@Insert("INSERT INTO mini_upload_file(file_name, file_path, way_type) VALUES (#{uploadFile.fileName}, #{uploadFile.filePath}, #{uploadFile.wayType})")
int insert(MiniUploadFile uploadFile);
@Insert({"<script>",
"insert into mini_upload_file(file_name, file_path, way_type) values",
"<foreach item='item' index='index' collection='uploadFiles' separator=','>",
"(#{item.fileName}, #{item.filePath}, #{item.wayType})",
"</foreach>",
"</script>"
})
int insertBatch(List<MiniUploadFile> uploadFiles);
@Delete({"<script>",
"delete from mini_upload_file where file_path in",
"<foreach item='item' index='index' collection='list' open='(' separator=',' close=')'>",
"#{item}",
"</foreach>",
"</script>"
})
int delByFilePath(List<String> list);
@Update({"<script>",
"update mini_upload_file set use_status=1 where file_path in",
"<foreach item='item' index='index' collection='list' open='(' separator=',' close=')'>",
"#{item}",
"</foreach>",
"</script>"
})
int addUseStatusByFilePath(List<String> list);
@Update({"<script>",
"update mini_upload_file set use_status=0 where file_path in",
"<foreach item='item' index='index' collection='list' open='(' separator=',' close=')'>",
"#{item}",
"</foreach>",
"</script>"
})
int delUseStatusByFilePath(List<String> list);
@Select("select * from mini_upload_file where use_status=0")
List<MiniUploadFile> queryNoUse();
@Delete({"<script>",
"delete from mini_upload_file where id in",
"<foreach item='item' index='index' collection='deleteId' open='(' separator=',' close=')'>",
"#{item}",
"</foreach>",
"</script>"
})
void delReallById(List<Long> deleteId);
}

@ -0,0 +1,74 @@
package com.currency.appengine.mapper.user;
import org.apache.ibatis.annotations.*;
import java.util.Map;
public interface UserMapper {
@Select("select * from mini_user where phone=#{phone}")
Map<String,Object> findByPhone(String phone);
@Select("select * from mini_user where email=#{email}")
Map<String,Object> findByEmail(String email);
@Select("select * from mini_user where user_name=#{userName}")
Map<String,Object> findByUserName(String userName);
@Update({"<script>",
"update mini_user",
"<set>",
"reject_description = null,",
"<if test= 'firstName!=null'>first_name=#{firstName},</if>",
"<if test= 'lastName!=null'>last_name=#{lastName},</if>",
"<if test= 'occupationCode!=null'>occupation_code=#{occupationCode},</if>",
"<if test= 'organizationTypeCode!=null'>organization_type_code=#{organizationTypeCode},</if>",
"<if test= 'encValue!=null'>user_password=#{encValue},</if>",
"<if test= 'downloadPurpose!=null'>download_purpose=#{downloadPurpose},</if>",
"<if test= 'email!=null'>email=#{email},</if>",
"<if test= 'curDate!=null'>create_time=#{curDate},</if>",
"<if test= 'sourceCode!=null'>source_code=#{sourceCode},</if>",
"<if test= 'sourceName!=null'>source_name=#{sourceName},</if>",
"<if test= 'sourceRemarks!=null'>source_remarks=#{sourceRemarks},</if>",
"<if test= 'applyStatus!=null'>apply_status=#{applyStatus},</if>",
"<if test= 'userId!=null'>user_id=#{userId},</if>",
"<if test= 'phone!=null'>phone=#{phone},</if>",
"<if test= 'userName!=null'>user_name=#{userName},</if>",
"<if test= 'occupation!=null'>occupation=#{occupation},</if>",
"<if test= 'userImg!=null'>user_img=#{userImg},</if>",
"</set>",
"where id=#{id}",
"</script>"
})
int update(Map<String,Object> map);
@Insert("INSERT INTO mini_user(user_password, email, apply_status, reject_description, create_time, source_name, source_remarks, source_code, phone, user_name, referral, user_img) " +
"VALUES (#{encValue}, #{email}, #{applyStatus}, #{rejectDescription}, #{curDate}, #{sourceName}, #{sourceRemarks}, #{sourceCode}, #{phone}, #{userName}, #{referral}, #{userImg})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
int insert(Map<String,Object> map);
@Update("update mini_user set user_id=#{userId} where id=#{id}")
int updateUserId(Map<String,Object> map);
@Update("update mini_user set phone=#{phone} where user_id=#{userId}")
int updatePhone(Map<String,Object> map);
@Update("update mini_user set email=#{email} where user_id=#{userId}")
int updateEmail(Map<String,Object> map);
@Update("update mini_user set user_password=#{password} where phone=#{phone}")
int updatePassword(Map<String,Object> map);
@Update("update mini_user set user_password=#{newPassword} where email=#{email}")
int updateByEmailPassword(Map<String,Object> map);
// @Update("update mini_user set quit_team_status=0")
// int updateQuitTeamStatus();
@Select("select count(1) from mini_email where #{suffix} like concat('%',email_suffix ) and status=1")
int isDefault(String suffix);
}

@ -0,0 +1,171 @@
package com.currency.appengine.service.common;
import com.currency.appengine.enums.CodeEnum;
import com.currency.appengine.mapper.common.CommonMapper;
import com.currency.appengine.service.user.impl.UserServiceImpl;
import com.currency.appengine.utils.LockUtils;
import com.currency.appengine.utils.date.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Service
public class CommonServices {
private final static Logger logger = LoggerFactory.getLogger(CommonServices.class);
@Autowired
CommonMapper commonMapper;
public String getCode(String type, Map<String, Object> data) {
Map<String, Function<Map<String, Object>,String>> grantTypeMap = new HashMap<>();
grantTypeMap.put("CustomerCode", params -> customerCode(params)); // 客户编码
grantTypeMap.put("SupplierCode", params -> supplierCode(params)); // 供应商编码
grantTypeMap.put("SalesOrderNumber", params -> salesOrderNumber(params)); // 销售单号
grantTypeMap.put("OrderNumber", params -> orderNumber(params)); // 订单编号
grantTypeMap.put("ProductionPlan", params -> productionPlan(params)); // 生产计划
grantTypeMap.put("ProductionSchedulingNumber", params -> productionSchedulingNumber(params)); // 排产编号
grantTypeMap.put("ProductionOrderNumber", params -> productionOrderNumber(params)); // 排产单号
grantTypeMap.put("PurchaseNumber", params -> purchaseNumber(params)); // 采购编号
Function<Map<String, Object>,String> result = grantTypeMap.get(type);
if(result!=null){
//传入resourceId 执行这段表达式获得String型的grantType
return result.apply(data);
}
return null;
}
/**
* C+5
* mini_customer_info
* @param params
* @return
*/
public String customerCode(Map<String, Object> params) {
try {
return LockUtils.doWithLock(() -> {
int count = commonMapper.count("mini_customer_info", null, null);
return "C" + formatNumber(count, "5");
});
} catch (Exception e) {
return null;
}
}
/**
* V+5
* @param params
* @return
*/
public String supplierCode(Map<String, Object> params) {
try {
return LockUtils.doWithLock(() -> {
int count = commonMapper.count("mini_supplier_info", null, null);
return "V" + formatNumber(count, "5");
});
} catch (Exception e) {
return null;
}
}
/**
* ++3SW20240929-001SW20240929-002SW20240929-003..)
* @param params
* @return
*/
public String salesOrderNumber(Map<String, Object> params) {
return null;
}
/**
* +0010100102
* @param params
* @return
*/
public String orderNumber(Map<String, Object> params) {
return null;
}
/**
* :P+3
* @param params
* @return
*/
public String productionPlan(Map<String, Object> params) {
try {
return LockUtils.doWithLock(() -> {
int count = commonMapper.count("mini_production_schedule", "date(create_time) = curdate()", null);
return "P" + DateUtil.getYyyyMMdd() + formatNumber(count, "3");
});
} catch (Exception e) {
return null;
}
}
/**
* JY+3
* @param params
* @return
*/
public String productionSchedulingNumber(Map<String, Object> params) {
try {
return LockUtils.doWithLock(() -> {
int count = commonMapper.count("mini_extrusion_schedule", "date(create_time) = curdate()", null);
return "JY" + DateUtil.getYyyyMMdd() + formatNumber(count, "3");
});
} catch (Exception e) {
return null;
}
}
/**
* JY++3
* @param params
* @return
*/
public String productionOrderNumber(Map<String, Object> params) {
try {
return LockUtils.doWithLock(() -> {
int count = commonMapper.count("mini_extrusion_schedule", "date(create_time) = curdate()", null);
return "JY" + DateUtil.getYyyyMMdd() + formatNumber(count, "3");
});
} catch (Exception e) {
return null;
}
}
/**
* PO++
* @param params
* @return
*/
public String purchaseNumber(Map<String, Object> params) {
try {
return LockUtils.doWithLock(() -> {
int count = commonMapper.count("mini_purchase_orders", "date(create_time) = curdate()", null);
return "PO" + DateUtil.getYyyyMMdd() + formatNumber(count, "3");
});
} catch (Exception e) {
return null;
}
}
public String formatNumber(int number, String digit) {
return String.format("%0" + digit + "d", number);
}
public static void main(String[] arg) {
int sequenceNumber = 123456; // 假设这是你的序号
String formattedSequence = String.format("%05d", sequenceNumber);
System.out.println(formattedSequence); // 输出00123
}
}

@ -0,0 +1,19 @@
package com.currency.appengine.service.dynamic;
import com.currency.appengine.utils.Result;
import java.util.Map;
public interface DynamicService {
Result listBefore(Map content);
Result listAfter(Object content);
Result addBefore(Map content);
Result addAfter(Object content);
Result editBefore(Map content);
Result editAfter(Object content);
Result deleteBefore(String[] ids);
Result deleteAfter(Object content);
}

@ -0,0 +1,22 @@
package com.currency.appengine.service.dynamic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
public class DynamicServiceImp {
@Autowired
Map<String, DynamicService> dynamicServiceMap;
public DynamicService getDynamicService(String type) {
DynamicService dynamicService = dynamicServiceMap.get(type);
if (dynamicService == null) {
return null;
}
return dynamicService;
}
}

@ -0,0 +1,75 @@
package com.currency.appengine.service.dynamic.imp;
import com.currency.appengine.service.dynamic.DynamicService;
import com.currency.appengine.utils.date.DateUtil;
import com.currency.appengine.utils.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service("dyMiniInfo")
public class DyMiniInfoImp implements DynamicService {
//log日志
private static Logger logger = LoggerFactory.getLogger(DyMiniInfoImp.class);
@Override
public Result listBefore(Map content) {
logger.info("进入DyMiniInfoImp listBefore");
return Result.suc(content);
}
@Override
public Result listAfter(Object content) {
logger.info("进入DyMiniInfoImp listAfter");
return Result.suc(content);
}
@Override
public Result addBefore(Map content) {
logger.info("进入DyMiniInfoImp addBefore");
// 生成unionKey
// String teamId = String.valueOf(content.get("teamId"));
String curDate = DateUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss");
String teamId = "TSYS" + DateUtil.datetimeStrToFormat(curDate,"yyyyMMddHHmmss") + "";
String unionKey = teamId + DateUtil.getCurrentTime("yyyyMMddHHmmss");
content.put("teamId",teamId);
content.put("unionKey",unionKey);
content.put("taskType",2);
content.put("calculationStatus","end");
return Result.suc(content);
}
@Override
public Result addAfter(Object content) {
logger.info("进入DyMiniInfoImp addAfter");
return Result.suc(content);
}
@Override
public Result editBefore(Map content) {
logger.info("进入DyMiniInfoImp editBefore");
return Result.suc(content);
}
@Override
public Result editAfter(Object content) {
logger.info("进入DyMiniInfoImp editAfter");
return Result.suc(content);
}
@Override
public Result deleteBefore(String[] ids) {
logger.info("进入DyMiniInfoImp deleteBefore");
// 目前该代码逻辑不支持批量删除
return Result.suc(ids);
}
@Override
public Result deleteAfter(Object content) {
logger.info("进入DyMiniInfoImp deleteAfter");
return Result.suc(content);
}
}

@ -0,0 +1,14 @@
package com.currency.appengine.service.export;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.util.Map;
public interface ExportDataPageService {
int findCount(Map<String, Object> params, int method);
Object findPage(Map<String, Object> params, int method);
void setWorkbook(SXSSFWorkbook wb, SXSSFSheet eachSheet, Integer startRowCount, Integer endRowCount, Object datas, int method);
}

@ -0,0 +1,147 @@
package com.currency.appengine.service.export.impl;
import com.currency.appengine.domain.export.UserInfoExport;
import com.currency.appengine.handler.exception.MyException;
import com.currency.appengine.mapper.export.ExportMapper;
import com.currency.appengine.service.export.ExportDataPageService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Service
public class ExportDataPageServiceImpl implements ExportDataPageService {
@Autowired
private ExportMapper exportMapper;
/**
*
* @param params
* @param method
* @return
*/
@Override
public int findCount(Map<String, Object> params, int method) {
return exportMapper.findCount(this.sql(params, method));
}
/**
* sql
* @param params
* @param method
* @return
*/
private String sql(Map<String, Object> params, int method){
StringBuffer buffer = new StringBuffer();
switch (method) {
case 0:// 0 用户信息
buffer.append("select id, user_id, status, date_format(create_time,'%Y-%m-%d %T') create_time, nick_name, user_img from mini_user where 1=1 ");
if(Objects.nonNull(params.get("userId"))){
buffer.append(" and user_id like CONCAT('%',#{userId},'%') ");
}
if(Objects.nonNull(params.get("nickName"))){
buffer.append(" and nick_name like CONCAT('%',#{nickName},'%') ");
}
if(Objects.nonNull(params.get("status"))){
buffer.append(" and and status = #{status} ");
}
break;
default:
throw new MyException("导出失败传入method参数不匹配请检查代码");
}
return buffer.toString();
}
/**
*
* @param params
* @param method
* @return
*/
@Override
public Object findPage(Map<String, Object> params, int method) {
Object list = new ArrayList<>();
switch (method) {
case 0:// 0 用户信息
params.put("sql",this.sql(params, method));
list = exportMapper.findUserInfoPage(params);
break;
}
return list;
}
/**
* 使
* @param wb
* @param eachSheet
* @param startRowCount
* @param endRowCount
* @param datas
* @param method
*/
@Override
public void setWorkbook(SXSSFWorkbook wb, SXSSFSheet eachSheet, Integer startRowCount, Integer endRowCount, Object datas, int method) {
switch (method) {
case 0:// 用户信息 指定设置样式
List<UserInfoExport> list = (List<UserInfoExport>) datas;
if (Objects.nonNull(list) && !list.isEmpty()) {
setUserInfoExportData(wb, eachSheet, startRowCount, endRowCount, list);
}
break;
default: // 其他
break;
}
}
private void setUserInfoExportData(SXSSFWorkbook wb, SXSSFSheet eachSheet, Integer startRowCount, Integer endRowCount, List<UserInfoExport> list) {
for (int i = startRowCount; i <= endRowCount; i++) {
SXSSFRow eachDataRow = eachSheet.createRow(i);
if ((i - startRowCount) < list.size()) {
UserInfoExport model = list.get(i - startRowCount);
eachDataRow.createCell(0).setCellValue(model.getUserImg());
eachDataRow.createCell(1).setCellValue(model.getUserId());
eachDataRow.createCell(2).setCellValue(model.getNickName());
eachDataRow.createCell(3).setCellValue(model.getCreateTime());
eachDataRow.createCell(4).setCellValue(model.getStatus());
if("1".equals(model.getStatus())) {
int physicalNumberOfCells = eachDataRow.getPhysicalNumberOfCells();
for (int j = 0; j < physicalNumberOfCells; j++) {
if(i <= 1){
eachSheet.setColumnWidth(j, 20 * 256);
}
//获取当前单元格 中的value
if (j > 1 && j < 3) {
//获取单元格对象
Cell cell = eachDataRow.getCell(j);
//获取单元格样式对象
CellStyle cellStyle = wb.createCellStyle();
// cellStyle.setAlignment(HorizontalAlignment.CENTER);
//获取单元格内容对象
Font font = wb.createFont();
//一定要装入 样式中才会生效
cellStyle.setFont(font);
font.setColor(IndexedColors.RED.getIndex());
cell.setCellStyle(cellStyle);
}
}
}
}
}
}
}

@ -0,0 +1,17 @@
package com.currency.appengine.service.importFile;
import com.currency.appengine.utils.Result;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
public interface ImportFileService {
Result importFile(List<MultipartFile> files);
Result importExcel(MultipartFile file);
Result importExcelCommon(MultipartFile file, String type);
}

@ -0,0 +1,101 @@
package com.currency.appengine.service.importFile.impl;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.currency.appengine.controller.importFile.entity.MiniDataEntity;
import com.currency.appengine.controller.importFile.entity.MiniProductMaterialsImport;
import com.currency.appengine.enums.ResultCode;
import com.currency.appengine.mapper.data.DataMapper;
import com.currency.appengine.service.importFile.ImportFileService;
import com.currency.appengine.utils.Result;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@Service
public class ImportFileServiceImpl implements ImportFileService {
@Autowired
private DataMapper dataMapper;
@Override
public Result importFile(List<MultipartFile> files) {
return Result.suc();
}
@Override
public Result importExcel(MultipartFile file) {
try {
ImportParams params = new ImportParams();
params.setHeadRows(1);
List<MiniDataEntity> list = ExcelImportUtil.importExcel(file.getInputStream(), MiniDataEntity.class, params);
// for (int i = 0, len = list.size(); i < len; i++) {
// MiniDataEntity data = list.get(i);
// if (data != null) {
//
// }
// }
dataMapper.batchInsert(list);
return Result.exit(0, "导入成功", null);
} catch (Exception e) {
e.printStackTrace();
}
return Result.fail(ResultCode.FAIL);
}
@Override
public Result importExcelCommon(MultipartFile file, String type) {
try {
ImportParams params = new ImportParams();
params.setHeadRows(1);
System.out.println("导入");
System.out.println(type);
switch (type) {
case "materials":
List<MiniProductMaterialsImport> list = ExcelImportUtil.importExcel(file.getInputStream(), MiniProductMaterialsImport.class, params);
if (list.size() > 0) {
dataMapper.batchInsertMiniProductMaterials(list);
} else {
return Result.fail(-1, "数据为空");
}
break;
default:
}
return Result.exit(0, "导入成功", null);
} catch (Exception e) {
e.printStackTrace();
}
return Result.fail(ResultCode.FAIL);
}
// Utility method to get cell value and convert to appropriate type
private Object getCellValue(Cell cell) {
if (cell == null) return null;
switch (cell.getCellType()) {
case STRING:
return cell.getStringCellValue();
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
return cell.getDateCellValue(); // For date type
} else {
return cell.getNumericCellValue();
}
case BOOLEAN:
return cell.getBooleanCellValue();
default:
return null;
}
}
}

@ -0,0 +1,70 @@
package com.currency.appengine.service.log;
import com.currency.appengine.config.GlobalData;
import com.currency.appengine.mapper.log.LoginLogMapper;
import com.currency.appengine.utils.HttpUtil;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@Service
public class LogService {
private static Logger log = LoggerFactory.getLogger(LogService.class);
@Autowired
private GlobalData globalData;
@Autowired
private LoginLogMapper loginLogMapper;
/**
* 线 Bean
*
*/
@Async("logThread")
public void appendLoginLog(String ip, String userId) {
// 处理日志
log.info("**************登陆日志留痕开始**************");
// 登记日志
// 查询归属地
Map<String, Object> belong = globalData.queryBelong(ip);
if ("0".equals(String.valueOf(belong.get("code")))) {
String country = String.valueOf(belong.get("country"));
String province = String.valueOf(belong.get("province"));
String city = String.valueOf(belong.get("city"));
log.info("ip: {}, 归属地:{}", ip, new StringBuffer().append(country).append("|")
.append(province).append("|").append(city).append("|"));
}
Map map = Maps.newHashMapWithExpectedSize(7);
map.put("userId",userId);
map.put("ip",ip);
int re = loginLogMapper.insert(map);
log.info("**************登陆日志留痕结束**************");
}
/**
*
* @param request
*/
@Async("logThread")
public void appendInterfaceLog(HttpServletRequest request, String name) {
String ip = HttpUtil.getIpAddress(request);
Map<String, Object> belong = globalData.queryBelong(ip);
if ("0".equals(String.valueOf(belong.get("code")))) {
String country = String.valueOf(belong.get("country"));
String province = String.valueOf(belong.get("province"));
String city = String.valueOf(belong.get("city"));
log.info("接口: {}, ip: {}, 归属地:{}", name, ip, new StringBuffer().append(country).append("|")
.append(province).append("|").append(city).append("|"));
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save