Commit 2c9a96f5 by ddx

init

parents

Too many changes to show.

To preserve performance only 1000 of 1000+ files are displayed.

# 常量定义:
> 众所知周,一个系统的常量不会超过1W个,如果超过,需要拆分系统。
> 在第一条的前提下,我们定义常量长为1{module}{service}**,首位固定为1,用于区分系统。第二位为模块位,
比如tax-sys含有sign,token等模块,意味着一个模块含有【0,999】个常量值。第三个位服位,比如用户模块
含有用户服务,规则服务等,一个服务含有【0,99】个常量值。
# cloud结构
* **tax-service-center-registry** ##注册中心
* **tax-service-center-config** ##配置中心
* **tax-service-center-gateway** ## 网关
# 项目结构
* **tax-common** ##通用模块 10***
* **tax-mq** ##通用模块-mq服务 101**
* **tax-file-system** ##文件系统服务
* **tax-elastic-job** ##当当定时服务
* **tax-user** ##用户模块 11*** http://localhost:10300/user
* **tax-token** ##token模块 12*** http://localhost:10300/token
* **tax-sign** ##签名模块 13*** http://localhost:10300/sign 提供签名,代理ip服务
* **tax-file** ##文件模块 14*** http://localhost:10300/files
* **tax-zone** ##地区模块 15*** http://localhost:10300/zone
# 开发流程
开发接口生成器:1.使用maven插件mybatis-generator生成bean,mapper.xml
2.使用common模块下Gen类生成mapper,service,serviceImpl
# 部署流程
* 配置eurekaServer的hosts为 eurekahost 127.0.0.1
* 配置zookeeper的hosts为 taxsys-zookeeper 127.0.0.1
* 如果模块服务和eureka不在一个机器 配置模块服务host 为 eurekahost {eurekaServer的IP}
* 启动顺序
1.tax-service-center-registry
2.tax-service-center-config
#脚本部署账号
autodeploy / Autodeploy2018!
#脚本发布
./auto_deploy.sh [ startserver | stopserver | startclient | stopclient | startall | stopall | force | status ]
[ start [sign-startup token-startup user-startup scan-startup taxfile-startup zone-startup tax-service-center-gateway tax-websocket-startup]
[ stop [sign-startup token-startup user-startup scan-startup taxfile-startup zone-startup tax-service-center-gateway tax-websocket-startup]]
[ update [sign-startup token-startup user-startup scan-startup taxfile-startup zone-startup tax-service-center-gateway tax-websocket-startup | clientall | serverall | registry | config ]
[ log [sign-startup token-startup user-startup scan-startup taxfile-startup zone-startup tax-service-center-gateway tax-websocket-startup]
#添加模块脚本修改
在clientList中增加
\ No newline at end of file
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yxcheng.tax</groupId>
<artifactId>tax-sys</artifactId>
<version>2.2-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>tax-common</module>
<module>tax-token</module>
<module>tax-elastic-job</module>
<module>tax-mq</module>
<module>tax-zone</module>
<module>tax-sign</module>
<module>tax-file-face</module>
<module>tax-file-system</module>
<module>tax-file</module>
<module>tax-user</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.13</version>
</parent>
<!-- 公共属性定义 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.encoding>UTF-8</maven.compiler.encoding>
<maven.test.skip>true</maven.test.skip>
<dist.console.jar.dir>${project.build.directory}</dist.console.jar.dir>
<tax.profiles>prd</tax.profiles>
<docker.url>http://localhost:2375</docker.url>
<registry.url>192.168.123.105:5000</registry.url>
<jasypt.version>1.16</jasypt.version>
</properties>
<profiles>
<profile>
<id>dev</id>
<properties>
<deployType>dev</deployType>
<nacos.group>tax-sys</nacos.group>
<nacos.address>localhost:8848</nacos.address>
<nacos.namespace>53745adf-58da-4874-b94c-8f727fc30546</nacos.namespace>
<nacos.username>nacos</nacos.username>
<nacos.password>nacos</nacos.password>
</properties>
<!-- 默认激活 -->
<activation>
<activeByDefault>true</activeByDefault>
</activation>
</profile>
<!-- 测试环境 -->
<profile>
<id>test</id>
<properties>
<deployType>test</deployType>
<nacos.group>tax-sys</nacos.group>
<nacos.address>localhost:8848</nacos.address>
<nacos.namespace>53745adf-58da-4874-b94c-8f727fc30546</nacos.namespace>
<nacos.username>nacos</nacos.username>
<nacos.password>nacos</nacos.password>
</properties>
</profile>
<!-- 正式环境 -->
<profile>
<id>prod</id>
<properties>
<deployType>prod</deployType>
<nacos.group>tax-sys</nacos.group>
<nacos.address>nacos.taxservices.cn:8500</nacos.address>
<nacos.namespace>fcf74289-9986-426b-8db2-a563b22a5cef</nacos.namespace>
<nacos.username>nacos</nacos.username>
<nacos.password>nac@csq!2022</nacos.password>
</properties>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${jasypt.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<delimiters>@</delimiters>
<useDefaultDelimiters>false</useDefaultDelimiters>
</configuration>
</plugin>
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>0.4.13</version>
<configuration>
<imageName>${registry.url}/${project.name}:0.0.1</imageName>
<dockerHost>${docker.url}</dockerHost>
<dockerDirectory>${project.basedir}</dockerDirectory>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
<serverId>docker-hub</serverId>
<registryUrl>https://index.docker.io/v1/</registryUrl>
</configuration>
</plugin>
</plugins>
<!--允许某目录支持 maven的filter-->
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
\ No newline at end of file
1 docker 应用
\ No newline at end of file
#!/bin/bash
for line in `cat errorpath.txt`
do
echo $line
cd $line
for filename in `ls $line`
do
fsize=`ls -l $filename | awk '{print $5}'`
if [ $fsize -le 200 ]; then
echo $fsize
echo $filename
rm $filename
fi
done
done
#!/bin/bash
echo "1";
for i in `find ./tax-user -type d -name "sign"`;
do
n=`echo $i | sed 's/sign/user/g'`;
echo "i is "$i; echo "n is "$n;
mv $i $n;
done
#!/usr/bin/env bash
aj="12334433"
li=${aj##*2}
echo $li
\ No newline at end of file
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yxcheng.tax</groupId>
<artifactId>tax-sys</artifactId>
<version>2.2-SNAPSHOT</version>
</parent>
<groupId>com.yxcheng.tax</groupId>
<artifactId>tax-common</artifactId>
<version>2.2-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-cbor</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.6.3</version>
</dependency>
<!-- jackson json -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
<version>2.12.4</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<!-- httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.20</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.6</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.1.6</version>
</dependency>
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${jasypt.version}</version>
</dependency>
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>
</project>
package com.yxcheng.token.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface LogT {
public static final String LOG_VIEW_FULL = "full";
public static final String LOG_VIEW_PART = "part";
String value() default LOG_VIEW_FULL;
}
package com.yxcheng.token.common.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* redis分布式限流算法注解,对整个集群进行总量限流,超过限流阈值的请求会直接中断,<p>
* 返回标准限流异常<b>LimitException</b>。<p>
* <b>参数:count</b> 为整个集群每秒限流总量,超过的请求会直接返回fase<p>
* <b>参数:unitTime</b> 为限流单位,默认1秒,即每秒限流个数<p>
*
* @author wuyuegang
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface RedisLimit
{
/**
* 集群限流数量,默认10。所有客户端共享这个数值
*
* @return
*/
int count() default 10;
/**
* 限流时间单位,默认1秒
*
* @return
*/
long unitTime() default 1;
}
package com.yxcheng.token.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface RuleT {
String value() default "";
}
package com.yxcheng.token.common.aop;
import com.alibaba.fastjson.JSONObject;
import com.yxcheng.token.common.annotation.LogT;
import com.yxcheng.token.utils.MapUtil;
import com.yxcheng.token.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
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.util.HashMap;
import java.util.Map;
@Slf4j
@Aspect
@Component
public class LogAop {
//切入点
@Pointcut("@annotation(com.yxcheng.token.common.annotation.LogT)")
public void log(){
}
// @After("log()")
// public void afterExec(JoinPoint joinpoint) throws Throwable{
// }
//
// @Before("log()")
// public void beforeExec(JoinPoint joinpoint) throws Throwable{
// }
@Around(value = "log() && @annotation(logt)")
public Object aroundExec(ProceedingJoinPoint point, LogT logt) throws Throwable{
//请求开始时间
long start = System.currentTimeMillis();
//请求参数
Map paramsMap = new HashMap();
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String contentType = request.getContentType();//获取请求的content-type
if(StringUtils.isNotBlank(contentType) && (contentType.contains("multipart/form-data") || contentType.contains("application/json"))){//文件上传请求 json传输 *特殊请求
//上传文件获取第一个入参对象。
Object[] args = point.getArgs();
if(args.length>0){
paramsMap = MapUtil.objectToMap(point.getArgs()[0]);
}
}else{//非文件上传请求
paramsMap = request.getParameterMap();
}
log.info(start + " method:"+point.toShortString()+";params:"+ JSONObject.toJSONString(paramsMap) + " is start!");
//执行方法
Object result = point.proceed();
//请求耗时
long time = System.currentTimeMillis() - start;
//输出日志
String logResult = JSONObject.toJSONString(result);
if(logt.value().equals(LogT.LOG_VIEW_PART)) {
logResult = sublog(logResult);
}
log.info(start + " method:"+ point.toShortString() +";response:"+ logResult +" is end! cost:["+time+"ms]");
return result;
}
private String sublog(String log) {
if(StringUtil.isNotEmpty(log) && log.length()>305) {
log = log.substring(0, 300) + "...";
}
return log;
}
}
package com.yxcheng.token.common.aop;
import com.yxcheng.token.common.annotation.RedisLimit;
import com.yxcheng.token.common.exception.LimitException;
import com.yxcheng.token.common.limit.RedisLimiter;
import com.yxcheng.token.common.model.SafeModel;
import com.yxcheng.token.utils.IpUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* 集群限流处理类,采用spring AOP切面基础,进行限流拦截,对超过限流的请求
* <p>
* 返回限流异常<b>LimitException</b>,异常码枚举<b>SystemErrorEnum.TOO_MUCH_ERROR</b>
* <p>
*
* @author wuyuegang
*
*/
@Aspect
@Configuration
public class RedisLimiterAop
{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* redis限流器,主要是对redis的操作封装
*/
@Autowired
private RedisLimiter limiter;
@Before("@annotation(annotation)")
public void doBefore(JoinPoint point, RedisLimit annotation)
throws Throwable
{
String methodName = point.getSignature().getName();// 限流注解所在方法名
String className = point.getTarget().getClass().getName();// 限流注解所在类名
int index = className.lastIndexOf(".");
// className = className.substring(index+1,className.length());
String key = className + "." + methodName;// 用类名+方法名,可以唯一确定一个限流函数,作为限流器生成主键
// 判断拦截到的方法是不是有注解 BWRedisLimit,如果没有这个注解,说明不是需要拦截的方法,放过。如果有注解,开始进入限流拦截
Object o = point.getArgs()[0];
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
if(o instanceof SafeModel){
SafeModel safeModel = (SafeModel) o;
key += (":" + safeModel.getAccessKeyID());
}
if (annotation != null)
{
// 执行限流
long start = System.currentTimeMillis();
int count = annotation.count();// 从注解中得到限流值 count
long unitTime = annotation.unitTime();// 从注解中得到限流单位时间 unitTime
if (limiter.tryAcquire(key, count, unitTime))// 执行限流判断
{
// 成功进入限流,继续执行业务
if (logger.isDebugEnabled())
{
logger.debug("RedisLimiter tryAcquire success, key [{}] count [{}] cost[{}]ms",
key,
count,
(System.currentTimeMillis() - start));
}
}
else
{
// 请求被限流,抛出异常,中断业务
if (logger.isInfoEnabled())
{
logger.info("RedisLimiter tryAcquire failed, key [{}] count [{}] cost[{}]ms",
key,
count,
(System.currentTimeMillis() - start));
}
throw new LimitException(key + ",ip:"+ IpUtil.getRequestRealIp(request)+" 系统限流,请稍后再试");
}
}
}
}
//package com.yxcheng.token.common.aop;
//
//
//import org.aspectj.lang.ProceedingJoinPoint;
//import org.aspectj.lang.annotation.Around;
//import org.aspectj.lang.annotation.Aspect;
//import org.aspectj.lang.reflect.MethodSignature;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.context.annotation.Configuration;
//
//@Aspect
//@Configuration
//public class ServiceDigestAop {
// private final Logger logger = LoggerFactory.getLogger(this.getClass());
// public static final String POINT = "execution (* com..*.service.impl.*.*(..))";
// private static final long FIVE_SECONDS = 5000L;
//
// public ServiceDigestAop() {
// }
//
// @Around("execution (* com..*.service.impl.*.*(..))")
// public Object timeAround(ProceedingJoinPoint joinPoint) {
// Object obj = null;
// Object[] args = joinPoint.getArgs();
// long startTime = System.currentTimeMillis();
// MethodSignature signature = (MethodSignature)joinPoint.getSignature();
// String methodName = signature.getDeclaringTypeName() + "_" + signature.getName();
//
// try {
// obj = joinPoint.proceed(args);
// } catch (Throwable var10) {
// if (var10 instanceof RuntimeException) {
// throw (RuntimeException)var10;
// }
//
// throw new RuntimeException(var10);
// }
//
// long endTime = System.currentTimeMillis();
// this.printExecTime(methodName, args, startTime, endTime);
// return obj;
// }
//
// private boolean isPrimite(Class<?> clazz) {
// return clazz.isPrimitive() || clazz == String.class;
// }
//
// private void printExecTime(String methodName, Object[] args, long startTime, long endTime) {
// long diffTime = endTime - startTime;
// StringBuffer argString = new StringBuffer();
// Object[] var10 = args;
// int var11 = args.length;
//
// for(int var12 = 0; var12 < var11; ++var12) {
// Object arg = var10[var12];
// if (this.isPrimite(arg.getClass())) {
// argString.append(arg.toString()).append(",");
// } else {
// argString.append(arg.getClass()).append(",");
// }
// }
//
// if (diffTime > 5000L) {
// this.logger.warn("[" + methodName + "] param:" + argString + " cost " + diffTime + " ms");
// } else {
// this.logger.info("[" + methodName + "] param:" + argString + " cost " + diffTime + " ms");
// }
//
// }
//}
\ No newline at end of file
package com.yxcheng.token.common.cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* 类名:RedisCacheConfiguration<br>
* 描述:<br>
* 创建人:<br>
* 创建时间:2016/9/6 17:33<br>
*
* @version v1.0
*/
@Configuration
@EnableCaching
public class RedisCacheConfiguration extends CachingConfigurerSupport {
Logger logger = LoggerFactory.getLogger(RedisCacheConfiguration.class);
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.lettuce.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.lettuce.pool.max-active}")
private int maxTotal;
@Value("${spring.redis.lettuce.pool.max-wait}")
private long maxWaitMillis;
@Value("${spring.redis.password}")
private String password;
@Bean
public JedisPool redisPoolFactory() {
logger.info("JedisPool注入成功!!");
logger.info("redis地址:" + host + ":" + port);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(maxTotal);
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
return jedisPool;
}
}
\ No newline at end of file
package com.yxcheng.token.common.cache;
import com.yxcheng.token.utils.SerializeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.*;
/**
* RedisService不支持泛型,因此添加了一个新类支持泛型
* @author breeze
*
* @param <K>
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
@Service
public class RedisServiceGeneric<K,V> {
private Logger LOG = LoggerFactory.getLogger(RedisServiceGeneric.class);
@Autowired
private List<RedisTemplate<K,V>> redisTemplateList;
@Autowired
private RedisTemplate<K,V> redisTemplate;
/**
* 获取有序集合的大小
* @param key
* @return
*/
public Long zkSize(K key){
return redisTemplate.opsForZSet().size(key);
}
/**
* zk移除元素
* @param key
* @param start
* @param end
*/
public Long zkRemoveRange(K key, long start, long end){
return redisTemplate.opsForZSet().removeRange(key, start, end);
}
/**
* zk插入元素
* @param key
* @param value
* @param score
* @return
*/
public Boolean zkAdd(K key, V value, double score){
return redisTemplate.opsForZSet().add(key, value, score);
}
/**
* zk获取元素
* @param key
* @param start
* @param end
* @return
*/
public Set<V> zkRange(K key, long start, long end){
return redisTemplate.opsForZSet().range(key, start, end);
}
/**
* 判断是否存在key
* @param key
* @return
*/
public Boolean hasKey(K key){
return redisTemplate.hasKey(key);
}
}
package com.yxcheng.token.common.cache.distributelock;
import com.yxcheng.token.common.cache.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
@Service
public class ScheduledControll {
@Autowired
private RedisService redisService;
public boolean getScheduledLock(String key,int expire) {
RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisService.getRedisTemplate().getConnectionFactory());
Long increment = entityIdCounter.getAndIncrement();
if ((null == increment || increment.longValue() == 0) && expire > 0) {//初始设置过期时间
entityIdCounter.expire(expire, TimeUnit.SECONDS);
}
//redis值大于0,获取锁失败。
if(increment>0){
return false;
}else{
return true;
}
}
public void delScheduledLock(String key) {
redisService.del(key);
}
}
package com.yxcheng.token.common.controller;
import com.yxcheng.token.common.model.CrRpcResult;
import com.yxcheng.token.common.model.RestfulApi;
import com.yxcheng.token.common.model.SafeModel;
import net.sf.json.JSONObject;
public class BaseClientController {
@Deprecated
public boolean isSafe(SafeModel model, CrRpcResult result){
JSONObject data = new JSONObject();
data.put("accessKeyID",model.getAccessKeyID());
data.put("signature",model.getSignature());
data.put("signatureNonce",model.getSignatureNonce());
data.put("timeStamp",model.getTimeStamp());
data.put("version",model.getVersion());
data.put("data","");
RestfulApi apiModel = new RestfulApi();
// return RestFulCheckFactory.newInstance().createCheckService().checkData(data.toString(),apiModel,result);
return true;
}
public boolean checkUserSafe(CrRpcResult result){
return result!=null && "0".equals(result.getCode());
}
}
package com.yxcheng.token.common.enumutil;
import org.springframework.util.StringUtils;
/**
* 全局错误码枚举,数字编码不允许重复,请按照升序进行排列,此错
* <p>
* 误码和错误信息是直接返回给最终用户的,请写清楚错误原因,更好
* <p>
* 的来指导用户进行后续的操作。
* <p>
*
* @author wuyuegang
*
*/
public enum AcceptErrorEnum
{
// 全局错误码
/**
* 默认错误,系统异常
*/
SYSTEM_ERROR("-1", "系统异常,请稍后再试"),
/**
* 长软99,系统异常,请重试
*/
CR_REALTIME_CERTIFY_ERROR_99("201", "系统异常,请重试"),
/**
* 长软03,参数不全,请检查
*/
CR_REALTIME_CERTIFY_ERROR_03("211", "参数不全,请检查"),
/**
* 长软-1,未知错误
*/
CR_ASYNC_CERTIFY_ERROR_1("215", "未知错误"),
/**
* 网络错误
*/
CR_GET_FPXX_RESULT_IO_ERROR("481","网络错误"),
/**
* 请求参数不正确
*/
CR_GET_FPXX_REQUEST_NULL("483","请求参数不正确"),
/********************验收单异常信息***************************/
/**
* 未知错误
*/
UNKNOWN_ERROR("10000", "未知异常");
private String msg;
private String code;
/**
*
* getByCode:(根据code获取枚举). <br/>
* (如果code为空,返回null).<br/>
*
* @author wuyuegang
* @param code
* @return
* @since JDK 1.8
*/
public static AcceptErrorEnum getByCode(String code)
{
if (StringUtils.isEmpty(code))
{
return null;
}
for (AcceptErrorEnum errorEnum : AcceptErrorEnum.values())
{
if (errorEnum.getCode().equals(code))
{
return errorEnum;
}
}
return null;
}
/**
*
* Creates a new instance of SystemErrorEnum.
*
* @param code
* @param msg
*/
private AcceptErrorEnum(String code, String msg)
{
this.code = code;
this.msg = msg;
}
private AcceptErrorEnum(String msg)
{
this.msg = msg;
}
public String getMsg()
{
return this.msg;
}
public String getCode()
{
return this.code;
}
}
package com.yxcheng.token.common.enumutil;
/**
**/
public interface ResultCode {
/**
* 返回码
*
* @return 编码值
*/
String getCode();
/**
* get消息
*
* @return 消息
*/
String getMessage();
}
package com.yxcheng.token.common.enumutil;
/**
*
*/
public enum ResultEnum implements ResultCode {
///////////////////////////////// 通用模块 /////////////////////////////////
/**
* 成功的返回值
*/
ok("10000","操作成功!"),
/**
* 签名失败的返回值
*/
sign_error("10001","签名结果错误"),
verson_error("10002","版本号不正确"),
time_diff_error("10003","时间差异超出范围"),
sign_nonce_error("10004","SignatureNonce值已被使用过"),
param_error("10005","请求参数不正确"),
ip_role_error("10006","IP不在授权范围内"),
id_valid_error("10007","身份验证失败"),
no_inter_error("10008","未开通该接口"),
time_fmt_error("10009","时间格式错误"),
no_opt_taxno_error("10010","不能操作该税号"),
fail("10011","操作失败!"),
/**
* 参数校验失败的返回值
*/
/**
* 无权限的返回值
*/
unauthorized("10012","非法访问!"),
/**
* 权限不够的返回值
*/
forbidden("10013","权限不够!"),
/**
* 找不到记录的返回值
*/
notfound("10014","不存在!"),
/**
* 系统异常的返回值
*/
system_error("10015","系统异常,请稍后再试!"),
/**
* session超时的返回值
*/
request_timeout("10016","抱歉,您的请求超时了。"),
/**
* 请重新登录
*/
login_error("10017","请重新登录!"),
/**
* 解密失败的返回值
*/
decrypt_error("10018","解密失败。"),
/**
* 签名失败的返回值
*/
session_key_error("10019","缺少sessionKey参数"),
limit_access("10020","您已被限流,请稍后重试"),
user_disvaild("10021","您的用户已经过期或停用"),
///////////////////////////////// user模块 /////////////////////////////////
user_not_permission("11001","用户没有权限"),
user_mismatch_rules("11002","用户不符合规则"),
user_not_own_taxno("11003","用户没权限操作此税号"),
ip_notin_whitelist("11003","ip不在白名单内"),
taxno_in_blacklist("11004","该税号在黑名单内"),
///////////////////////////////// token模块 /////////////////////////////////
zone_not_exist("12001","地区不存在"),
token_not_obtained("12002", "token未获取"),
user_taxno_not_exist("12003","用户没有此税号数据"),
flush_error("12004", "刷新异常"),
taxno_registered("12005", "税号已注册"),
user_not_exist("12006", "用户不存在"),
user_taxno_temp_stop("12007","此税号数据异常"),
user_taxno_temp_disable("12008","此税号暂停"),
taxno_status_error("12009","税号异常,请检查"),
taxno_status_middle("12010","中间过程"),
user_taxno_fpy_disable("12011","此税号为数字账户用户"),
sms_parse_fail("12012","短信解析失败"),
sms_push_fail("12013","短信推送失败"),
user_taxno_waiting("12014","税号排队中"),
///////////////////////////////// scan模块 /////////////////////////////////
no_verify_code("13001", "没有获取答案"),
more_than_times("13002", "请求超过次数"),
///////////////////////////////// sign模块 /////////////////////////////////
no_data("13001","无数据"),
///////////////////////////////// 手工打码 /////////////////////////////////
verify_timeout("20201", "识别验证码超时,重新上传验证码或跳过"),
/**
* 文件上传异常的返回值
*/
file_upload_error("30001","上传异常,请稍后再试!"),
/**
* 根据用户名获取税号列表为空
*/
file_taxnos_error("30002","获取税号列表为空!"),
/**
* 根据任务编号查询file,列表为空
*/
file_taskno_error("30003","任务编号不存在或已反馈过!"),
/**
* 重复下载数据超过5次,需要调用反馈接口进行反馈。
*/
file_down_repeat_error("30004","重复下载数据超过5次,需要调用反馈接口进行反馈!可根据data节点中的任务编号反馈");
private String code;
private String message;
ResultEnum(String code,String message) {
this.code = code;
this.message = message;
}
@Override
public String getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
package com.yxcheng.token.common.exception;
import com.yxcheng.token.common.enumutil.AcceptErrorEnum;
/**
* 自定义业务异常-通用系统异常,表示所有未知原因引起的系统异常
*
* @author wuyuegang
*
*/
public class AcceptException extends MyBaseException
{
/**
* auto generate
*/
private static final long serialVersionUID = 8912473097017237022L;
/**
* construct
*
* @param errorCode
* @param errorMsg
*/
public AcceptException(String errorCode, String errorMsg)
{
super(errorCode, errorMsg);
}
public AcceptException(AcceptErrorEnum error)
{
super(error.getCode(), error.getMsg());
}
}
package com.yxcheng.token.common.exception;
public class LimitException extends Exception {
String errorMsg;
public String getErrorMsg() {
return this.errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public LimitException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
}
package com.yxcheng.token.common.exception;
public class MyBaseException extends Exception{
private static final long serialVersionUID = 8177301895983119239L;
String errorCode;
String errorMsg;
public String getErrorCode() {
return this.errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return this.errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public MyBaseException(String errorCode, String errorMsg) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
}
package com.yxcheng.token.common.exception.handler;
import com.alibaba.fastjson.JSONObject;
import com.yxcheng.token.common.enumutil.AcceptErrorEnum;
import com.yxcheng.token.common.enumutil.ResultEnum;
import com.yxcheng.token.common.exception.AcceptException;
import com.yxcheng.token.common.exception.LimitException;
import com.yxcheng.token.common.exception.MyBaseException;
import com.yxcheng.token.common.model.BaseJsonModel;
import com.yxcheng.token.common.model.JsonResult;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ResponseStatus;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Map;
public class BaseGlobalExceptionHandler
{
private final Logger logger = LoggerFactory.getLogger(getClass());
protected static final String DEFAULT_ERROR_MESSAGE = "系统异常,请稍后再试";
protected JsonResult<BaseJsonModel> handleError(HttpServletRequest req, HttpServletResponse rsp, Exception e)
throws Exception
{
//异常时输入请求参数
String contentType = req.getContentType();//获取请求的content-type
if(StringUtils.isNotBlank(contentType) && (contentType.contains("multipart/form-data") || contentType.contains("application/json"))){//文件上传请求 json传输 *特殊请求
//上传文件获取第一个入参对象。
this.logger.warn("Request: {} raised exception params:{}", new Object[] { req.getRequestURI(), charReader(req)});
}else{//非文件上传请求
Map paramsMap = req.getParameterMap();
this.logger.warn("Request: {} raised exception params:{}", new Object[] { req.getRequestURI(), JSONObject.toJSONString(paramsMap)});
}
String errorMsg = "";
String errorCode = "-1";
JsonResult<BaseJsonModel> result = null;
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
throw e;
}
if ((e instanceof UndeclaredThrowableException)) {
e = (Exception)((UndeclaredThrowableException)e).getUndeclaredThrowable();
}
if ((e instanceof MyBaseException))
{
errorCode = ((MyBaseException)e).getErrorCode();
errorMsg = ((MyBaseException)e).getErrorMsg();
result = new JsonResult((MyBaseException)e);
this.logger.warn("Request: {} raised exception errcode:{} errmsg:{}", new Object[] { req.getRequestURI(), errorCode, errorMsg });
}
if(e instanceof LimitException){
result = new JsonResult().errorResponse(ResultEnum.limit_access);
}
else
{
errorMsg = e.getMessage() != null ? e.getMessage() : DEFAULT_ERROR_MESSAGE;
AcceptException sysException = new AcceptException(AcceptErrorEnum.SYSTEM_ERROR);
result = new JsonResult(sysException);
this.logger.error("Request: {} raised exception errcode:{} errmsg:{}", new Object[] { req.getRequestURI(), errorCode, errorMsg });
}
return result;
}
protected JsonResult<BaseJsonModel> handleMyError(HttpServletRequest req, HttpServletResponse rsp, MyBaseException e)
throws Exception
{
String errorMsg = "";
String errorCode = "-1";
JsonResult<BaseJsonModel> result = null;
errorCode = e.getErrorCode();
errorMsg = e.getErrorMsg();
result = new JsonResult(e);
this.logger.warn("Request: {} raised exception errcode:{} errmsg:{}", new Object[] { req.getRequestURI(), errorCode, errorMsg });
return result;
}
public String charReader(HttpServletRequest request) {
BufferedReader br = null;
String str, wholeStr = "";
try {
br = request.getReader();
while((str = br.readLine()) != null){
wholeStr += str;
}
} catch (IOException e) {
e.printStackTrace();
}
return wholeStr;
}
}
package com.yxcheng.token.common.exception.handler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yxcheng.token.common.exception.MyBaseException;
import com.yxcheng.token.common.model.BaseJsonModel;
import com.yxcheng.token.common.model.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;
@ControllerAdvice
public class GlobalExceptionHandler
extends BaseGlobalExceptionHandler
{
@ExceptionHandler({NoHandlerFoundException.class})
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public JsonResult<BaseJsonModel> handle404Error(HttpServletRequest req, HttpServletResponse rsp, Exception e)
throws Exception
{
return handleError(req, rsp, e);
}
@ExceptionHandler({Exception.class})
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public JsonResult<BaseJsonModel> handle500Error(HttpServletRequest req, HttpServletResponse rsp, Exception e)
throws Exception
{
return handleError(req, rsp, e);
}
// @ExceptionHandler({MyBaseException.class})
// @ResponseStatus(HttpStatus.OK)
// @ResponseBody
// public JsonResult<BaseJsonModel> handleMyException(HttpServletRequest req, HttpServletResponse rsp, MyBaseException e)
// throws Exception
// {
// return handleMyError(req, rsp, e);
// }
}
package com.yxcheng.token.common.limit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* redis 分布式集群限流工具类,采用滑动时间窗口的算法来进行计数统计和限流判断
*
* @author wuyuegang
*
*/
@Component
public class RedisLimiter
{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final String LIMIT_TIME_KEY_SUFFIX = ".time_key";
private static final String LIMIT_COUNTER_KEY_SUFFIX = ".counter_key";
/**
* 类锁,用于并发控制
*/
public static Object lock = new Object();
/**
* 注入redis操作工具类
*/
@Autowired
private RedisUtil redisUtil;
/**
* 根据key值向redis申请资源,如果超过限流值,直接返回false
*
* @param key 限流关键字,通常为 className+"."+methodName
* @param count 限流数量
* @param unitTime 限流单位时间
* @return
*/
public boolean tryAcquire(String key, int count, long unitTime)
{
// 定义时间窗口key,规则:key+常量后缀
String timeKey = key + LIMIT_TIME_KEY_SUFFIX;
// 定义计数器key,规则:key+常量后缀
String counterKey = key + LIMIT_COUNTER_KEY_SUFFIX;
long start = System.currentTimeMillis();
try
{
if (!redisUtil.exists(timeKey))
{ // 如果不存在时间窗口key值,初始化一个时间窗口,放到redis缓存
synchronized (lock) // 为了线程安全,加类锁判断,确保多线程环境下,只初始化一次
{
if (!redisUtil.exists(timeKey))
{
redisUtil.set(timeKey, "0", unitTime);
// 同时置空计数器
redisUtil.set(counterKey, "0");// count reset to 0
if (logger.isDebugEnabled())
{
logger.debug("RedisLimiter init timeKey[{}] counterKey[{}]", timeKey, counterKey);
}
}
}
}
if (redisUtil.exists(timeKey) && redisUtil.incrby(counterKey, (long)1) > count)
{
if (logger.isInfoEnabled())
{
logger.info("RedisLimiter tryAcquire key[{}] exceed count [{}], return false, cost[{}]ms",
timeKey,
count,
(System.currentTimeMillis() - start));
}
// 如果在当前时间窗口下,计数器超过允许的限流count,直接返回false
return false;
}
}
catch (Exception e)
{// 遇到任何异常,都应放过限流,不影响业务,并记录错误日志
logger.error("RedisLimiter error when tryAcquire,key[{}] count [{}] cost[{}]ms errormsg [{}]",
timeKey,
count,
(System.currentTimeMillis() - start),
e.getMessage());
}
// 如果没有超过限流值,返回true
return true;
}
}
package com.yxcheng.token.common.limit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.concurrent.TimeUnit;
/**
* Redis操作工具类,采用<b>RedisTemplate</b>封装对Redis的<b>set,get,exists,incrby</b>操作
*
* @author wuyuegang
*
*/
@Component
public class RedisUtil
{
// @Resource
private RedisTemplate redisTemplate;
// @Autowired
// public void setRedisTemplate(RedisTemplate redisTemplate){
// RedisSerializer stringSerializer = new StringRedisSerializer();
// redisTemplate.setKeySerializer(stringSerializer);
// redisTemplate.setValueSerializer(stringSerializer);
// redisTemplate.setHashKeySerializer(stringSerializer);
// redisTemplate.setHashValueSerializer(stringSerializer);
// }
@Autowired(required = false)
public void setRedisTemplate(RedisTemplate redisTemplate) {
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setDefaultSerializer(stringSerializer);
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(stringSerializer);
this.redisTemplate = redisTemplate;
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public boolean exists(final String key)
{
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public Object get(final String key)
{
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value)
{
boolean result = false;
try
{
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value, Long expireTime)
{
boolean result = false;
try
{
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
/**
* 字符串类型: 将key进行递增。如果key不存在,操作之前,key就会被置为0.如果key的value类型错误或者是个不能表示成数字的字符串,就返回错误。 这个操作最多支持64位有符号的整形数字。
*
* @param key
* @param offset
* @return
*/
public Long incrby(final String key, final Long offset)
{
@SuppressWarnings("unchecked")
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
Object result = operations.get(key);
Long count = Long.valueOf(result.toString());
count = count + 1;
operations.set(key, String.valueOf(count));
return count;
}
}
package com.yxcheng.token.common.model;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.Serializable;
public class BaseJsonModel implements Serializable {
private static final long serialVersionUID = -7532190300864165247L;
private transient SerializerFeature[] features = new SerializerFeature[3];
public BaseJsonModel() {
this.features[0] = SerializerFeature.QuoteFieldNames;
this.features[1] = SerializerFeature.WriteMapNullValue;
this.features[2] = SerializerFeature.WriteNullStringAsEmpty;
}
public String toString() {
return JSON.toJSONString(this, this.features);
}
public String toString(SerializeFilter... filters) {
return filters == null ? JSON.toJSONString(this, this.features) : JSON.toJSONString(this, filters, this.features);
}
}
package com.yxcheng.token.common.model;
import java.util.HashMap;
import java.util.Map;
/**
* ClassName:CommonConstant
* Function: 常量维护类
* Date: 2017年12月9日10:34:10
* @author admin
* @see
*/
public class CommonConstant {
/**租户管理导入下级机构校验参数map*/
public static final Map<String, String> UPLOAD_FPXX_MAP = new HashMap<String, String>();
static{
UPLOAD_FPXX_MAP.put("0", "批次号");
UPLOAD_FPXX_MAP.put("6", "批次号验收单号");
UPLOAD_FPXX_MAP.put("11", "发票代码");
UPLOAD_FPXX_MAP.put("12", "发票号码");
UPLOAD_FPXX_MAP.put("13", "含税金额");
}
}
\ No newline at end of file
package com.yxcheng.token.common.model;
import com.yxcheng.token.common.enumutil.ResultEnum;
/**
* Created by waitupon17 on 2017/2/16.
*/
public class CrRpcResult<T> {
private String code = "0";
private String message = "成功";
private T data;
public CrRpcResult()
{
}
private T error(String code, String message) {
this.code = code;
this.message = message;
return (T)this;
}
public CrRpcResult(String code, String message) {
this.code = code;
this.message = message;
}
public CrRpcResult(String code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
public T errorResponse(ResultEnum resultEnum) {
return error(resultEnum.getCode(), resultEnum.getMessage());
}
public String getCode()
{
return code;
}
public void setCode(String code)
{
this.code = code;
}
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public boolean isSuccess(){
return "0".equals(code);
}
}
package com.yxcheng.token.common.model;
import com.alibaba.fastjson.annotation.JSONField;
import com.yxcheng.token.common.enumutil.ResultEnum;
import com.yxcheng.token.common.exception.MyBaseException;
import com.yxcheng.token.utils.StringUtil;
/**
* 返回结果类,封装了统一的返回json结果格式,使用方法参考下面的例子: <br/>
* {"data":[],"errorCode":-1,"errorMsg":"系统异常,请稍后再试","success":false} <br/>
* {"data":[{"adress":"beijing","age":20,"name":"test"},{"adress":"shanghai","age":30,"name":"abc"}],"errorCode":0,"errorMsg":"","success":true}
* <br/>
* {"data":[{"adress":"hangzhou","age":50,"name":"ttt"}],"errorCode":0,"errorMsg":"","success":true} <br/>
* <p>
* 使用方法举例:<br/>
* <p>
* <b>1、返回异常结果</b><br/>
* SystemException e = new SystemException(SystemErrorEnum.SYSTEM_ERROR);<br/>
* BWJsonResult result = new BWJsonResult(e);<br/>
* System.out.println(result.toString());<br/>
* <p>
* <b>2、返回List正常结果</b><br/>
* public Class ProductVO extends BaseJsonModel { ... } 定义bean对象,必须继承基类 BaseJsonModel <br/>
* List &lt;ProductVO&gt list = new ArrayList&lt;ProductVO&gt();<br/>
* BWJsonResult &lt;ProductVO&gt result = new BWJsonResult&lt;ProductVO&gt(list);<br/>
* System.out.println(result.toString());<br/>
* <p>
* <b>3、返回Object正常结果</b><br/>
* public Class ProductVO extends BaseJsonModel { ... } 定义bean对象,必须继承基类 BaseJsonModel <br/>
* ProductVO m3 = new ProductVO();<br/>
* BWJsonResult &lt;ProductVO&gt result = new BWJsonResult&lt;ProductVO&gt(m3);<br/>
* System.out.println(result.toString());<br/>
*
* @author dwh
* @version
* @since JDK 1.8
* @see BaseJsonModel
*/
public class JsonResult<T> extends BaseJsonModel
{
private static final long serialVersionUID = -7532190660864165247L;
/**
* 返回值的成功标志
* 判断反馈结构是成功还是失败,一律根据此字段。
*/
@JSONField
private boolean success = true;
/**
* 错误码,成功时为0,失败时由SystemErrorEnum枚举定义
*/
@JSONField
private String errorCode = "0";
/**
* 信息字段,成功时开发者自填,失败时由SystemErrorEnum枚举定义
*/
@JSONField
private String message = "成功";
@JSONField
private String retrySecond = "";
/**
* 返回值list,所有的返回对象值都在data中,它是一个集合
*/
@JSONField
private T data = null;
/**
*
* BaseJsonResult:(构造方法,入参为自定义异常). <br/>
* 如果异常不为空,则success设置为false,返回异常码和异常信息
*
* @author wuyuegang
* @param exception
* @since JDK 1.8
*/
public JsonResult(MyBaseException exception)
{
if (exception != null)
{
this.success = false;
this.errorCode = exception.getErrorCode();
this.message = exception.getErrorMsg();
}
}
public JsonResult(){
}
/**
*
* Creates a new instance of BWJsonResult.
*
* @param data
*/
public JsonResult(T data)
{
this.data = data;
}
public JsonResult errorResponse(ResultEnum errorEnum){
this.errorCode = errorEnum.getCode();
this.message = errorEnum.getMessage();
this.success = false;
return this;
}
public JsonResult errorResponse(ResultEnum errorEnum, String errorCode, String errorMessage, String retrySecond){
this.errorCode = errorEnum.getCode();
this.message = errorEnum.getMessage();
if(StringUtil.isNotEmpty(errorMessage)) {
this.message = "(" + errorCode + ")" + errorMessage;
}
this.retrySecond = retrySecond;
this.success = false;
return this;
}
public JsonResult success(ResultEnum errorEnum){
this.errorCode = errorEnum.getCode();
this.message = errorEnum.getMessage();
this.success = true;
return this;
}
public JsonResult success(String errorCode,String message){
this.errorCode = errorCode;
this.message = message;
this.success = true;
return this;
}
public JsonResult error(String errorCode,String message){
this.errorCode = errorCode;
this.message = message;
this.success = false;
return this;
}
public static JsonResult errorResult(String errorCode,String message){
JsonResult result = new JsonResult();
result.setErrorCode(errorCode);
result.setMessage(message);
result.setSuccess(false);
return result;
}
public static <T>JsonResult<T> erroCrRpcResult(CrRpcResult<T> crRpcResult){
JsonResult<T> result = new JsonResult<T>();
result.setErrorCode(crRpcResult.getCode());
result.setMessage(crRpcResult.getMessage());
result.setSuccess(false);
return result;
}
public JsonResult successResponse() {
return success(ResultEnum.ok);
}
public boolean isSuccess()
{
return success;
}
public void setSuccess(boolean success)
{
this.success = success;
}
public String getErrorCode()
{
return errorCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public T getData()
{
return data;
}
public void setData(T data) {
this.data = data;
}
public String getRetrySecond() {
return retrySecond;
}
public void setRetrySecond(String retrySecond) {
this.retrySecond = retrySecond;
}
}
package com.yxcheng.token.common.model;
import java.io.Serializable;
public interface MqMessage extends Serializable {
}
/**
* Project Name:acceptance-service
* File Name:ProductVO.java
* Package Name:com.baiwang.cloud.acceptance.service.model
* Date:2017年10月20日下午3:42:55
* Copyright (c) 2017, wuyuegang@baiwang.com All Rights Reserved.
*
*/
package com.yxcheng.token.common.model;
/**
* ClassName:ProductVO测试对象,可以删除 <br/>
* Function: 测试,必须继承基类BaseJsonModel. <br/>
* Reason: 测试. <br/>
* Date: 2017年10月20日 下午3:42:55 <br/>
*
* @author wuyuegang
* @version
* @since JDK 1.8
* @see
*/
public class ProductVO extends BaseJsonModel
{
/**
* name
*/
private String name;
/**
* address
*/
private String address;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
}
package com.yxcheng.token.common.model;
import org.apache.commons.lang.StringUtils;
/**
* Created by 曹小红 on 2017-04-11.
*/
public class RestfulApi {
private String accessKeyID;
private String timeStamp;
private String signatureNonce;
private String version;
private String data;
private String signature;
private String type;
private String taxno;
public String getAccessKeyID() {
return accessKeyID;
}
public void setAccessKeyID(String accessKeyID) {
this.accessKeyID = accessKeyID;
}
public String getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(String timeStamp) {
this.timeStamp = timeStamp;
}
public String getSignatureNonce() {
return signatureNonce;
}
public void setSignatureNonce(String signatureNonce) {
this.signatureNonce = signatureNonce;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTaxno() {
return taxno;
}
public void setTaxno(String taxno) {
this.taxno = taxno;
}
public boolean isHaveNull() {
if(StringUtils.isEmpty(getAccessKeyID())
|| StringUtils.isEmpty(getTimeStamp()) || StringUtils.isEmpty(getSignatureNonce())
|| StringUtils.isEmpty(getVersion()) || StringUtils.isEmpty(getSignature())) {
return true;
}
return false;
}
public String getSignStr() {
return "accessKeyID=" + getAccessKeyID() + "&signatureNonce=" + getSignatureNonce()
+ "&timeStamp=" + getTimeStamp() + "&version=" + getVersion();
}
public String getCapitalSignStr() {
return "AccessKeyID=" + getAccessKeyID() + "&SignatureNonce=" + getSignatureNonce()
+ "&TimeStamp=" + getTimeStamp() + "&Version=" + getVersion();
}
}
package com.yxcheng.token.common.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class RuleModel {
private String taxno;
private String userName;
private String ipAddr;
private String functionCode;
}
package com.yxcheng.token.common.model;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
@Getter
@Setter
public class SafeModel implements Serializable {
private String accessKeyID;
private String signature;
private String signatureNonce;
private String timeStamp;
private String version;
private String taxno;
public void clearSafeData(){
this.accessKeyID = null;
this.signature = null;
this.signatureNonce = null;
this.timeStamp = null;
this.version = null;
this.taxno = null;
}
}
package com.yxcheng.token.common.model;
import lombok.Data;
@Data
public class SocketSendBean {
/**
* OpenDevice,
* MakeClientHello,
* MakeClientAuth,
* GetTaxNO,
* GetSign,
* GetToken,
* CloseDevice
* init
*/
private String operationType;
private String certno;
private String token;
private String online;
}
package com.yxcheng.token.common.model;
import lombok.Data;
@Data
public class SocketSendMsg<T> {
private int code;
private String errMsg;
private T data;
}
package com.yxcheng.token.common.model;
import lombok.Getter;
import lombok.Setter;
/**
* @ProjectName: tax-sys
* @Package: com.tax.token.model
* @ClassName: TaxUserInfo
* @Author: ddx
* @Description: ${description}
* @Date: 2023-01-31 14:53
* @Version: 1.0
*/
@Getter
@Setter
public class TaxUserInfo {
/**
* 省份编码
*/
private String provinceCode = "";
/**
* 税号
*/
private String nsrsbh = "";
/**
* 登录账号
*/
private String username = "";
/**
* 手机号
*/
private String phone = "";
/**
* 密码1
*/
private String password = "";
/**
* 密码2
*/
private String password2 = "";
/**
* 身份类型
*/
private String userType = "";
/**
* 用户姓名|自然人姓名
*/
private String realname = "";
/**
* 主管税务机关名称
*/
private String taxstation = "";
/**
* 身份证号(后四位),看具体参数,身份证相关的就存到这里
*/
private String idcard = "";
/**
* 企业名称
*/
private String companyName = "";
/**
* 手机验证码
*/
private String verifyCode = "";
private String loginType = "";
private String index = "";
private String serNo = "";
@Override
public String toString() {
return "TaxUserInfo{" +
"provinceCode='" + provinceCode + '\'' +
// ", nsrsbh='" + nsrsbh + '\'' +
", username='" + username + '\'' +
", phone='" + phone + '\'' +
", password='" + password + '\'' +
", password2='" + password2 + '\'' +
", userType='" + userType + '\'' +
", realname='" + realname + '\'' +
", taxstation='" + taxstation + '\'' +
", idcard='" + idcard + '\'' +
// ", companyName='" + companyName + '\'' +
", loginType='" + loginType + '\'' +
// ", index='" + index + '\'' +
// ", serNo='" + serNo + '\'' +
'}';
}
}
package com.yxcheng.token.common.model;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UserReq extends SafeModel {
private String taxno;
private String userName;
private String taxName;
private String applyFunction;
private String ip;
}
package com.yxcheng.token.common.service;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Autowired;
import com.yxcheng.token.utils.StringUtil;
public abstract class AbstractService<M extends BaseMapper<E,T>,E,T> implements BaseServiceI<E,T> {
public static Map<String,String> tableMap = new ConcurrentHashMap();
public static final String INVOICE_FRONT = "fin_invoice_";
@Autowired
protected M baseMapper;
@Override
public int countByExample(E example) {
return baseMapper.countByExample(example);
}
@Override
public int deleteByExample(E example) {
return baseMapper.deleteByExample(example);
}
@Override
public int deleteByPrimaryKey(Serializable id) {
return baseMapper.deleteByPrimaryKey(id);
}
@Override
public int insert(T record) {
return baseMapper.insert(record);
}
@Override
public int insertSelective(T record) {
return baseMapper.insertSelective(record);
}
@Override
public T getOne(E example){
List<T> list = this.selectByExample(example);
if(list!=null && list.size()>0){
return this.selectByExample(example).get(0);
}
return null;
}
@Override
public List<T> selectByExample(E example) {
return baseMapper.selectByExample(example);
}
@Override
public T selectByPrimaryKey(Serializable id) {
return baseMapper.selectByPrimaryKey(id);
}
@Override
public int updateByExampleSelective(T record, E example) {
return baseMapper.updateByExampleSelective(record,example);
}
@Override
public int updateByExample(T record, E example) {
return baseMapper.updateByExample(record,example);
}
@Override
public int updateByPrimaryKeySelective(T record) {
return baseMapper.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(T record) {
return baseMapper.updateByPrimaryKey(record);
}
}
package com.yxcheng.token.common.service;
import java.io.Serializable;
import java.util.List;
public interface BaseMapper<E,T> {
int countByExample(E example);
int deleteByExample(E example);
int deleteByPrimaryKey(Serializable id);
int insert(T record);
int insertSelective(T record);
List<T> selectByExample(E example);
T selectByPrimaryKey(Serializable id);
int updateByExampleSelective(T record, E example);
int updateByExample(T record, E example);
int updateByPrimaryKeySelective(T record);
int updateByPrimaryKey(T record);
}
package com.yxcheng.token.common.service;
import java.io.Serializable;
import java.util.List;
public interface BaseServiceI<E,T> {
int countByExample(E example);
int deleteByExample(E example);
int deleteByPrimaryKey(Serializable id);
int insert(T record);
int insertSelective(T record);
T getOne(E example);
List<T> selectByExample(E example);
T selectByPrimaryKey(Serializable id);
int updateByExampleSelective(T record, E example);
int updateByExample(T record, E example);
int updateByPrimaryKeySelective(T record);
int updateByPrimaryKey(T record);
}
package com.yxcheng.token.common.template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Instant;
public abstract class ApiTemplate<T> {
private static final String SUCCEED_POSTFIX = "_SUCCEED";
private static final String FAILED_POSTFIX = "_FAILED";
protected Logger logger = LoggerFactory.getLogger(getClass());
protected String monitorKey;
protected ApiTemplate(String monitorKey) {
this.monitorKey = monitorKey;
}
protected void checkParams() {
}
protected abstract T process() throws Exception;
protected void onFinish() {
}
protected void onSuccess() {
}
protected void onError(Throwable e) {
}
public T execute() {
try {
checkParams();
} catch (IllegalArgumentException e) {
logger.debug("check param failed", e);
throw e;
}
Instant start = Instant.now();
try {
T result = process();
onSuccess();
Instant end = Instant.now();
long duration = end.toEpochMilli() - start.toEpochMilli();
logger.info("{} finished,cost:{}ms",monitorKey, duration);
return result;
} catch (Throwable e) {
Instant end = Instant.now();
long duration = end.toEpochMilli() - start.toEpochMilli();
logger.warn("unexpected error while execute", e);
onError(e);
throw new RuntimeException("unexpected error", e);
} finally {
Instant end = Instant.now();
onFinish();
}
}
}
package com.yxcheng.token.common.threadpool;
import org.springframework.beans.factory.annotation.Value;
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.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ResetThreadPool {
@Value("${spring.threadPool.reset.corePoolSize}")
protected int corePoolSize = 10;//线程池维护线程的最少数量
@Value("${spring.threadPool.reset.maxPoolSize}")
protected int maxPoolSize = 30;//线程池维护线程的最大数量
@Value("${spring.threadPool.reset.queueCapacity}")
protected int queueCapacity = 8; //缓存队列
@Value("${spring.threadPool.reset.keepAlive}")
protected int keepAlive = 60;//允许的空闲时间
@Bean
public Executor resetExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix("resetExecutor-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //对拒绝task的处理策略
executor.setKeepAliveSeconds(keepAlive);
executor.initialize();
return executor;
}
}
package com.yxcheng.token.common.threadpool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class TaskThreadPoolConfig {
@Value("${spring.threadPool.main.corePoolSize}")
protected int corePoolSize = 10;//线程池维护线程的最少数量
@Value("${spring.threadPool.main.maxPoolSize}")
protected int maxPoolSize = 30;//线程池维护线程的最大数量
@Value("${spring.threadPool.main.queueCapacity}")
protected int queueCapacity = 8; //缓存队列
@Value("${spring.threadPool.main.keepAlive}")
protected int keepAlive = 60;//允许的空闲时间
public int getCorePoolSize() {
return corePoolSize;
}
public void setCorePoolSize(int corePoolSize) {
this.corePoolSize = corePoolSize;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public int getQueueCapacity() {
return queueCapacity;
}
public void setQueueCapacity(int queueCapacity) {
this.queueCapacity = queueCapacity;
}
public int getKeepAlive() {
return keepAlive;
}
public void setKeepAlive(int keepAlive) {
this.keepAlive = keepAlive;
}
}
package com.yxcheng.token.common.threadpool;
import org.springframework.beans.factory.annotation.Autowired;
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.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ThreadPool {
@Autowired
private TaskThreadPoolConfig config;
@Bean
public Executor myExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.corePoolSize);
executor.setMaxPoolSize(config.maxPoolSize);
executor.setQueueCapacity(config.queueCapacity);
executor.setThreadNamePrefix("mqExecutor-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //对拒绝task的处理策略
executor.setKeepAliveSeconds(config.keepAlive);
executor.initialize();
return executor;
}
@Bean
public Executor downExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(config.corePoolSize);
executor.setMaxPoolSize(config.maxPoolSize);
executor.setQueueCapacity(config.queueCapacity);
executor.setThreadNamePrefix("downExecutor-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //对拒绝task的处理策略
executor.setKeepAliveSeconds(config.keepAlive);
executor.initialize();
return executor;
}
}
package com.yxcheng.token.common.threadpool;
import org.springframework.beans.factory.annotation.Value;
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.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class TokenThreadPool {
@Value("${spring.threadPool.token.corePoolSize}")
protected int corePoolSize = 10;//线程池维护线程的最少数量
@Value("${spring.threadPool.token.maxPoolSize}")
protected int maxPoolSize = 30;//线程池维护线程的最大数量
@Value("${spring.threadPool.token.queueCapacity}")
protected int queueCapacity = 8; //缓存队列
@Value("${spring.threadPool.token.keepAlive}")
protected int keepAlive = 60;//允许的空闲时间
@Bean
public Executor tokenExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix("tokenExecutor-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //对拒绝task的处理策略
executor.setKeepAliveSeconds(keepAlive);
executor.initialize();
return executor;
}
}
package com.yxcheng.token.constants;
public class HttpRedisContants {
public static final String KEY_SPLIT_CHAR = ":";
public static final String INVOICE_EXP_LIST = "taxsys:file:exp:list:";
public static final String COLLECT_LIST_TYPE_FILE = "0";
public static String getInvoiceExpListGroupName(String userName, String taxno, String dataType) {
return INVOICE_EXP_LIST + dataType + KEY_SPLIT_CHAR + userName + KEY_SPLIT_CHAR + taxno;
}
}
package com.yxcheng.token.constants;
public class RedisContants {
//获取token请求次数
public static String TOKEN_REQ_TIMES = "taxsys:token:reqTimes:";
public static String TOKEN_SIGNDATA_TIMES = "taxsys:token:signData:";
public static String TOKEN_ZONE_IS_NEW = "taxsys:token:zoneIsNew:";
public static String TOKEN_WEB_SOCKET = "taxsys:token:websocket:";
public static String TOKEN_WEB_SOCKET_GETSIGN = "taxsys:token:websocket:getSign:";
public static String TOKEN_WEB_SOCKET_ISONLINE = "taxsys:token:socketIsOnline";
public static String TOKEN_TIMEOUT_TIMES = "taxsys:token:timeoutTimes";
//获取日期列表
public static String SIGN_DATE_LIST = "taxsys:sign:dateList:";
//获取百望税号列表
public static String SIGN_TAXNO_LIST = "sign:taxno:list:";
public static String SIGN_IP_LIST = "sign:ip:list:";
//获取token定时任务锁
public static String GET_TOKEN_SCHEDULED_LOCK = "taxsys:token:SynGetTokenJob";
public static int GET_TOKEN_SCHEDULED_EXPIRE = 60 * 30;
//获取token定时任务锁
public static String SYNC_TAXNO_SCHEDULED_LOCK = "taxsys:sign:SyncTaxnoServiceJob";
public static int SYNC_TAXNO_SCHEDULED_EXPIRE = 5*60-2;
//获取token定时任务锁
public static String SYNC_DATE_INFO_LOCK = "taxsys:sign:SynDateInfoJob";
public static int SYNC_DATE_INFO_SCHEDULED_EXPIRE = 24*60*60-2;
//获取token定时任务锁
public static String SYN_GET_SERVERDATE_SCHEDULED_LOCK = "taxsys:sign:SynGetServerDate4ZoneJob";
public static int SYN_GET_SERVERDATE_SCHEDULED_EXPIRE = 60*60-2;
public static String DELIMITER = ":";
public static String NUONUO_TOKEN_TYPE = "taxsys:token:NNtokenType:";
//用户校验key
public static String CHECK_USER = "taxsys:user:checkuser:";
public static String CHECK_FULLINFO = "taxsys:user:fullInfo:";
public static String CHECK_FUNCTION = "taxsys:user:function:";
public static String CHECK_RULE = "taxsys:user:rule:";
public static String CHECK_RULE_IP = "taxsys:user:rule:ip:";
public static String CHECK_USER_TAXNO = "taxsys:user:usertaxno:";
public static String SCAN_VERIFY_CODE = "taxsys:scan:verifycode:";
public static String SCAN_VERIFY_LIMIT = "taxsys:scan:verifylimit:";
public static String SCAN_VERIFY_CODE_CONFIG = "taxsys:scan:verifycodeConfig";
public static String CHECK_SIGNATURENONCE = "taxsys:user:signatureNonce:";
//文件申请
public static String FILE_APPLY_LOCK = "taxsys:file:fileApply:";
public static String FILE_APPLY_TIMES_LOCK = "taxsys:file:fileApply:times:";
public static String FILE_TOKEN_LOCK = "taxsys:file:token:";
public static String FILE_TOKEN_STATUS = "taxsys:file:token:status:";
public static String FILE_APPLY_ALARM = "taxsys:file:apply:alarm:";
//文件下载
public static String FIX_DOWN_FILE_LOCK = "taxsys:file:fixDownFile:";
public static String DOWN_FILE_TIMES_LOCK = "taxsys:file:downFile:times:";
public static String INCOME_FILEID_LOCK = "taxsys:file:incomeFileId:";
//区域管理
public static String ZONE_CODE = "taxsys:zone:code:";
public static String ELE_ZONE_CODE = "taxsys:ele:zone:code:";
public static String FILE_DOWN_MINIO_ERROR_COUNT = "taxsys:file:downFile:minio:error:count";
public static String USER_GROUP_ID = "taxsys:token:user:groupId:";
public static String TOKEN_REALREQUEST_COUNT = "taxsys:token:realRequest:count:";
public static String getCheckRulesByUser(String userName) {
return RedisContants.CHECK_RULE + userName;
}
public static String getCheckTaxnosByUser(String userName, String functionCode, String taxno) {
return RedisContants.CHECK_USER_TAXNO + userName
+ RedisContants.DELIMITER + functionCode
+ RedisContants.DELIMITER + taxno;
}
public static String getLimitName(String functionName, String userName, String taxno) {
return functionName + RedisContants.DELIMITER + userName + RedisContants.DELIMITER + taxno;
}
}
package com.yxcheng.token.constants;
import java.util.HashMap;
import java.util.Map;
/**
* Created by 曹小红 on 2017-04-11.
*/
public class RestFulApiContants {
/**
* 01、异步采集认证
* 02、实时采集认证
* 03、查验
* 04、签名
* 05、token服务
*/
public static final String ASYN_COLLECT_CERTIFIED = "01";
public static final String SYN_COLLECT_CERTIFIED = "02";
public static final String CHECK = "03";
public static final String SIGN = "04";
public static final String TOKEN_SERVICE = "05";
public static Map<String,String> userInfo = null;
//taxsys:user:checkuser:yxclient
static {
userInfo = new HashMap<String, String>();
userInfo.put("baoxiao","bx!pass@");
userInfo.put("dxhy","dxhy@pass");
userInfo.put("daxiang","Gfx#@f26");
userInfo.put("sxc","sxc^234!xm");
//长软
userInfo.put("gwssi","gwssi$%^123");
userInfo.put("bwgf-limit","bw@2u9%5Ts#2");
userInfo.put("gwssitest","gwssi@mla4r34!$");
userInfo.put("gwssiclient","M7I9$m2Y1H");
userInfo.put("signclient-yy","Y3&e3#H2P1");
userInfo.put("signclient-lg","R5%e9$WnQ2");
userInfo.put("karamay","vde-ooi#U3o");
userInfo.put("dxadmin","fehui*!Iuu");
//鹏哥客户端
userInfo.put("yxclient","Lkks#wfv3k!");
//测试账号
userInfo.put("testdwh","Its@#!ita");
userInfo.put("testtyy","test123");
//X账号
userInfo.put("xforce","nop&fcIup");
userInfo.put("tengzhu","tzasd!@#cvw129abc");
userInfo.put("yongyou","yongyou!@#443abd");
userInfo.put("szyh","szyh!@#fkuc2kk");
userInfo.put("banguser","bangong@)!^");
userInfo.put("bwdz","3Ku&r$Ws9M");
userInfo.put("yunzf","pq89#ckki0");
userInfo.put("diliankeji","402880be5ca48207015ca4d367ee10c1");
}
}
package com.yxcheng.token.constants;
import lombok.Data;
@Data
public class WebSocketConstants {
final public static String OpenDevice = "0";
final public static String MakeClientHello = "1";
final public static String MakeClientAuth = "2";
final public static String GetTaxNO = "3";
final public static String GetSign = "4";
final public static String GetToken = "5";
final public static String CloseDevice = "6";
final public static String init = "7";
}
package com.yxcheng.token.gen;
import com.yxcheng.token.utils.MapUtil;
import com.yxcheng.token.utils.StringUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class Gen {
private static final String TEMPLATE_PATH = "tax-common/src/main/resources/ftl/origin";
@Getter private final Configuration configuration;
public Gen() {
this.configuration = new Configuration();
try {
configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IllegalAccessException {
GenEntity entity = new GenEntity();
entity.setModule("sign");
entity.setEntityName("SgCookieConfig");
System.out.println(entity);
new Gen().generate(entity);
}
private void generate(GenEntity entity) throws IllegalAccessException {
Map<String, Object> data = MapUtil.objectToMap(entity);
Map<String, String> ftlPathMap = this.getFtlPathMap(entity);
ftlPathMap.keySet().stream().forEach(flt->{
Template template = null;
Writer out = null;
try {
template = this.getConfiguration().getTemplate(flt);
// step5 生成数据
String javaName = entity.getEntityName() + flt.substring(0,flt.indexOf(".")) + ".java";
File docFile = new File(ftlPathMap.get(flt) + File.separator + javaName);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
// step6 输出文件
template.process(data, out);
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^"+javaName+" 文件创建成功 !\npath:" + docFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.flush();
out.close();
} catch (IOException e) {
}
}
});
}
public Map<String, String> getFtlPathMap(GenEntity entity){
if(entity==null || StringUtils.isBlank(entity.getModule())){
throw new IllegalArgumentException("please input module");
}
String path = "";
Map<String, String> data = new HashMap<String, String>();
String mapperPath = String.format(path +"tax-%s/%s-dao/src/main/java/com/tax/%s/mapper",entity.getModule(),entity.getModule(),entity.getModule());
String serivcePath = String.format(path +"tax-%s/%s-service/src/main/java/com/tax/%s/service/api",entity.getModule(),entity.getModule(),entity.getModule());
String serviceImplPath = String.format(path +"tax-%s/%s-service/src/main/java/com/tax/%s/service/impl",entity.getModule(),entity.getModule(),entity.getModule());
data.put("Mapper.ftl",mapperPath);
data.put("Service.ftl",serivcePath);
data.put("ServiceImpl.ftl",serviceImplPath);
return data;
}
@Data
private static class GenEntity{
private String module;
private String entityName;
}
}
package com.yxcheng.token.gen;
import com.yxcheng.token.utils.MapUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.Data;
import lombok.Getter;
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class GenPlus {
private static final String TEMPLATE_PATH = "tax-common/src/main/resources/ftl/plus";
@Getter private final Configuration configuration;
public GenPlus() {
this.configuration = new Configuration();
try {
configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IllegalAccessException {
GenEntity entity = new GenEntity();
entity.setModule("file");
entity.setEntityName("FileToken");
System.out.println(entity);
new GenPlus().generate(entity);
}
private void generate(GenEntity entity) throws IllegalAccessException {
Map<String, Object> data = MapUtil.objectToMap(entity);
Map<String, String> ftlPathMap = this.getFtlPathMap(entity);
ftlPathMap.keySet().stream().forEach(flt->{
Template template = null;
Writer out = null;
try {
template = this.getConfiguration().getTemplate(flt);
// step5 生成数据
String javaName = entity.getEntityName() + flt.substring(0,flt.indexOf(".")) + ".java";
File docFile = new File(ftlPathMap.get(flt) + File.separator + javaName);
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
// step6 输出文件
template.process(data, out);
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^"+javaName+" 文件创建成功 !\npath:" + docFile.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
out.flush();
out.close();
} catch (IOException e) {
}
}
});
}
public Map<String, String> getFtlPathMap(GenEntity entity){
if(entity==null || StringUtils.isBlank(entity.getModule())){
throw new IllegalArgumentException("please input module");
}
String path = "";
Map<String, String> data = new HashMap<String, String>();
String mapperPath = String.format(path +"tax-%s/%s-dao/src/main/java/com/tax/%s/mapper",entity.getModule(),entity.getModule(),entity.getModule());
String serivcePath = String.format(path +"tax-%s/%s-service/src/main/java/com/tax/%s/service/api",entity.getModule(),entity.getModule(),entity.getModule());
String serviceImplPath = String.format(path +"tax-%s/%s-service/src/main/java/com/tax/%s/service/impl",entity.getModule(),entity.getModule(),entity.getModule());
data.put("Mapper.ftl",mapperPath);
data.put("Service.ftl",serivcePath);
data.put("ServiceImpl.ftl",serviceImplPath);
return data;
}
@Data
private static class GenEntity{
private String module;
private String entityName;
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.yxcheng.token.utils;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
public class AESSecurityUtil {
public static final String ALGORITHM = "AES";
public static final String Charsets = "utf-8";
public AESSecurityUtil() {
}
public static String encrypt(String data, String key) throws GeneralSecurityException, UnsupportedEncodingException {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(1, secretKeySpec);
byte[] encryptValue = cipher.doFinal(data.getBytes("utf-8"));
Base64 base64 = new Base64();
byte[] encodeValue = base64.encode(encryptValue);
return new String(encodeValue, "utf-8");
}
public static String decrypt(String data, String key) throws GeneralSecurityException, UnsupportedEncodingException {
Base64 base64 = new Base64();
byte[] decodeValue = base64.decode(data.getBytes("utf-8"));
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("utf-8"), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(2, secretKeySpec);
byte[] decryptValue = cipher.doFinal(decodeValue);
return new String(decryptValue, "utf-8");
}
public static void main(String[] args) throws Exception {
// String data = "百望股份-让天下没有难开的发票1,百望股份-让天下没有难开的发票,百望股份-让天下没有难开的发票,百望股份-让天下没有难开的发票,百望股份-让天下没有难开的发票";
// String key = "BWCSDK2017090688";
// String text = encrypt(data, key);
// System.out.println(text);
// System.out.println(decrypt(text, key));
}
public static String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0; i < length; ++i) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
package com.yxcheng.token.utils;
import java.io.UnsupportedEncodingException;
public class Base64Util {
public static final String DEFAULT_CODE = "UTF-8";
private static char[] base64EncodeChars = new char[]{
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/'};
private static byte[] base64DecodeChars = new byte[]{
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1};
public static String encode(byte[] data) {
StringBuffer sb = new StringBuffer();
int len = data.length;
int i = 0;
int b1, b2, b3;
while (i < len) {
b1 = data[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
}
b2 = data[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
}
b3 = data[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
}
public static String encode(String data) throws UnsupportedEncodingException {
return encode(data.getBytes(DEFAULT_CODE));
}
public static String encode(String data, String code) throws UnsupportedEncodingException {
return encode(data.getBytes(code));
}
public static byte[] decode(String str) throws UnsupportedEncodingException {
StringBuffer sb = new StringBuffer();
byte[] data = str.getBytes("US-ASCII");
int len = data.length;
int i = 0;
int b1, b2, b3, b4;
while (i < len) {
do {
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1) break;
do {
b2 = base64DecodeChars
[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1) break;
sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
do {
b3 = data[i++];
if (b3 == 61) return sb.toString().getBytes("iso8859-1");
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1) break;
sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
do {
b4 = data[i++];
if (b4 == 61) return sb.toString().getBytes("iso8859-1");
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1) break;
sb.append((char) (((b3 & 0x03) << 6) | b4));
}
return sb.toString().getBytes("iso8859-1");
}
public static void main(String[] args) {
try {
System.out.println(new String(Base64Util.decode("euW8oOi/m+iNo1thJWJAcV1BYTE5MDAwMFthJWJAcV0="), "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.yxcheng.token.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.NPOIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* excel读写工具类
*
* */
@Slf4j
public class ExcelReadUtil {
private final static String xls = "xls";
private final static String xlsx = "xlsx";
/**
* 根据URL获取inputStream输入流
*
* @param timeout 超时时间 单位毫秒
* @return
*/
public static InputStream getInputStreamByUrl(String urlAddr,int timeout) throws Exception{
URL url = new URL(urlAddr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(timeout);//设置超时间
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); //防止屏蔽程序抓取而返回403错误
BufferedInputStream input = new BufferedInputStream(conn.getInputStream());
return input;
}
/**
* 复制inputStream输入流,创建Workbook实例的时候流会关闭,可以根据复制的流创建实例
*
* @param inputStream
* @return inputStream
* @return
*/
public static InputStream inputStreamClone(InputStream inputStream) throws Exception{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
IOUtils.copy(inputStream, outputStream);
//转换成字节数组
byte[] byteArray = outputStream .toByteArray();
ByteArrayInputStream inputStreamClone = new ByteArrayInputStream(byteArray);
return inputStreamClone;
}
/**
* 读入excel文件,解析后返回
* @param inputStream
* @throws IOException
*/
public static List<String[]> readExcel(InputStream inputStream) throws Exception{
//获得Workbook工作薄对象
Workbook workbook = getWorkBook(inputStream);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List<String[]> list = new ArrayList<String[]>();
if(workbook != null){
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
//获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
//循环除了第一行的所有行
for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
//获得当前行
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
}
return list;
}
/**
* 读入excel文件,解析后返回
* @param file
* @throws IOException
*/
public static List<String[]> readExcel(MultipartFile file) throws IOException{
//检查文件
checkFile(file);
//获得Workbook工作薄对象
Workbook workbook = getWorkBook(file);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List<String[]> list = new ArrayList<String[]>();
if(workbook != null){
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
//获得当前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
//获得当前sheet的开始行
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行
int lastRowNum = sheet.getLastRowNum();
//循环除了第一行的所有行
for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
//获得当前行
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//获得当前行的开始列
int firstCellNum = row.getFirstCellNum();
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
String[] cells = new String[row.getPhysicalNumberOfCells()];
//循环当前行
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
}
return list;
}
/**
* 检查excel文件
* @param file
* @throws IOException
*/
public static void checkFile(MultipartFile file) throws IOException{
//判断文件是否存在
if(null == file){
log.error("文件不存在!");
throw new FileNotFoundException("文件不存在!");
}
//获得文件名
String fileName = file.getOriginalFilename();
//判断文件是否是excel文件
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
log.error(fileName + "不是excel文件");
throw new IOException(fileName + "不是excel文件");
}
}
/**
* 创建工作簿
* @param fis
* @throws InvalidFormatException
*/
public static Workbook getWorkBook(InputStream fis) throws Exception{
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
NPOIFSFileSystem fs = new NPOIFSFileSystem(fis);
workbook = WorkbookFactory.create(fs);
return workbook;
}
/**
* 创建工作簿
* @param file
*/
public static Workbook getWorkBook(MultipartFile file) {
//获得文件名
String fileName = file.getOriginalFilename();
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
log.info(e.getMessage());
}
return workbook;
}
/**
* 获取单元格的值
* @param cell
*/
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
//把数字当成String来读,避免出现1读成1.0的情况
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判断数据的类型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
}
\ No newline at end of file
package com.yxcheng.token.utils;
import java.util.HashMap;
import java.util.Map;
/**
* @ProjectName: tax-sys-test
* @Package: com.yxcheng.token.constants
* @ClassName: FileDownloadContants
* @Author: ddx
* @Description: ${description}
* @Date: 2022-01-17 14:48
* @Version: 1.0
*/
public class FileDownloadUtil {
public static Map<String, String> gxDic = null;
public static Map<String, String> gxAllDic = null;
public static Map<String, String> invTypeDicG = null;
public static Map<String, String> invTypeDicX = null;
public static Map<String, String> forceFlagDic = null;
static {
gxDic = new HashMap<String, String>();
gxDic.put("1", "进项");
gxDic.put("2", "销项");
gxAllDic = new HashMap<String, String>();
gxAllDic.put("0", "全部");
gxAllDic.putAll(gxDic);
invTypeDicX = new HashMap<String, String>();
invTypeDicX.put("01", "增值税专用发票");
invTypeDicX.put("03", "机动车销售统一发票");
invTypeDicX.put("10", "增值税普通发票(电子)");
invTypeDicX.put("04", "增值税普通发票");
invTypeDicX.put("08", "增值税专用发票(电子)");
invTypeDicX.put("11", "增值税普通发票(卷票)");
invTypeDicX.put("14", "道路通行费电子普通发票");
invTypeDicX.put("15", "二手车销售统一发票");
invTypeDicX.put("81", "电子发票(增值税专用发票)");
invTypeDicX.put("82", "电子发票(普通发票)");
// invTypeDicX.put("83", "电子发票(铁路电子客票)");
invTypeDicX.put("84", "纸质发票(增值税专用发票)");
invTypeDicX.put("85", "纸质发票(增值税普通发票)");
invTypeDicG = new HashMap<String, String>();
invTypeDicG.putAll(invTypeDicX);
invTypeDicG.put("17", "海关缴款书");
forceFlagDic = new HashMap<String, String>();
forceFlagDic.put("0", "正常");
forceFlagDic.put("1", "强制");
}
public static boolean checkForceFlag(String forceFlag) {
return forceFlagDic.containsKey(forceFlag);
}
public static boolean checkInvSpec(String invSpec) {
return gxDic.containsKey(invSpec);
}
public static boolean checkAllInvSpec(String invSpec) {
return gxAllDic.containsKey(invSpec);
}
public static boolean checkInvType(String invSpec, String invType) {
boolean checkInvTypeFlag = false;
if(invSpec.equals(INVTYPE_INCOME)) {
checkInvTypeFlag = invTypeDicG.containsKey(invType);
} else {
checkInvTypeFlag = invTypeDicX.containsKey(invType);
}
return checkInvTypeFlag;
}
//进项
public static String INVTYPE_INCOME = "1";
//销项
public static String INVTYPE_SALE = "2";
}
package com.yxcheng.token.utils;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Maps;
public class FinValidUtils {
//老式电子发票
public static String OLD_ELECTRONIC_INVOICE_TYPE="10";
//电子发票
public static String ELECTRONIC_INVOICE_TYPE="10";
//卷式发票
public static String ROLL_INVOICE_TYPE="11";
//机动车发票
public static String MOTOR_VEHICLE_INVOICE_TYPE="03";
//增值税专用发票
public static String VAT_SPA_INVOICE_TYPE="01";
//增值税普通发票
public static String VAT_INVOICE_TYPE="04";
//增值税电子专用发票
public static String ELECTRONIC_VAT_INVOICE_TYPE="08";
//货物运输发票
public static String FREIGHT_INVOICE_TYPE="02";
//通行费发票
public static String TOLL_INVOICE_TYPE="14";
//二手车发票
public static String USED_CAR_TYPE="15";
public static String ERROR_TYPE="00";
public static List<String>oldEleList=Arrays.asList("144031539110","131001570151","133011501118","111001571071");
public static Map<String, String> errorMap = Maps.newHashMap();
static {
errorMap.put("正常", "0");
errorMap.put("失控", "1");
errorMap.put("作废", "2");
errorMap.put("红冲", "3");
errorMap.put("异常", "4");
}
public static String generateType(String code){
if(code!=null){
int length = code.length();
if(oldEleList.contains(code)){
return OLD_ELECTRONIC_INVOICE_TYPE;
}
if(length == 12){
if(code.startsWith("0")){
String suff2 = code.substring(code.length()-2);
if("11".equals(suff2)){
return ELECTRONIC_INVOICE_TYPE;
}else if("06".equals(suff2) || "07".equals(suff2)){
return ROLL_INVOICE_TYPE;
} else if("12".equals(suff2)) {
return TOLL_INVOICE_TYPE;
} else if("17".equals(suff2)) {
return USED_CAR_TYPE;
} else if("08".equals(suff2)) {
return ELECTRONIC_VAT_INVOICE_TYPE;
}
}else{
if("2".equals(code.substring(7, 8))){
return MOTOR_VEHICLE_INVOICE_TYPE;
}
}
}else if(length == 10){
String eighth = code.substring(7, 8);
if("1".equals(eighth) || "5".equals(eighth)){
return VAT_SPA_INVOICE_TYPE;
}else if("3".equals(eighth) || "6".equals(eighth)){
return VAT_INVOICE_TYPE;
}else if("2".equals(eighth) || "7".equals(eighth)){
return FREIGHT_INVOICE_TYPE;
}
}
}
return ERROR_TYPE;
}
/**
* 获取企业类型
* @param tokenCode
* @return
*/
public static String getCompanyType(String tokenCode) {
String defComType = "1";
if(StringUtil.isNotEmpty(tokenCode)) {
String levelType = tokenCode.split("~")[0];
String comType = tokenCode.split("~")[1];
if(levelType.equals("0") || levelType.equals("5") || levelType.equals("6")) {
defComType = "1";
} else if(comType.equals("2") || comType.equals("3")) {
defComType = comType;
}
}
return defComType;
}
public static String getErrorType(String errorName) {
if(errorMap.containsKey(errorName)) {
return errorMap.get(errorName);
} else {
return null;
}
}
public static void main(String[] args) {
System.out.println(FinValidUtils.generateType("233001900111"));
}
// /**
// * 通过发票代码判断发票类型
// 1、 电子发票
// 特殊的发票代码包括:'144031539110', '131001570151', '133011501118', '111001571071',如果发票代码为以上代码之一,则判定为电子发票。
// 代码长度为12位,首位为0,最后两位为11。
// 2、 通行费发票
// 代码长度为12位,首位为0,最后两位是12。
// 3、 增值税普通发票
// 代码长度为12位,首位为0,最后两位是04或05;
// 代码长度为10位,第8位是3或者6。
// 4、 卷式发票
// 代码长度为12位,首位为0,最后两位是06或07;
// 5、 机动车发票
// 代码长度为12位,首位不是0,第8位是2
// 6、 增值税专用发票
// 代码长度为10位,第8位为1或5。
// 7、 货物运输发票
// 代码长度为10位,第8位为2或7
// 8、 二手车发票
// 代码长度为12位,首位为0,最后两位是17
// 9、增值税电子专用发票
// 代码长度为12位,首位为0,最后两位是08
}
package com.yxcheng.token.utils;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/*
* 利用HttpClient进行post请求的工具类
*/
public class HttpClientUtil {
public String doPost(String url,Map<String,String> map,String charset){
HttpClient httpClient = null;
HttpPost httpPost = null;
String result = null;
try{
httpClient = new SSLClient();
httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT,"IE");
httpPost = new HttpPost(url);
//设置参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Entry<String,String> elem = (Entry<String, String>) iterator.next();
list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
}
if(list.size() > 0){
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if(response != null){
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity,charset);
}
}
}catch(Exception ex){
ex.printStackTrace();
}
return result;
}
}
package com.yxcheng.token.utils;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class HttpConnectionManager
{
private static HttpParams httpParams;
private static ClientConnectionManager connectionManager;
/**
* �?大连接数
*/
public final static int MAX_TOTAL_CONNECTIONS = 500;
/**
* 获取连接的最大等待时�?
*/
public final static int WAIT_TIMEOUT = 300000;
/**
* 每个路由�?大连接数
*/
public final static int MAX_ROUTE_CONNECTIONS = 400;
/**
* 连接超时时间
*/
public final static int CONNECT_TIMEOUT = 15000;
/**
* 读取超时时间
*/
public final static int READ_TIMEOUT = 15000;
static
{
httpParams = new BasicHttpParams();
// 设置�?大连接数
ConnManagerParams.setMaxTotalConnections(httpParams,
MAX_TOTAL_CONNECTIONS);
// 设置获取连接的最大等待时�?
ConnManagerParams.setTimeout(httpParams, WAIT_TIMEOUT);
// 设置每个路由�?大连接数
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(
MAX_ROUTE_CONNECTIONS);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams, connPerRoute);
// 设置连接超时时间
HttpConnectionParams.setConnectionTimeout(httpParams, CONNECT_TIMEOUT);
// 设置读取超时时间
HttpConnectionParams.setSoTimeout(httpParams, READ_TIMEOUT);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https",
SSLSocketFactory.getSocketFactory(), 443));
connectionManager = new ThreadSafeClientConnManager(httpParams,
registry);
}
public static HttpClient getHttpClient()
{
return new DefaultHttpClient(connectionManager, httpParams);
}
public static HttpClient httpsTrustClient()
{
HttpClient base = getHttpClient();
try
{
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager()
{
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException
{
// TODO Auto-generated method stub
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException
{
// TODO Auto-generated method stub
}
public X509Certificate[] getAcceptedIssuers()
{
// TODO Auto-generated method stub
return null;
}
};
ctx.init(null, new TrustManager[] {tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = base.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
//设置要使用的端口,默认是443
sr.register(new Scheme("https", ssf, 443));
return new DefaultHttpClient(ccm, base.getParams());
}
catch (Exception ex)
{
ex.printStackTrace();
return null;
}
}
}
package com.yxcheng.token.utils;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
public class IdWorker {
// 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
private final static long twepoch = 1239876547531569L;
// 机器标识位数
private final static long workerIdBits = 5L;
// 数据中心标识位数
private final static long datacenterIdBits = 5L;
// 机器ID最大值
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 数据中心ID最大值
private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒内自增位
private final static long sequenceBits = 12L;
// 机器ID偏左移12位
private final static long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private final static long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
/* 上次生产id时间戳 */
private static long lastTimestamp = -1L;
// 0,并发控制
private long sequence = 0L;
private final long workerId;
// 数据标识id部分
private final long datacenterId;
public IdWorker(){
this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
}
/**
* @param workerId
* 工作机器ID
* @param datacenterId
* 序列号
*/
// public IdWorker(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;
// }
/**
* 获取下一个ID
*
* @return
*/
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
// 当前毫秒内,则+1
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// 当前毫秒内计数满了,则等待下一秒
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
// ID偏移组合生成最终的ID,并返回ID
long nextId = ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
return nextId;
}
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
/**
* <p>
* 获取 maxWorkerId
* </p>
*/
protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
StringBuffer mpid = new StringBuffer();
mpid.append(datacenterId);
String name = ManagementFactory.getRuntimeMXBean().getName();
if (!name.isEmpty()) {
/*
* GET jvmPid
*/
mpid.append(name.split("@")[0]);
}
/*
* MAC + PID 的 hashcode 获取16个低位
*/
return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
}
/**
* <p>
* 数据标识id部分
* </p>
*/
protected static long getDatacenterId(long maxDatacenterId) {
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
id = ((0x000000FF & (long) mac[mac.length - 1])
| (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
} catch (Exception e) {
System.out.println(" getDatacenterId: " + e.getMessage());
}
return id;
}
public static void main(String[] args) {
try {
IdWorker ik = new IdWorker();
System.out.println("========start========");
for(int i=0;i<200;i++){
System.out.println(ik.nextId());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.yxcheng.token.utils;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;
public class IpUtil {
/**
* 获取用户IP
* @param request
* @return
*/
public static String getRequestRealIp(HttpServletRequest request) {
String strIP = request.getHeader("X-Real-IP");
String strTemp = request.getHeader("x-forwarded-for");
if (StringUtil.isEmpty(strIP) && StringUtil.isNotEmpty(strTemp)) {
String[] strArray = strTemp.split(",");
strIP = strTemp.split(",")[strArray.length - 1];
}
if (strIP == null || strIP.length() == 0
|| "unknown".equalsIgnoreCase(strIP)) {
strIP = request.getHeader("Proxy-Client-IP");
}
if (strIP == null || strIP.length() == 0
|| "unknown".equalsIgnoreCase(strIP)) {
strIP = request.getHeader("WL-Proxy-Client-IP");
}
if (strIP == null || strIP.length() == 0
|| "unknown".equalsIgnoreCase(strIP)) {
strIP = request.getRemoteAddr();
}
// 如果是本地webservice转发,则使用转发的IP地址
String strRemoteIP = request.getParameter("IP");
if (strRemoteIP != null && strRemoteIP.length() > 0) {
if ("127.0.0.1".equalsIgnoreCase(strIP)
|| "localhost".equalsIgnoreCase(strIP))
strIP = strRemoteIP;
}
return strIP;
}
/**
* 获取用户路由信息
* @param request
* @return
*/
public static String getRequestRountIp(HttpServletRequest request) {
return request.getHeader("x-forwarded-for");
}
/**
* 获取url
* @param request
* @return
*/
public static String getRequestUrl(HttpServletRequest request) {
StringBuffer url = request.getRequestURL();
String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
return tempContextUrl;
}
public static boolean ping(String ipAddress) {
int timeOut = 5000 ; //超时应该在5钞以上
boolean status = false; // 当返回值是true时,说明host是可用的,false则不可。
try {
status = InetAddress.getByName(ipAddress).isReachable(timeOut);
} catch (IOException e) {
e.printStackTrace();
}
return status;
}
}
package com.yxcheng.token.utils;
import java.security.MessageDigest;
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
public static String MD5Encode(String origin) {
String charsetname = "UTF-8";
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
public static void main(String[] args) {
System.out.println(MD5Util.MD5Encode("91310118MA1JPDDL2G" + "2" + "81" + "2021-12-01" + "2021-12-31"));
}
}
package com.yxcheng.token.utils;
import java.lang.reflect.Field;
import java.util.*;
public class MapUtil {
/**
* 对象转map
* @param obj 对象
* @return map
* @throws IllegalAccessException 异常
*/
public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
if(obj == null){
return null;
}
//获取所有字段,包含父类。
List<Field> fieldList = new ArrayList<>() ;
Class<?> tempClass = obj.getClass();
while (tempClass !=null && !tempClass.getName().toLowerCase().equals("java.lang.object")) {//当父类为null的时候说明到达了最上层的父类(Object类).
fieldList.addAll(Arrays.asList(tempClass .getDeclaredFields()));
tempClass = tempClass.getSuperclass(); //得到父类,然后赋给自己
}
//反射,处理每个字段。
Map<String, Object> map = new HashMap<>();
for (Field field : fieldList) {
field.setAccessible(true);
String fieldName = field.getName();
Object value = field.get(obj);
map.put(fieldName, value);
}
return map;
}
}
package com.yxcheng.token.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5 {
/**
* 获得随机数字
* @param num 位数
* @return
*/
public static String getRandom(int num){
Double key = Math.random()*100000;
String result = new Integer(key.intValue()).toString();
if(result.length()>num){
result = result.substring(result.length()-num);
}else{
for(int i=num-result.length();i>0;i--){
result = "0" + result;
}
}
return result;
}
/**
* 获取Md5码
* @param key
* @return String
* @throws NoSuchAlgorithmException
*/
public static String getEncode(String key) throws NoSuchAlgorithmException{
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
try {
messageDigest.update(key.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
messageDigest.update(key.getBytes());
}
byte digest[] = messageDigest.digest();
int j = digest.length;
char str[] = new char[j * 2];
int k = 0;
for(int i = 0; i < j; i++)
{
byte byte0 = digest[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
public static String getEncode(byte[] key) throws NoSuchAlgorithmException{
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(key);
byte digest[] = messageDigest.digest();
int j = digest.length;
char str[] = new char[j * 2];
int k = 0;
for(int i = 0; i < j; i++)
{
byte byte0 = digest[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
static final char hexDigits[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'
};
}
\ No newline at end of file
package com.yxcheng.token.utils;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class ObjectUtil {
public static boolean isBigger(Object s,int v){
return Integer.valueOf(s.toString()) > v;
}
public static boolean isNotBigger(Object s,int v){
return Integer.valueOf(s.toString()) <= v;
}
public static String fixNull(Object obj){
String result = "";
if(obj!=null){
result = obj.toString();
}
return result;
}
public static boolean checkData(Object...objs){
boolean flag = true;
if(objs!=null && objs.length>0){
for(Object o : objs){
if(StringUtils.isBlank(fixNull(o))){
flag = false;
break;
}
}
}
return flag;
}
/**
* 未来版本会删除
*/
@Deprecated
public static Map<String,String> getParameterMap(HttpServletRequest request) {
// 参数Map
Map properties = request.getParameterMap();
// 返回值Map
Map<String,String> returnMap = new HashMap<String,String>();
Iterator entries = properties.entrySet().iterator();
Map.Entry entry;
String name = "";
String value = "";
while (entries.hasNext()) {
entry = (Map.Entry) entries.next();
name = (String) entry.getKey();
Object valueObj = entry.getValue();
if(null == valueObj){
value = "";
}else if(valueObj instanceof String[]){
String[] values = (String[])valueObj;
for(int i=0;i<values.length;i++){
value = values[i] + ",";
}
value = value.substring(0, value.length()-1);
}else{
value = valueObj.toString();
}
returnMap.put(name, value);
}
return returnMap;
}
public static boolean dataBaseListIsExist(List list){
return list!=null && list.size()==1;
}
}
package com.yxcheng.token.utils;
import java.io.UnsupportedEncodingException;
public class ResponseContent {
private String encoding;
private byte[] contentBytes;
private int statusCode;
private String contentType;
private String contentTypeString;
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getContentType() {
return this.contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentTypeString() {
return this.contentTypeString;
}
public void setContentTypeString(String contenttypeString) {
this.contentTypeString = contenttypeString;
}
public String getContent() throws UnsupportedEncodingException {
return this.getContent(this.encoding);
}
public String getContent(String encoding)
throws UnsupportedEncodingException {
if (encoding == null) {
return new String(contentBytes);
}
return new String(contentBytes, encoding);
}
public String getUTFContent() throws UnsupportedEncodingException {
return this.getContent("UTF-8");
}
public byte[] getContentBytes() {
return contentBytes;
}
public void setContentBytes(byte[] contentBytes) {
this.contentBytes = contentBytes;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
}
package com.yxcheng.token.utils;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
//用于进行Https请求的HttpClient
public class SSLClient extends DefaultHttpClient{
public SSLClient() throws Exception{
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
package com.yxcheng.token.utils;
import javax.crypto.Cipher;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
public class Security {
public static String charsetName = "UTF-8";
public final static String toHex(byte[] md) {
// 把密文转换成十六进制的字符串形式
int j = md.length;
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
private static int hexToNum(char c) {
int num = 0;
char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F' };
for (int j = 0; j < hexDigits.length; j++) {
if (c == hexDigits[j])
num = j;
}
return num;
}
public static byte[] toDecimal(String msg) {
byte[] result = new byte[msg.length() / 2];
char[] origional = msg.toCharArray();
for (int i = 0; i < origional.length - 1; i++) {
if (i % 2 == 0) {
result[i / 2] = (byte) (hexToNum((origional[i])) * 16 + hexToNum(origional[i + 1]));
}
}
return result;
}
/**
* MD5加密
*
* @param s
* @return
*/
public final static String MD5(String s) {
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
return toHex(md);
} catch (Exception e) {
return null;
}
}
/**
* Description 根据键值进行加密
*
* @param key
* @return
* @throws UnsupportedEncodingException
* @throws GeneralSecurityException
*/
public static String encrypt(String data, String key)
throws GeneralSecurityException, UnsupportedEncodingException {
byte[] src = data.getBytes(charsetName);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(charsetName));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes(charsetName));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return toHex(cipher.doFinal(src));
}
/**
* Description 根据键值进行解密
*
* @param src
* @param key
* 加密键byte数组
* @return
* @throws UnsupportedEncodingException
* @throws Exception
*/
public static String decrypt(String src, String key)
throws GeneralSecurityException, UnsupportedEncodingException {
// 生成一个可信任的随机数源
byte[] data = toDecimal(src);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(charsetName));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes(charsetName));
cipher.init(Cipher.DECRYPT_MODE, securekey, iv);
return new String(cipher.doFinal(data), charsetName);
}
/**
* 获得随机数字
*
* @param num
* 位数
* @return
*/
public static String getRandom(int num) {
Double key = Math.random() * 100000;
String result = new Integer(key.intValue()).toString();
if (result.length() > num) {
result = result.substring(result.length() - num);
} else {
for (int i = num - result.length(); i > 0; i--) {
result = "0" + result;
}
}
return result;
}
// private static ThreadLocal<SimpleDateFormat> dateFormat = new ThreadLocal<SimpleDateFormat>();
//
// public static String getCurrentString() {
// if (null == dateFormat.get()) {
// dateFormat.set(new SimpleDateFormat("yyyyMMddhhssmmSSS"));
// }
// return dateFormat.get().format(
// new Timestamp(System.currentTimeMillis()));
// }
public static String getSignature(byte[] data, byte[] key)
throws NoSuchAlgorithmException, InvalidKeyException {
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHmac = mac.doFinal(data);
String str = new String(rawHmac);
return Md5.getEncode(rawHmac);
}
public static void main(String[] args) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
String data = "AccessKeyID=userid&SignatureNonce=123456&TimeStamp=2016-02-23T12:46:24Z&Version=1.0";
String secretKey = "password";
System.out.println(Security.getSignature(data.getBytes("utf-8"), secretKey.getBytes("utf-8")));
}
public static final String bytesToHexString(byte[] bArray) {
StringBuffer sb = new StringBuffer(bArray.length);
String sTemp;
for (int i = 0; i < bArray.length; i++) {
sTemp = Integer.toHexString(0xFF & bArray[i]);
if (sTemp.length() < 2)
sb.append(0);
sb.append(sTemp.toUpperCase());
}
return sb.toString();
}
public static String decodeTs(String cert,String token){
String m1 = MD5Util.MD5Encode(MD5Util.MD5Encode(cert+token+cert)).replaceAll("a", "").replaceAll("b", "").replaceAll("c", "").replaceAll("d", "").replaceAll("e", "").replaceAll("f", "");
String m2 = MD5Util.MD5Encode(MD5Util.MD5Encode(MD5Util.MD5Encode(token+cert+m1))).replaceAll("a", "").replaceAll("b", "").replaceAll("c", "").replaceAll("d", "").replaceAll("e", "").replaceAll("f", "");
return m1+m2;
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment