项目源码
This commit is contained in:
120
ksafepack-common/pom.xml
Normal file
120
ksafepack-common/pom.xml
Normal file
@@ -0,0 +1,120 @@
|
||||
<?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">
|
||||
<parent>
|
||||
<groupId>com.kelp</groupId>
|
||||
<artifactId>ksafepack</artifactId>
|
||||
<version>1.0.1</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<artifactId>ksafepack-common</artifactId>
|
||||
|
||||
<description>
|
||||
common通用工具
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- Maven的继承依赖应用 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.github.ulisesbocchio</groupId>
|
||||
<artifactId>jasypt-spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- freemarker -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-freemarker</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- redis -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 自定义验证注解 -->
|
||||
<dependency>
|
||||
<groupId>javax.validation</groupId>
|
||||
<artifactId>validation-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!--常用工具类 -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- ftp文件上传工具类 -->
|
||||
<dependency>
|
||||
<groupId>commons-net</groupId>
|
||||
<artifactId>commons-net</artifactId>
|
||||
<version>3.6</version>
|
||||
</dependency>
|
||||
|
||||
<!-- servlet包 -->
|
||||
<dependency>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- json依赖包 -->
|
||||
<dependency>
|
||||
<groupId>net.sf.json-lib</groupId>
|
||||
<artifactId>json-lib</artifactId>
|
||||
<version>2.4</version>
|
||||
<classifier>jdk15</classifier>
|
||||
</dependency>
|
||||
|
||||
<!-- jwt -->
|
||||
<dependency>
|
||||
<groupId>com.auth0</groupId>
|
||||
<artifactId>java-jwt</artifactId>
|
||||
<version>3.8.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- freemarker -->
|
||||
<dependency>
|
||||
<groupId>org.freemarker</groupId>
|
||||
<artifactId>freemarker</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>commons-io</groupId>
|
||||
<artifactId>commons-io</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 阿里云短信 -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||
<version>4.0.6</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 阿里云短信 -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
|
||||
<version>1.1.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.kelp.common.annotation;
|
||||
|
||||
import java.lang.annotation.Documented;
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Inherited;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
import com.kelp.common.enums.DataSourceType;
|
||||
|
||||
/**
|
||||
* 自定义多数据源切换注解
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
@Inherited
|
||||
public @interface DataSource {
|
||||
/**
|
||||
* 切换数据源名称
|
||||
*/
|
||||
public DataSourceType value() default DataSourceType.MASTER;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.kelp.common.base;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
|
||||
|
||||
public class RichFreeMarkerView extends FreeMarkerView {
|
||||
|
||||
@Override
|
||||
protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request)
|
||||
throws Exception {
|
||||
|
||||
model.put("contextPath", request.getContextPath());
|
||||
model.put("base", request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath());
|
||||
//model.put("base", "//" + request.getRemoteHost() + request.getContextPath());
|
||||
|
||||
super.exposeHelpers(model, request);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.kelp.common.config;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.aliyuncs.DefaultAcsClient;
|
||||
import com.aliyuncs.IAcsClient;
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
|
||||
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
|
||||
import com.aliyuncs.http.MethodType;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
import com.aliyuncs.profile.IClientProfile;
|
||||
|
||||
@Component
|
||||
public class AliSMSBean {
|
||||
|
||||
@Value("${sms.ali.accessKeyId}")
|
||||
private String accessKeyId;
|
||||
|
||||
@Value("${sms.ali.accessKeySecret}")
|
||||
private String accessKeySecret;
|
||||
|
||||
@Value("${sms.ali.signName}")
|
||||
private String signName;
|
||||
|
||||
@Value("${sms.ali.product}")
|
||||
private String product;
|
||||
|
||||
@Value("${sms.ali.domain}")
|
||||
private String domain;
|
||||
|
||||
@Value("${sms.ali.region}")
|
||||
private String region;
|
||||
|
||||
@Value("${sms.ali.connect.timeout}")
|
||||
private String connectTimeout;
|
||||
|
||||
@Value("${sms.ali.read.timeout}")
|
||||
private String readTimeout;
|
||||
|
||||
@Value("${sms.ali.template.code}")
|
||||
private String templateCode;
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(AliSMSBean.class);
|
||||
|
||||
public SendSmsResponse send(String telephone,String rawData) {
|
||||
|
||||
// 设置超时时间-可自行调整
|
||||
System.setProperty("sun.net.client.defaultConnectTimeout", connectTimeout);
|
||||
System.setProperty("sun.net.client.defaultReadTimeout", readTimeout);
|
||||
|
||||
// 初始化ascClient,暂时不支持多region(请勿修改)
|
||||
IClientProfile profile = DefaultProfile.getProfile(region, accessKeyId, accessKeySecret);
|
||||
try {
|
||||
DefaultProfile.addEndpoint(region, region, product, domain);
|
||||
IAcsClient acsClient = new DefaultAcsClient(profile);
|
||||
// 组装请求对象
|
||||
SendSmsRequest request = new SendSmsRequest();
|
||||
// 使用post提交
|
||||
request.setMethod(MethodType.POST);
|
||||
// 必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000”
|
||||
request.setPhoneNumbers(telephone);
|
||||
|
||||
// 必填:短信签名-可在短信控制台中找到
|
||||
request.setSignName(new String(signName.getBytes("ISO-8859-1"),"utf-8"));
|
||||
|
||||
// 必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
|
||||
request.setTemplateCode(templateCode);
|
||||
// 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
|
||||
// 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
|
||||
request.setTemplateParam("{\"rawData\":\"" + rawData + "\"}");
|
||||
|
||||
// 可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
|
||||
// request.setSmsUpExtendCode("90997");
|
||||
// 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
|
||||
// request.setOutId("yourOutId");
|
||||
// 请求失败这里会抛ClientException异常
|
||||
SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
|
||||
|
||||
if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
|
||||
return sendSmsResponse;
|
||||
}
|
||||
log.error("短信发送失败,错误码为:" + sendSmsResponse.getCode());
|
||||
return null;
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package com.kelp.common.config;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import org.apache.commons.net.ftp.FTP;
|
||||
import org.apache.commons.net.ftp.FTPClient;
|
||||
import org.apache.commons.net.ftp.FTPReply;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class FtpBean {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(FtpBean.class);
|
||||
|
||||
/**
|
||||
* ftp服务器地址
|
||||
*/
|
||||
@Value("${ftp.server}")
|
||||
private String hostname;
|
||||
|
||||
/**
|
||||
* ftp服务器端口
|
||||
*/
|
||||
@Value("${ftp.port}")
|
||||
private int port;
|
||||
|
||||
/**
|
||||
* ftp登录账号
|
||||
*/
|
||||
@Value("${ftp.userName}")
|
||||
private String username;
|
||||
|
||||
/**
|
||||
* ftp登录密码
|
||||
*/
|
||||
@Value("${ftp.userPassword}")
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* ftp保存目录
|
||||
*/
|
||||
@Value("${ftp.basePath}")
|
||||
private String basePath;
|
||||
|
||||
/**
|
||||
* 图片的http地址
|
||||
*/
|
||||
@Value("${ftp.baseUrl}")
|
||||
private String baseUrl;
|
||||
|
||||
/**
|
||||
* 初始化ftp服务器
|
||||
*/
|
||||
private FTPClient getFtpClient() {
|
||||
FTPClient ftpClient = new FTPClient();
|
||||
ftpClient.setControlEncoding("utf-8");
|
||||
|
||||
try {
|
||||
log.info("connecting to ftp server: " + hostname + ":" + port);
|
||||
// 连接ftp服务器
|
||||
ftpClient.connect(hostname, port);
|
||||
// 登录ftp服务器
|
||||
ftpClient.login(username, password);
|
||||
// 是否成功登录服务器
|
||||
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
|
||||
log.error("connect to ftp server: " + hostname + ":" + port + " failed.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 开启服务器对UTF-8的支持
|
||||
FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"));
|
||||
|
||||
log.info("connect to ftp server: " + hostname + ":" + port + " successful.");
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
return ftpClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* 上传文件
|
||||
*
|
||||
* @param targetDir ftp服务保存地址
|
||||
* @param fileName 上传到ftp的文件名
|
||||
* @param inputStream 输入文件流
|
||||
* @return 上传路径
|
||||
*/
|
||||
public String uploadFileToFtp(String targetDir, String fileName, InputStream inputStream) {
|
||||
FTPClient ftpClient = getFtpClient();
|
||||
try {
|
||||
|
||||
if(ftpClient == null || !ftpClient.isConnected()) {
|
||||
log.error("connected to FTP server failed.");
|
||||
return null;
|
||||
}
|
||||
|
||||
String serverPath = String.format("%s%s%s", basePath, "/", targetDir);
|
||||
|
||||
log.info("starting transform file : " + fileName + " to ftp server");
|
||||
// 设置上传文件类型为二进制
|
||||
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
|
||||
ftpClient.makeDirectory(serverPath);
|
||||
ftpClient.changeWorkingDirectory(serverPath);
|
||||
// 设置被动模式
|
||||
ftpClient.enterLocalPassiveMode();
|
||||
ftpClient.storeFile(fileName, inputStream);
|
||||
inputStream.close();
|
||||
ftpClient.logout();
|
||||
log.info(fileName + " transform to FTP server successful.");
|
||||
|
||||
return baseUrl + targetDir + "/" + fileName;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error(fileName + " transform to FTP server failed.");
|
||||
log.error(e.getMessage(), e);
|
||||
|
||||
return null;
|
||||
} finally {
|
||||
try {
|
||||
ftpClient.disconnect();
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
inputStream.close();
|
||||
} catch (IOException e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.kelp.common.config;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.kelp.common.utils.DateUtils;
|
||||
|
||||
/**
|
||||
* 操作 hash 的基本操作
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
@Component
|
||||
public class RedisBean {
|
||||
|
||||
public static final Logger log = LoggerFactory.getLogger(RedisBean.class);
|
||||
|
||||
@Autowired
|
||||
private RedisTemplate<String, String> redisTemplate;
|
||||
|
||||
/**
|
||||
* 存放从现在起几分钟内有效的东西,如验证码
|
||||
*
|
||||
* @param key
|
||||
* @param field
|
||||
* @param value
|
||||
* @param minute
|
||||
*/
|
||||
public void hset(String key, String field, String value, int minute) {
|
||||
if (key == null || "".equals(key)) {
|
||||
return;
|
||||
}
|
||||
redisTemplate.opsForHash().put(key, field, value);
|
||||
redisTemplate.expireAt(key, DateUtils.addMinute(new Date(), minute));
|
||||
}
|
||||
|
||||
/**
|
||||
* 向Hash中添加值
|
||||
*
|
||||
* @param key 可以对应数据库中的表名
|
||||
* @param field 可以对应数据库表中的唯一索引
|
||||
* @param value 存入redis中的值
|
||||
*/
|
||||
public void hset(String key, String field, String value) {
|
||||
if (key == null || "".equals(key)) {
|
||||
return;
|
||||
}
|
||||
redisTemplate.opsForHash().put(key, field, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从redis中取出值
|
||||
*
|
||||
* @param key
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
public String hget(String key, String field) {
|
||||
if (key == null || "".equals(key)) {
|
||||
return null;
|
||||
}
|
||||
Object o = redisTemplate.opsForHash().get(key, field);
|
||||
if (null != o) {
|
||||
return (String) redisTemplate.opsForHash().get(key, field);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 是否存在 key 以及 hash key
|
||||
*
|
||||
* @param key
|
||||
* @param field
|
||||
* @return
|
||||
*/
|
||||
public boolean hexists(String key, String field) {
|
||||
if (key == null || "".equals(key)) {
|
||||
return false;
|
||||
}
|
||||
return redisTemplate.opsForHash().hasKey(key, field);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询 key中对应多少条数据
|
||||
*
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public long hsize(String key) {
|
||||
if (key == null || "".equals(key)) {
|
||||
return 0L;
|
||||
}
|
||||
return redisTemplate.opsForHash().size(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除
|
||||
*
|
||||
* @param key
|
||||
* @param field
|
||||
*/
|
||||
public void hdel(String key, String field) {
|
||||
if (key == null || "".equals(key)) {
|
||||
return;
|
||||
}
|
||||
redisTemplate.opsForHash().delete(key, field);
|
||||
}
|
||||
|
||||
public boolean lock(String key, String value) {
|
||||
if (redisTemplate.opsForValue().setIfAbsent(key, value)) {
|
||||
return true;
|
||||
}
|
||||
String currentValue = redisTemplate.opsForValue().get(key);
|
||||
// 如果锁过期
|
||||
if (!StringUtils.isEmpty(currentValue) && Long.parseLong(currentValue) < System.currentTimeMillis()) {
|
||||
String oldValue = redisTemplate.opsForValue().getAndSet(key, value);
|
||||
// 是否已被别人抢占
|
||||
return StringUtils.isNotEmpty(oldValue) && oldValue.equals(currentValue);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void unlock(String key, String value) {
|
||||
try {
|
||||
String currentValue = redisTemplate.opsForValue().get(key);
|
||||
if (!StringUtils.isEmpty(currentValue) && currentValue.equals(value)) {
|
||||
redisTemplate.opsForValue().getOperations().delete(key);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("redis unlock error : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package com.kelp.common.config;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.kelp.common.utils.DateUtils;
|
||||
import com.kelp.common.utils.security.Md5Utils;
|
||||
|
||||
/**
|
||||
* 外部接口调用 签名工具类
|
||||
*/
|
||||
@Component
|
||||
public class SignBean {
|
||||
private static Logger log = LoggerFactory.getLogger(SignBean.class);
|
||||
|
||||
@Value("${api.appid}")
|
||||
private String appid;
|
||||
|
||||
@Value("${api.secret}")
|
||||
private String secret;
|
||||
|
||||
/**
|
||||
* API签名生成
|
||||
* @param params,params中必须含有timestamp
|
||||
* @return
|
||||
*/
|
||||
public String sign(Map<String, String> params) {
|
||||
|
||||
// 1、将所有业务请求参数按字母先后顺序排序.
|
||||
// 2、参数名称和参数值链接成一个字符串A
|
||||
StringBuilder stringA = new StringBuilder();
|
||||
Set<String> keySet = new TreeSet<>(params.keySet());
|
||||
|
||||
for (String key : keySet) {
|
||||
String value = params.get(key);
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
stringA.append(key);
|
||||
stringA.append("=");
|
||||
stringA.append(params.get(key));
|
||||
stringA.append("&");
|
||||
}
|
||||
// trim the last "&"
|
||||
stringA.setLength(stringA.length() - 1);
|
||||
|
||||
String sign = null;
|
||||
// 3、在字符串A的首尾加上apiid secret组成一个新字符串B
|
||||
StringBuilder stringB = new StringBuilder();
|
||||
stringB.append(appid).append(stringA).append(secret);
|
||||
|
||||
try {
|
||||
|
||||
// 4、对字符串进行MD5散列运算得到签名sign,然后再进行Base64编码
|
||||
byte[] bytes = Base64.getEncoder().encode(Md5Utils.hash(stringB.toString()).getBytes("UTF-8"));
|
||||
|
||||
sign = new String(bytes, "UTF-8");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("sign failed : ", e);
|
||||
}
|
||||
|
||||
return sign;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查API签名是否合法
|
||||
* (1)客户端请求里面会携带签名(客户端利用apiSecret和给定的算法产生签名)
|
||||
* (2)服务器端会使用存在服务器端的apiSecret和相同的算法产生一个签名。
|
||||
* (3)服务器端对这两个签名进行校验,得出签名的有效性。如果有效,则正常走业务流程,否则拒绝请求。
|
||||
* @param params,params中必须含有sign/timestamp
|
||||
* @return
|
||||
*/
|
||||
public boolean checkSign(Map<String, String> params) {
|
||||
|
||||
String sign = null;
|
||||
String timestamp = null;
|
||||
|
||||
StringBuilder stringA = new StringBuilder();
|
||||
Set<String> keySet = new TreeSet<>(params.keySet());
|
||||
|
||||
for (String key : keySet) {
|
||||
|
||||
String value = params.get(key);
|
||||
if (value == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if(key.equals("sign")) {
|
||||
sign = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if(key.equals("timestamp")) {
|
||||
timestamp = value;
|
||||
//5分钟内签名有效
|
||||
Long time = (System.currentTimeMillis() - Long.valueOf(timestamp))/6000;
|
||||
if(time < -5 || time > 5 ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
stringA.append(key);
|
||||
stringA.append("=");
|
||||
stringA.append(value);
|
||||
stringA.append("&");
|
||||
}
|
||||
// trim the last "&"
|
||||
stringA.setLength(stringA.length() - 1);
|
||||
|
||||
// Base64解码客户端的签名
|
||||
try {
|
||||
sign = new String(Base64.getDecoder().decode(sign), "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
log.error("validate sign failed : " + e);
|
||||
}
|
||||
|
||||
String sign_ = null;
|
||||
StringBuilder stringB = new StringBuilder();
|
||||
stringB.append(appid).append(stringA).append(secret);
|
||||
|
||||
// 对新字符串B进行MD5散列运算生成服务器端的API签名,将客户端的API签名进行Base64解码,然后开始验证签名。
|
||||
// 如果服务器端生成的API签名与客户端请求的API签名是一致的,则请求是可信的,否则就是不可信的。
|
||||
sign_ = Md5Utils.hash(stringB.toString());
|
||||
|
||||
return sign != null && sign_ != null && sign.equals(sign_);
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
Map<String, String> params = new HashMap<String, String>();
|
||||
params.put("startTime", DateUtils.date2string(new Date()));
|
||||
params.put("endTime", DateUtils.date2string(DateUtils.addMinute(new Date(), -5)));
|
||||
params.put("timestamp", String.valueOf(System.currentTimeMillis()));
|
||||
|
||||
SignBean signBean = new SignBean();
|
||||
String sign = signBean.sign(params);
|
||||
System.out.println("sign === " + sign);
|
||||
|
||||
params.put("sign", sign);
|
||||
|
||||
System.out.println("validate === " + signBean.checkSign(params));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.kelp.common.config.datasource;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* 数据源切换处理
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class DynamicDataSourceContextHolder {
|
||||
public static final Logger log = LoggerFactory.getLogger(DynamicDataSourceContextHolder.class);
|
||||
|
||||
/**
|
||||
* 使用ThreadLocal维护变量,ThreadLocal为每个使用该变量的线程提供独立的变量副本,
|
||||
* 所以每一个线程都可以独立地改变自己的副本,而不会影响其它线程所对应的副本。
|
||||
*/
|
||||
private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
|
||||
|
||||
/**
|
||||
* 设置数据源的变量
|
||||
*/
|
||||
public static void setDataSourceType(String dsType) {
|
||||
log.info("切换到{}数据源", dsType);
|
||||
CONTEXT_HOLDER.set(dsType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得数据源的变量
|
||||
*/
|
||||
public static String getDataSourceType() {
|
||||
return CONTEXT_HOLDER.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空数据源变量
|
||||
*/
|
||||
public static void clearDataSourceType() {
|
||||
CONTEXT_HOLDER.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.kelp.common.constant;
|
||||
|
||||
/**
|
||||
* 常量信息
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class CommonConstants {
|
||||
|
||||
/**
|
||||
* 用户名长度限制
|
||||
*/
|
||||
public static final int USERNAME_MIN_LENGTH = 6;
|
||||
public static final int USERNAME_MAX_LENGTH = 20;
|
||||
|
||||
/**
|
||||
* 密码长度限制
|
||||
*/
|
||||
public static final int PASSWORD_MIN_LENGTH = 6;
|
||||
public static final int PASSWORD_MAX_LENGTH = 20;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.kelp.common.constant;
|
||||
|
||||
/**
|
||||
* 代码生成通用常量
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class GeneratorConstants {
|
||||
/** 单表(增删改查) */
|
||||
public static final String TPL_CRUD = "crud";
|
||||
|
||||
/** 树表(增删改查) */
|
||||
public static final String TPL_TREE = "tree";
|
||||
|
||||
/** 树编码字段 */
|
||||
public static final String TREE_CODE = "treeCode";
|
||||
|
||||
/** 树父编码字段 */
|
||||
public static final String TREE_PARENT_CODE = "treeParentCode";
|
||||
|
||||
/** 树名称字段 */
|
||||
public static final String TREE_NAME = "treeName";
|
||||
|
||||
/** 数据库字符串类型 */
|
||||
public static final String[] COLUMNTYPE_STR = { "char", "varchar", "narchar", "varchar2", "tinytext", "text",
|
||||
"mediumtext", "longtext" };
|
||||
|
||||
/** 数据库时间类型 */
|
||||
public static final String[] COLUMNTYPE_TIME = { "datetime", "time", "date", "timestamp" };
|
||||
|
||||
/** 数据库数字类型 */
|
||||
public static final String[] COLUMNTYPE_NUMBER = { "tinyint", "smallint", "mediumint", "int", "number", "integer",
|
||||
"bigint", "float", "float", "double", "decimal" };
|
||||
|
||||
/** 页面不需要编辑字段 */
|
||||
public static final String[] COLUMNNAME_NOT_EDIT = { "id", "create_by", "create_time", "del_flag" };
|
||||
|
||||
/** 页面不需要显示的列表字段 */
|
||||
public static final String[] COLUMNNAME_NOT_LIST = { "id", "create_by", "create_time", "del_flag", "update_by",
|
||||
"update_time" };
|
||||
|
||||
/** 页面不需要查询字段 */
|
||||
public static final String[] COLUMNNAME_NOT_QUERY = { "id", "create_by", "create_time", "del_flag", "update_by",
|
||||
"update_time", "remark" };
|
||||
|
||||
/** Entity基类字段 */
|
||||
public static final String[] BASE_ENTITY = { "createBy", "createTime", "updateBy", "updateTime", "remark" };
|
||||
|
||||
/** Tree基类字段 */
|
||||
public static final String[] TREE_ENTITY = { "parentName", "parentId", "orderNum", "ancestors" };
|
||||
|
||||
/** 文本框 */
|
||||
public static final String HTML_INPUT = "input";
|
||||
|
||||
/** 文本域 */
|
||||
public static final String HTML_TEXTAREA = "textarea";
|
||||
|
||||
/** 下拉框 */
|
||||
public static final String HTML_SELECT = "select";
|
||||
|
||||
/** 单选框 */
|
||||
public static final String HTML_RADIO = "radio";
|
||||
|
||||
/** 复选框 */
|
||||
public static final String HTML_CHECKBOX = "checkbox";
|
||||
|
||||
/** 日期控件 */
|
||||
public static final String HTML_DATETIME = "datetime";
|
||||
|
||||
/** 字符串类型 */
|
||||
public static final String TYPE_STRING = "String";
|
||||
|
||||
/** 整型 */
|
||||
public static final String TYPE_INTEGER = "Integer";
|
||||
|
||||
/** 长整型 */
|
||||
public static final String TYPE_LONG = "Long";
|
||||
|
||||
/** 浮点型 */
|
||||
public static final String TYPE_DOUBLE = "Double";
|
||||
|
||||
/** 高精度计算类型 */
|
||||
public static final String TYPE_BIGDECIMAL = "BigDecimal";
|
||||
|
||||
/** 时间类型 */
|
||||
public static final String TYPE_DATE = "Date";
|
||||
|
||||
/** 模糊查询 */
|
||||
public static final String QUERY_LIKE = "LIKE";
|
||||
|
||||
/** 需要 */
|
||||
public static final String REQUIRE = "1";
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.kelp.common.constant;
|
||||
|
||||
public class KeyConstant {
|
||||
|
||||
public static final String KEY = "无意苦争春";
|
||||
public static final String NAME = "千里杀一人";
|
||||
public static final String REALNAME = "人闲桂花落";
|
||||
public static final String TELEPHONE = "二月春风似剪刀";
|
||||
public static final String SELFID = "何似在人间";
|
||||
|
||||
public static final String JWTKEY = "一任群芳妒";
|
||||
|
||||
public static final String ZERO_KEY = "aPU4Be0sgGQ5Wmh2wwGxoQ==";
|
||||
public static final String ONE_KEY = "SfRmdiUdQkPpmCfyRcqYUw==";
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.kelp.common.constant;
|
||||
|
||||
/**
|
||||
* 正则常量
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class RegexConstants {
|
||||
|
||||
/**
|
||||
* 身份证号格式限制
|
||||
*/
|
||||
public static final String ID_PATTERN = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
|
||||
|
||||
/**
|
||||
* 手机号码格式限制
|
||||
*/
|
||||
public static final String MOBILE_PHONE_NUMBER_PATTERN = "^[1][3,4,5,6,7,8,9][0-9]{9}$";
|
||||
|
||||
/**
|
||||
* 邮箱格式限制
|
||||
*/
|
||||
public static final String EMAIL_PATTERN = "^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.?";
|
||||
|
||||
/**
|
||||
* 必须包含数字和字母,如密码
|
||||
*/
|
||||
public static final String LETTER_DIGIT_PATTERN = "^[a-z0-9A-Z]+$";
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.kelp.common.enums;
|
||||
|
||||
/**
|
||||
* 数据源
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public enum DataSourceType {
|
||||
/**
|
||||
* 主库
|
||||
*/
|
||||
MASTER,
|
||||
|
||||
/**
|
||||
* 从库
|
||||
*/
|
||||
SLAVE
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.kelp.common.exception;
|
||||
|
||||
public class BaseException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* 错误码
|
||||
*/
|
||||
private String code;
|
||||
|
||||
/**
|
||||
* 错误消息
|
||||
*/
|
||||
private String msg;
|
||||
|
||||
public BaseException(String code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMessage() {
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package com.kelp.common.message;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.serializer.SerializerFeature;
|
||||
|
||||
/**
|
||||
* 封装消费者调用接口返回信息<br/>
|
||||
* 如果不够用自己添加 Created by ADon on 2016/7/22.
|
||||
*/
|
||||
public class Message<T> implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 403590390097622048L;
|
||||
|
||||
// 是否成功
|
||||
private boolean success;
|
||||
|
||||
// 消息 返回MessageCode中的说明
|
||||
private String msg;
|
||||
|
||||
// 消息状态码 返回MessageCode中的状态码
|
||||
private String code;
|
||||
|
||||
// 数据
|
||||
private T data;
|
||||
|
||||
public Message<T> setResultData(T data) {
|
||||
this.data = data;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Message<T> SetMessageCode(MessageCode messageCode) {
|
||||
this.msg = messageCode.getMsg();
|
||||
this.code = messageCode.getCode();
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生产成功信息
|
||||
*
|
||||
* @return Message
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static Message fireSuccess() {
|
||||
Message<?> message = new Message();
|
||||
message.setSuccess(true);
|
||||
message.setCode(MessageCode.SUCCESS.getCode());
|
||||
message.setMsg(MessageCode.SUCCESS.getMsg());
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生产失败信息
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static Message fireFail() {
|
||||
Message<?> message = new Message();
|
||||
message.setSuccess(false);
|
||||
message.setCode(MessageCode.FAIL.getCode());
|
||||
message.setMsg(MessageCode.FAIL.getMsg());
|
||||
message.setData(null);
|
||||
return message;
|
||||
}
|
||||
/**
|
||||
* 生产404信息
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public static Message fireFail404() {
|
||||
Message<?> message = new Message();
|
||||
message.setSuccess(false);
|
||||
message.setCode(MessageCode.FAIL404.getCode());
|
||||
message.setMsg(MessageCode.FAIL404.getMsg());
|
||||
message.setData(null);
|
||||
return message;
|
||||
}
|
||||
public boolean getSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return msg;
|
||||
}
|
||||
|
||||
public void setMsg(String msg) {
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public T getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(T data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public static String jsonSuccess() {
|
||||
return JSON.toJSONString(fireSuccess());
|
||||
}
|
||||
|
||||
public static String jsonFail() {
|
||||
return JSON.toJSONString(fireFail());
|
||||
}
|
||||
|
||||
public static String json(Message<?> mess) {
|
||||
return JSON.toJSONStringWithDateFormat(mess, "yyyy-MM-dd hh:mm:ss", SerializerFeature.WriteMapNullValue,
|
||||
SerializerFeature.WriteNonStringValueAsString);
|
||||
}
|
||||
|
||||
public static String jsonData(Message<?> mess) {
|
||||
return JSON.toJSONStringWithDateFormat(mess.getData(), "yyyy-MM-dd hh:mm:ss",
|
||||
SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNonStringValueAsString);
|
||||
}
|
||||
|
||||
public static String jsonObj(Object obj) {
|
||||
return JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd hh:mm:ss", SerializerFeature.WriteMapNullValue,
|
||||
SerializerFeature.WriteNonStringValueAsString);
|
||||
}
|
||||
|
||||
public static String jsonObjDate(Object obj) {
|
||||
return JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd", SerializerFeature.WriteMapNullValue,
|
||||
SerializerFeature.WriteNonStringValueAsString);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static String jsonMessage(Object obj) {
|
||||
Message<Object> mess = fireSuccess();
|
||||
mess.setData(obj);
|
||||
return json(mess);
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "unchecked", "rawtypes" })
|
||||
public static Message fail(Message mess, String code, String msg) {
|
||||
mess.setSuccess(false);
|
||||
mess.setCode(code);
|
||||
mess.setMsg(msg);
|
||||
mess.setData(null);
|
||||
return mess;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.kelp.common.message;
|
||||
|
||||
/**
|
||||
* 封装消费者调用接口返回信息状态码<br/>
|
||||
* 不够用请自己添加,注意命名规范
|
||||
* Created by ADon on 2016/7/22.
|
||||
*/
|
||||
public enum MessageCode {
|
||||
//成功状态码
|
||||
SUCCESS("0", "成功"),
|
||||
FAIL("002", "失败"),
|
||||
FAIL404("404", "没有权限"),
|
||||
ENTITY_ID_IS_EMPTY("002001", "传入的ID为空"),
|
||||
UserLoginInfo_VeCode_NOT_EXIST("010","用户不存在或密码错误"),
|
||||
UserLoginInfo_Password_NOT_EQUAL("011","用户不存在或密码错误"),
|
||||
UserLoginInfo_VeCode_IS_Login("012","登录成功"),
|
||||
UserLoginInfo_VeCode_NOT_Login("013","登录失败"),
|
||||
UserData_VeCode_NOT_EXIST("010","用户数据不存在"),
|
||||
UserData_VeCode_NOT_ERROR("011","发生错误"),
|
||||
UserData_Level_NOT_AUTH("010","尚未进行实名认证"),
|
||||
UserData_Pwd_NOT_LEGAL("010","密码只能为6位数字"),
|
||||
UserAccount_VeCode_NOT_ERROR("010","发生错误"),
|
||||
Manager_Delete_Error1("020","对不起,剩余管理员不能少于1位"),
|
||||
Manager_Delete_Error2("021","对不起,不能删除自己"),
|
||||
Group_Delete_Error("021","对不起,不能删除自己的角色"),
|
||||
|
||||
Dxx_Verification_Code_Error("101","验证码不正确"),
|
||||
Dxx_Verification_Code_Null("102","获取验证码失败,请重新获取。"),
|
||||
Dxx_Invitation_Code_Error("103","邀请码不正确"),
|
||||
Dxx_Invitation_Code_Null("104","获取邀请码失败,请重新获取。"),
|
||||
Dxx_Mycard_isNUll("105","未开卡"),
|
||||
Dxx_MyClub_isNUll("106","没有俱乐部信息。"),
|
||||
Dxx_MyGym_isNUll("107","没有场馆信息。"),
|
||||
Dxx_MyShop_isNUll("108","没有商城信息。"),
|
||||
Dxx_Entity_Empty("201","实体对象为空");
|
||||
|
||||
/*
|
||||
命名规范说明:
|
||||
实体名_属性_是否_错误信息
|
||||
TASKINFO_ID_IS_EMPTY("010", "任务ID为空")
|
||||
TASKINFO_ID_NOT_EXIST("011", "任务ID不存在")
|
||||
TASKINFO_ID_IS_EXIST("012", "任务ID已存在")
|
||||
*/
|
||||
|
||||
private String code;
|
||||
private String msg;
|
||||
|
||||
MessageCode(String code, String msg) {
|
||||
this.code = code;
|
||||
this.msg = msg;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return this.code;
|
||||
}
|
||||
|
||||
public String getMsg() {
|
||||
return this.msg;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.kelp.common.constant.KeyConstant;
|
||||
|
||||
|
||||
public class AESUtil {
|
||||
private static Logger log = LoggerFactory.getLogger(AESUtil.class);
|
||||
|
||||
private static final String KEY_ALGORITHM = "AES";
|
||||
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";// 默认的加密算法
|
||||
|
||||
/**
|
||||
* AES 加密操作
|
||||
*
|
||||
* @param content 待加密内容
|
||||
* @param password 加密密码
|
||||
* @return 返回Base64转码后的加密数据
|
||||
*/
|
||||
public static String encrypt(String content, String password) {
|
||||
try {
|
||||
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
|
||||
|
||||
byte[] byteContent = content.getBytes("utf-8");
|
||||
|
||||
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));// 初始化为加密模式的密码器
|
||||
|
||||
byte[] result = cipher.doFinal(byteContent);// 加密
|
||||
|
||||
return Base64.getEncoder().encodeToString(result);// 通过Base64转码返回
|
||||
} catch (Exception ex) {
|
||||
log.error("AESUtil: encrypt failed - " + ex.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* AES 解密操作
|
||||
*
|
||||
* @param content
|
||||
* @param password
|
||||
* @return
|
||||
*/
|
||||
public static String decrypt(String content, String password) {
|
||||
|
||||
try {
|
||||
// 实例化
|
||||
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
|
||||
|
||||
// 使用密钥初始化,设置为解密模式
|
||||
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
|
||||
|
||||
// 执行操作
|
||||
byte[] result = cipher.doFinal(Base64.getDecoder().decode(content));
|
||||
|
||||
return new String(result, "utf-8");
|
||||
} catch (Exception ex) {
|
||||
log.error("AESUtil: decrypt failed - " + ex.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成加密秘钥
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
private static SecretKeySpec getSecretKey(final String password) {
|
||||
// 返回生成指定算法密钥生成器的 KeyGenerator 对象
|
||||
KeyGenerator kg = null;
|
||||
|
||||
try {
|
||||
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
|
||||
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
|
||||
random.setSeed(password.getBytes("utf-8"));
|
||||
// AES 要求密钥长度为 128
|
||||
kg.init(128, random);
|
||||
|
||||
// 生成一个密钥
|
||||
SecretKey secretKey = kg.generateKey();
|
||||
|
||||
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);// 转换为AES专用密钥
|
||||
} catch (Exception ex) {
|
||||
log.error("AESUtil: getSecretKey failed - " + ex.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试Main方法
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
String sss = AESUtil.encrypt("17733877260", KeyConstant.TELEPHONE);
|
||||
System.err.println("加密后数据:" + sss);
|
||||
sss = AESUtil.decrypt(sss, KeyConstant.TELEPHONE);
|
||||
System.err.println("解密后数据:" + sss);
|
||||
|
||||
sss = AESUtil.encrypt("张晓", KeyConstant.NAME);
|
||||
System.err.println("加密后数据:" + sss);
|
||||
sss = AESUtil.decrypt(sss, KeyConstant.NAME);
|
||||
System.err.println("解密后数据:" + sss);
|
||||
|
||||
sss = AESUtil.encrypt("张晓", KeyConstant.REALNAME);
|
||||
System.err.println("加密后数据:" + sss);
|
||||
sss = AESUtil.decrypt(sss, KeyConstant.REALNAME);
|
||||
System.err.println("解密后数据:" + sss);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
105
ksafepack-common/src/main/java/com/kelp/common/utils/Arith.java
Normal file
105
ksafepack-common/src/main/java/com/kelp/common/utils/Arith.java
Normal file
@@ -0,0 +1,105 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
/**
|
||||
* 精确的浮点数运算
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class Arith {
|
||||
|
||||
/** 默认除法运算精度 */
|
||||
private static final int DEF_DIV_SCALE = 10;
|
||||
|
||||
/** 这个类不能实例化 */
|
||||
private Arith() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的加法运算。
|
||||
*
|
||||
* @param v1 被加数
|
||||
* @param v2 加数
|
||||
* @return 两个参数的和
|
||||
*/
|
||||
public static double add(double v1, double v2) {
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
return b1.add(b2).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的减法运算。
|
||||
*
|
||||
* @param v1 被减数
|
||||
* @param v2 减数
|
||||
* @return 两个参数的差
|
||||
*/
|
||||
public static double sub(double v1, double v2) {
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
return b1.subtract(b2).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的乘法运算。
|
||||
*
|
||||
* @param v1 被乘数
|
||||
* @param v2 乘数
|
||||
* @return 两个参数的积
|
||||
*/
|
||||
public static double mul(double v1, double v2) {
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
return b1.multiply(b2).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。
|
||||
*
|
||||
* @param v1 被除数
|
||||
* @param v2 除数
|
||||
* @return 两个参数的商
|
||||
*/
|
||||
public static double div(double v1, double v2) {
|
||||
return div(v1, v2, DEF_DIV_SCALE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。
|
||||
*
|
||||
* @param v1 被除数
|
||||
* @param v2 除数
|
||||
* @param scale 表示表示需要精确到小数点以后几位。
|
||||
* @return 两个参数的商
|
||||
*/
|
||||
public static double div(double v1, double v2, int scale) {
|
||||
if (scale < 0) {
|
||||
throw new IllegalArgumentException("The scale must be a positive integer or zero");
|
||||
}
|
||||
BigDecimal b1 = new BigDecimal(Double.toString(v1));
|
||||
BigDecimal b2 = new BigDecimal(Double.toString(v2));
|
||||
if (b1.compareTo(BigDecimal.ZERO) == 0) {
|
||||
return BigDecimal.ZERO.doubleValue();
|
||||
}
|
||||
return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 提供精确的小数位四舍五入处理。
|
||||
*
|
||||
* @param v 需要四舍五入的数字
|
||||
* @param scale 小数点后保留几位
|
||||
* @return 四舍五入后的结果
|
||||
*/
|
||||
public static double round(double v, int scale) {
|
||||
if (scale < 0) {
|
||||
throw new IllegalArgumentException("The scale must be a positive integer or zero");
|
||||
}
|
||||
BigDecimal b = new BigDecimal(Double.toString(v));
|
||||
BigDecimal one = new BigDecimal("1");
|
||||
return b.divide(one, scale, RoundingMode.HALF_UP).doubleValue();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class AuthenticationBean {
|
||||
|
||||
/**
|
||||
* role/<url/role>
|
||||
*/
|
||||
//plat
|
||||
private static HashMap<String,Map<String,String>> prfMap = new HashMap<String, Map<String,String>>();
|
||||
//enterprise
|
||||
private static HashMap<String,Map<String,String>> erfMap = new HashMap<String, Map<String,String>>();
|
||||
|
||||
public static HashMap<String, Map<String, String>> getPRfMap() {
|
||||
return prfMap;
|
||||
}
|
||||
public static void setPRfMap(HashMap<String, Map<String, String>> prfMap) {
|
||||
AuthenticationBean.prfMap = prfMap;
|
||||
}
|
||||
|
||||
public static HashMap<String, Map<String, String>> getERfMap() {
|
||||
return erfMap;
|
||||
}
|
||||
public static void setERfMap(HashMap<String, Map<String, String>> erfMap) {
|
||||
AuthenticationBean.erfMap = erfMap;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
public class Converter4Number {
|
||||
|
||||
public static Integer string2integer(String number) {
|
||||
try {
|
||||
return Integer.valueOf(number);
|
||||
}catch(Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试Main方法
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class CookieUtil {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(CookieUtil.class);
|
||||
|
||||
public static String getCookie(HttpServletRequest request, String name){
|
||||
Cookie[] cookies = request.getCookies();//根据请求数据,找到cookie数组
|
||||
|
||||
try {
|
||||
if (null != cookies) {
|
||||
for (Cookie cookie : cookies) {
|
||||
if (cookie.getName().equals(name)) {
|
||||
return URLDecoder.decode(cookie.getValue(), "UTF-8");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.error(ex.getMessage());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void addCookie(HttpServletResponse response, String name,
|
||||
String value) {
|
||||
try {
|
||||
Cookie cookie = new Cookie(name, URLEncoder.encode(value, "utf-8"));
|
||||
|
||||
cookie.setMaxAge(3600);
|
||||
cookie.setPath("/");
|
||||
|
||||
response.addCookie(cookie);
|
||||
} catch (Exception ex) {
|
||||
log.error(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
public static void editCookie(HttpServletRequest request,
|
||||
HttpServletResponse response, String name, String nvalue) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (null != cookies) {
|
||||
for (Cookie cookie : cookies) {
|
||||
if (cookie.getName().equals(name)) {
|
||||
try {
|
||||
cookie.setValue(URLEncoder.encode(nvalue, "utf-8"));
|
||||
cookie.setPath("/");
|
||||
cookie.setMaxAge(3600);
|
||||
response.addCookie(cookie);
|
||||
} catch (Exception ex) {
|
||||
log.error(ex.getMessage());
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 删除cookie
|
||||
public static void delCookie(HttpServletRequest request,
|
||||
HttpServletResponse response, String name) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (null != cookies) {
|
||||
for (Cookie cookie : cookies) {
|
||||
if (cookie.getName().equals(name)) {
|
||||
cookie.setValue(null);
|
||||
cookie.setMaxAge(0);
|
||||
cookie.setPath("/");
|
||||
response.addCookie(cookie);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
import org.apache.commons.lang3.time.DateFormatUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(DateUtils.class);
|
||||
|
||||
private static final String DATE_FORMAT_DEFAULT = "yyyy-MM-dd HH:mm:ss";
|
||||
private static final String DATE_FORMAT_MINUTE = "yyyy-MM-dd HH:mm";
|
||||
private static final String DATE_FORMAT_DAY_DEFAULT = "yyyy-MM-dd";
|
||||
private static final String DATE_FORMAT_MONTH = "yyyy-MM";
|
||||
private static final String DATE_FORMAT_DAY_YYYYMMDD = "yyyyMMdd";
|
||||
private static final String DATE_FORMAT_DAY_YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
|
||||
|
||||
private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
|
||||
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss",
|
||||
"yyyy.MM.dd HH:mm", "yyyy.MM" };
|
||||
|
||||
public static Date addMonth(Date date, int monty) {
|
||||
if (date == null)
|
||||
return null;
|
||||
GregorianCalendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(date);
|
||||
calendar.add(GregorianCalendar.MONTH, monty);
|
||||
date = calendar.getTime();
|
||||
return date;
|
||||
}
|
||||
|
||||
public static Date addDay(Date date, int day) {
|
||||
if (date == null)
|
||||
return null;
|
||||
GregorianCalendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(date);
|
||||
calendar.add(GregorianCalendar.DATE, day);
|
||||
date = calendar.getTime();
|
||||
return date;
|
||||
}
|
||||
|
||||
public static Date addHour(Date date, int hour) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
GregorianCalendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(date);
|
||||
calendar.add(GregorianCalendar.HOUR, hour);
|
||||
date = calendar.getTime();
|
||||
return date;
|
||||
}
|
||||
|
||||
public static Date addMinute(Date date, int minute) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
GregorianCalendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(date);
|
||||
calendar.add(GregorianCalendar.MINUTE, minute);
|
||||
date = calendar.getTime();
|
||||
return date;
|
||||
}
|
||||
|
||||
public static Date addSecond(Date date, int second) {
|
||||
if (date == null) {
|
||||
return null;
|
||||
}
|
||||
GregorianCalendar calendar = new GregorianCalendar();
|
||||
calendar.setTime(date);
|
||||
calendar.add(GregorianCalendar.SECOND, second);
|
||||
date = calendar.getTime();
|
||||
return date;
|
||||
}
|
||||
|
||||
public static Date string2date(String s) {
|
||||
if (s == null || s.trim().length() == 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DEFAULT);
|
||||
return sdf.parse(s);
|
||||
} catch (ParseException e) {
|
||||
log.error(e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String date2string(Date d, String format_) {
|
||||
SimpleDateFormat format = new SimpleDateFormat(format_);
|
||||
String s = format.format(d);
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String date2string(Date d) {
|
||||
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_DEFAULT);
|
||||
String s = format.format(d);
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String date2Day(Date d) {
|
||||
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_DAY_DEFAULT);
|
||||
String s = format.format(d);
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String date2MothFristDay(Date d) {
|
||||
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_MONTH);
|
||||
String s = format.format(d);
|
||||
return s + "-01";
|
||||
}
|
||||
|
||||
public static Date string2MothDate(String s) {
|
||||
if (s == null || s.trim().length() == 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_MONTH);
|
||||
return sdf.parse(s);
|
||||
} catch (ParseException e) {
|
||||
log.error(e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String date2YYYYMMDD(Date d) {
|
||||
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_DAY_YYYYMMDD);
|
||||
String s = format.format(d);
|
||||
return s;
|
||||
}
|
||||
|
||||
public static String date2YYYYMMDDHHMMSS(Date date) {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DAY_YYYYMMDDHHMMSS);
|
||||
return sdf.format(date);
|
||||
}
|
||||
|
||||
public static Date string2day(String s) {
|
||||
if (s == null || s.trim().length() == 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_DAY_DEFAULT);
|
||||
return sdf.parse(s);
|
||||
} catch (ParseException e) {
|
||||
log.error(e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String day2string(Date d) {
|
||||
SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT_DAY_DEFAULT);
|
||||
String s = format.format(d);
|
||||
return s;
|
||||
}
|
||||
|
||||
public static Date long2date(Long l) {
|
||||
return new Date(l);
|
||||
}
|
||||
|
||||
/**
|
||||
* 两个日期的天数差
|
||||
*
|
||||
* @param date1
|
||||
* @param date2
|
||||
* @return
|
||||
*/
|
||||
public static int dayDValue(Date date1, Date date2) {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date1);
|
||||
long time1 = cal.getTimeInMillis();
|
||||
cal.setTime(date2);
|
||||
long time2 = cal.getTimeInMillis();
|
||||
long between_days = (time2 - time1) / (1000 * 3600 * 24);
|
||||
|
||||
return Integer.parseInt(String.valueOf(between_days));
|
||||
}
|
||||
|
||||
public static long timeDValue(Date date1, Date date2) {
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date1);
|
||||
long time1 = cal.getTimeInMillis();
|
||||
cal.setTime(date2);
|
||||
long time2 = cal.getTimeInMillis();
|
||||
return (time2 - time1) / 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期相减,得到时分秒
|
||||
*
|
||||
* @param d1
|
||||
* @param d2
|
||||
* @return
|
||||
*/
|
||||
public static String dateSub2Time(Date d1, Date d2) {
|
||||
long s = (d1.getTime() - d2.getTime()) / 1000;
|
||||
|
||||
long hour = s % (24 * 3600) / 3600;
|
||||
long minute = s % 3600 / 60;
|
||||
long second = s % 60;
|
||||
|
||||
return String.format("%02d", hour) + ":" + String.format("%02d", minute) + ":" + String.format("%02d", second);
|
||||
}
|
||||
|
||||
public static String dateSubDate(Date d1, Date d2) {
|
||||
long s = (d1.getTime() - d2.getTime()) / 1000;
|
||||
|
||||
long day = s / (3600 * 24);
|
||||
long hour = s % (24 * 3600) / 3600;
|
||||
long minute = s % 3600 / 60;
|
||||
|
||||
return day + "天" + String.format("%02d", hour) + "小时" + String.format("%02d", minute) + "分钟";
|
||||
}
|
||||
|
||||
public static Date getThisMonday() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
|
||||
calendar.add(Calendar.DAY_OF_WEEK, 1);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
|
||||
calendar.add(Calendar.DAY_OF_WEEK, -1);
|
||||
}
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date getNextMonday() {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
|
||||
calendar.add(Calendar.DAY_OF_WEEK, 8);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
|
||||
calendar.add(Calendar.DAY_OF_WEEK, 7);
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
|
||||
calendar.add(Calendar.DAY_OF_WEEK, 1);
|
||||
}
|
||||
return calendar.getTime();
|
||||
}
|
||||
|
||||
public static Date string2date2minute(String s) {
|
||||
if (s == null || s.trim().length() == 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_MINUTE);
|
||||
return sdf.parse(s);
|
||||
} catch (ParseException e) {
|
||||
log.error(e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据Date ,日期格式 : yyyy-MM-dd 返回周几
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static String date2week(Date date) {
|
||||
String[] weeks = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
|
||||
|
||||
Calendar cal = Calendar.getInstance();
|
||||
cal.setTime(date);
|
||||
System.out.println(cal.get(Calendar.DAY_OF_WEEK));
|
||||
int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
|
||||
if (week_index < 0) {
|
||||
week_index = 0;
|
||||
}
|
||||
|
||||
return weeks[week_index];
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期路径 即年/月/日 如2018/08/08
|
||||
*/
|
||||
public static final String datePath() {
|
||||
Date now = new Date();
|
||||
return DateFormatUtils.format(now, "yyyy/MM/dd");
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期型字符串转化为日期 格式
|
||||
*/
|
||||
public static Date parseDate(Object str) {
|
||||
if (str == null) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return parseDate(str.toString(), parsePatterns);
|
||||
} catch (ParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Date sDate = DateUtil.string2MothDate("2019-03-08 00:00:00");
|
||||
// Date eDate = DateUtil.string2MothDate("2019-03-08 00:00:00");
|
||||
// System.out.println(sDate.before(eDate));
|
||||
|
||||
Date date = string2day("2019-09-05");
|
||||
System.out.println(date);
|
||||
|
||||
System.out.println(date2week(date));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.zip.GZIPInputStream;
|
||||
import java.util.zip.GZIPOutputStream;
|
||||
|
||||
import org.apache.tomcat.util.codec.binary.Base64;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* 压缩工具类
|
||||
*/
|
||||
public class GZIPUtils {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(GZIPUtils.class);
|
||||
|
||||
public static final String GZIP_ENCODE_UTF_8 = "UTF-8";
|
||||
|
||||
public static final String GZIP_ENCODE_ISO_8859_1 = "ISO-8859-1";
|
||||
|
||||
/**
|
||||
* 压缩GZip
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String gZip(String input) {
|
||||
byte[] bytes = null;
|
||||
GZIPOutputStream gzip = null;
|
||||
ByteArrayOutputStream bos = null;
|
||||
try {
|
||||
bos = new ByteArrayOutputStream();
|
||||
gzip = new GZIPOutputStream(bos);
|
||||
gzip.write(input.getBytes(GZIP_ENCODE_UTF_8));
|
||||
gzip.finish();
|
||||
gzip.close();
|
||||
bytes = bos.toByteArray();
|
||||
bos.close();
|
||||
} catch (Exception e) {
|
||||
log.error("zip error: ", e);
|
||||
} finally {
|
||||
try {
|
||||
if (gzip != null)
|
||||
gzip.close();
|
||||
if (bos != null)
|
||||
bos.close();
|
||||
} catch (final IOException ioe) {
|
||||
log.error("zip error: ", ioe);
|
||||
}
|
||||
}
|
||||
return Base64.encodeBase64String(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解压GZip
|
||||
*
|
||||
* @return String
|
||||
*/
|
||||
public static String unGZip(String input) {
|
||||
byte[] bytes;
|
||||
String out = input;
|
||||
GZIPInputStream gzip = null;
|
||||
ByteArrayInputStream bis;
|
||||
ByteArrayOutputStream bos = null;
|
||||
try {
|
||||
bis = new ByteArrayInputStream(Base64.decodeBase64(input));
|
||||
gzip = new GZIPInputStream(bis);
|
||||
byte[] buf = new byte[1024];
|
||||
int num;
|
||||
bos = new ByteArrayOutputStream();
|
||||
while ((num = gzip.read(buf, 0, buf.length)) != -1) {
|
||||
bos.write(buf, 0, num);
|
||||
}
|
||||
bytes = bos.toByteArray();
|
||||
out = new String(bytes, GZIP_ENCODE_UTF_8);
|
||||
gzip.close();
|
||||
bis.close();
|
||||
bos.flush();
|
||||
bos.close();
|
||||
} catch (Exception e) {
|
||||
log.error("unzip error: ", e);
|
||||
} finally {
|
||||
try {
|
||||
if (gzip != null)
|
||||
gzip.close();
|
||||
if (bos != null)
|
||||
bos.close();
|
||||
} catch (final IOException ioe) {
|
||||
log.error("unzip error: ", ioe);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) throws UnsupportedEncodingException {
|
||||
// String json="H4sIAAAAAAAAA+1cWXPbOBL+Lfugmt2HuHhTfJTkOEmVc1Ti3ezbFESCEtYQqSKh2MqvH/AAiIYk8zDjkbKOKioTR7MvfN0NkJr484ll/cBZTtKE/zWxZ/zbNK+MK6O4tBb8O19jzPK6t5wweetO5v5k5k7eOpP59SRYTN5OJzNzMpua6rgEbbCk2japvFeEY7Sj8G5hSt9jFOHsa/rwHpPVmlW9llHNyYrmon+R0u8kYuuq21G7lVnmlW1XPSEYbxrGxL+WcxbpLhFTLDl+t0mUDrPuQCEjPzBnT1BSmzlXNZmqla2x1Mqhlj7HMQmx1Ec5mFNIs64zlii8X2WcxwiYAtU8uG4toXa90q6XzbVQSkPZ6kLZNiFl24CU7UbdDD+yLtwagCKkB6l14dCbAnJTB9AzDU9SRGGIk04cBlBoU1enaWtEu6nSh1QtSNUJNKJ2B6KmBy0vr5fNNaTqDPAnM7BOWKmi6fa3k2lqhgp0Q3ldxBdrV1D1bUDVNyXR9X6LM0qS+w5kofRBoHHaWD9OKU0fcPS+B3HTCQB5XyPPFcPJS7Y5JpJkdZMKtOLf1zhZ/ZcgDvXGrYDEikQa7U+MtCTFCDGksllc36ElBWhmnrz4gehOCQfWzefZNWL4n47tBP6/+LXkJmd72oz888/ljlD2IflWNFsqR9YJ+mY7HbOmc5RUR75dyx2Xb8vuz7g9hHHXG5fxAXw7Q/iejsy3OcBT3AGMe+bYHt6BkM64N4RxZ2zGB7iKP4Rxfzoy405/xqcDGPeNYGTG3f6MB0MYt8dm3OvPuGmoxNpUEqfZZkeRpL0wjTcKRRn4qqqEy4k+pREIdypvZUORJSsJe7KjVN4LZPKWdccTVR6J+Q2Nptr6MaNkVddilpipBGbT2z7yCWp8bioFEMLnPKbL7mWa8QrpFsdM56vquUu3xzu+NqWT3jVPGUs3eh9Nw3scVa0sKzQukvIPSYQFf3Xy/sAJfc9Qfe8Y0RxrupfV3bWeffQwymnlwJvJUvMlbpZjinmFmCag2gX+m+klJSxMTck18Bd+DQaJG1LuM7LaVRUsGHDnwoyVZOSnyEvE8Itud4WV1yhjjcwn9iqC+WT+Vm5RVOu0VvBjNdAzp1deXZrthZ1qzHpoNhZcx7vyPJGUKzsRU+/KCpp/ogBlvCT4pHJjyRuXnH/bohA4XFmT42iRZgnOcnUpNZOAgxIGPTb9wWsQtD+YmW+/gH0HmqhXSXpDKFUWuvCokx3sEdIrqg7Ykm/DG5Ll7Bbl7AvKkA4jnFH2mX/FVK6MpgMii0SVegRKwrUAX9C0YNkRXreaf2iq4IDwVWP9Z027cYrlgUbJQcsOcJ2zjNxj0HSPs1rtZhknKsOEYAxFjADbbAkL1zdoQ+geDCx8IccQPgp/ixuXKnxtvkneUDZRYjRGI5OvCErgzUcmXxGUUJtSEjVOWRssLDfXKLAiTxIAebrbfEwj6Quea3AbCCDhnZ/jWHbaotO/1qAeJ1HhzcBjZB/lXCQqHlUUXEAB7Vh6V6zbaz6eifiq+NGWpmyWQTOVK/8dh4etjnZlzx1XXY1kIiJl2jjeQnDeDKwNQaJHcF2mA9CRh0HHAEM5mq5JUmDBh/gTXqFi//UQDxFAw2S3+YpjtUVcWNYfT21a//GPieXw8U41uPzTbBI5TneBOOeAMs83EVs0GYRlbTabN/sj2YGUbwwuFw2Xi0FcvsM8tFQcaUnMGgnfsNQYix4/NKsmMHzDdPwivnlu4NpF8S8GLlF2TSAsF5vMW5KsYCPaKpv1lhkINWX7Mqs+jHtVVKtx/A0vIgF7WF8S6JEojm7qYigylC6JqOSwDqJ8pSQMMXmS0qRYUblmDxhEj1/SHKyaDfpfmt2R8P4jyuodwbpc3pBE7xGJP2+8XVJJyuqyAGHwDIWWRJqx2UaAL0RFSSLzUJ5yKOt3XJQ1n0LZ6QHKviYdcjvol2UcrxnG75phVHJnaZ7PRF0jMLrpEmgpfJhnI/oqoUvKWW2UJzxniXJ8Rzb43wmBeuWh52YDQnFbeCynzThOlzkNMNwMoLc4ZjoC7LYO7FDasYHdVID9XUYiThwDT/w/wmnFXY8EOuuXBLrXIvU1XrzGi18bL2BqfCxelG1zzB4whvjUKQbA4qNzEAB7fhTt0x240QYlO0RvD9ofP8p712T3By2i+r0yXJPHD8/zXcd0XfEMwV52F4HFdV3LswPLtWsNPYjuaTC1HcO2+Zip49ST16LXmwa+NzVdO5gavgtOOUbEPAklNGX/IfnnRHh4g2cRybdzipL7fAbNmq/Th2sOyXmBdh/Rowod3Vj9reLb0JsbGgk9AvVE+fFW+TYjCfuGGYfyFYDDdXlIcpOmDANWUHF29Z2wNQ/eKyIONmDIQisMeusoK7zer4/mqGyoLa1dM31CxZNorRdTrLBYNKpccMEEftR6RVucfZOHBrVPxEWo/8LHf9ptlhjG5oPUUOS8FIX3syT6viZH0sMoQ+IYTg2zOb45ditlCM8DyM+U35Beb+s47YmAW+QWJDzWE6Zb0uCxGgmEZ5MkwnJDT62p0QZH5TGrvlminXIW2Fs+elUfZ/rl+XFtgU7HnuCMMyliAHcAQ/5hOlf+oHNPcKxTHK5xbzHe8P+z5pk+pVZ4Qi7rkuSyustlX5Jcdne5nEuSy+kul3tJcrnd5fIuSS6vu1wFv+55yuU8Fw8vRq6eeHgxcvXEw4uRqyceXoxcPfHwYuTqiYf2U3LN5Xsmf4903nNR8cKk64mNFyZdT4S8MOl64uSFSdcTLS9Mup6YaZyxcINg8vwF6omM5y9QTzA8f4F64t/5C9QT8s5foHaUm1h2HIe+8g7zoSx8TBAahuG9rAhzFHVi3yo+T7MfIz9qtcAypdFzmNff8qgf9tR58ePiI2cpbzA0jzZor4U8m5LyHsmzaakvnjyDGDD1AtFwR+VWfpvJkVt8xlx9L2R7Oy4+xxTj9bR9d0rttu9Oq4PtuxCDtl/j8J6rfIGpcsp8zPjNa06QQLrZoOfMNCbuvDppHEJjl2U4CffPnNyXh6Mwp6074OqEIUrC8VH67eOWogSxNCukqLZF2ldw6OG4LebwgGO+dNh8l6YtQafDO4V6fv0E4FjGWb5QeGxtn6iHlAXuHl/g76vfQpjUL3G9lGpN/8q+TOU6wSDtthRMI2t3rEj54tq1j2rXatNuS/V2Jto9wXx7pVbVAWHw1C5OHd39X18HvKbSg1PpD8l21xKCW7KITsXS+DZ+CSAovXxqKG8Tt+entyQpX6nvkKCKO+BlED69joKweHT0l+sYCPIJ7xh4kvMpEQow6Lscl1bxGWM5dqfUvhy70+rgPV2IQaWn1TNoY+xiaKXVmVayfW3dndJzKtkBtu5CDP4Y4I71wF4w9QvOwvrnOV6s9HA0/9B+lezQT+p8Ij8OL3fihw2eJcDfsVlzMvIMK4OecNvxa64TQesuZW1I35YFxIbx0hHqO8qSKmFt30fo7Utr5bd96geU237u54icv/0PAB0LYZXwr9Y4B2sc/wWu38Es1ctHzUsN6vunv5vdrNpu5fsefwHEztjVCVoAAA==";
|
||||
// System.out.println(URLDecoder.decode(unGZip(json), "utf-8"));
|
||||
|
||||
String aa = "sdfsdfasdfsdfasdf";
|
||||
String gZip = gZip(aa);
|
||||
System.err.println("加密后: " + gZip);
|
||||
|
||||
String unGZip = unGZip(gZip);
|
||||
|
||||
System.err.println("解密后: " + unGZip);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class IdWorker {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(IdWorker.class);
|
||||
|
||||
//工作id
|
||||
private long workerId;
|
||||
//数据id
|
||||
private long datacenterId;
|
||||
//12位的序列号
|
||||
private long sequence;
|
||||
|
||||
//初始时间戳
|
||||
private long twepoch = 1585644268888L;
|
||||
|
||||
//5位的机器id
|
||||
private long workerIdBits = 5L;
|
||||
//5位的机房id
|
||||
private long datacenterIdBits = 5L;
|
||||
//每毫秒内产生的id数 2 的 12次方
|
||||
private long sequenceBits = 12L;
|
||||
|
||||
//最大值
|
||||
private long maxWorkerId = -1L ^ (-1L << workerIdBits);
|
||||
private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
|
||||
private long sequenceMask = -1L ^ (-1L << sequenceBits);
|
||||
|
||||
//工作id需要左移的位数,12位
|
||||
private long workerIdShift = sequenceBits;
|
||||
//数据id需要左移位数 12+5=17位
|
||||
private long datacenterIdShift = sequenceBits + workerIdBits;
|
||||
//时间戳需要左移位数 12+5+5=22位
|
||||
private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
|
||||
|
||||
//上次时间戳,初始值为负数
|
||||
private long lastTimestamp = -1L;
|
||||
|
||||
public IdWorker(long workerId, long datacenterId, long sequence){
|
||||
if (workerId > maxWorkerId || workerId < 0) {
|
||||
|
||||
log.error(String.format("worker Id can't be greater than %d or less than 0",maxWorkerId));
|
||||
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0",maxWorkerId));
|
||||
}
|
||||
if (datacenterId > maxDatacenterId || datacenterId < 0) {
|
||||
log.error(String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId));
|
||||
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId));
|
||||
}
|
||||
|
||||
this.workerId = workerId;
|
||||
this.datacenterId = datacenterId;
|
||||
this.sequence = sequence;
|
||||
}
|
||||
|
||||
public long getWorkerId(){
|
||||
return workerId;
|
||||
}
|
||||
|
||||
public long getDatacenterId(){
|
||||
return datacenterId;
|
||||
}
|
||||
|
||||
//下一个ID生成算法
|
||||
public synchronized long nextId() {
|
||||
long timestamp = nextMillis();
|
||||
|
||||
//获取当前时间戳如果小于上次时间戳,则表示时间戳获取出现异常
|
||||
if (timestamp < lastTimestamp) {
|
||||
log.error(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
|
||||
lastTimestamp - timestamp));
|
||||
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
|
||||
lastTimestamp - timestamp));
|
||||
}
|
||||
|
||||
//获取当前时间戳如果等于上次时间戳(同一毫秒内),则在序列号加一;否则序列号赋值为0,从0开始。
|
||||
if (lastTimestamp == timestamp) {
|
||||
sequence = (sequence + 1) & sequenceMask;
|
||||
if (sequence == 0) {
|
||||
timestamp = nextMillis(lastTimestamp);
|
||||
}
|
||||
}else {
|
||||
sequence = 0;
|
||||
}
|
||||
|
||||
//将上次时间戳值刷新
|
||||
lastTimestamp = timestamp;
|
||||
|
||||
return ((timestamp - twepoch) << timestampLeftShift) |
|
||||
(datacenterId << datacenterIdShift) |
|
||||
(workerId << workerIdShift) |
|
||||
sequence;
|
||||
}
|
||||
|
||||
//获取时间戳,并与上次时间戳比较
|
||||
private long nextMillis(long lastTimestamp) {
|
||||
long timestamp = nextMillis();
|
||||
while (timestamp <= lastTimestamp) {
|
||||
timestamp = nextMillis();
|
||||
}
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
//获取系统时间戳
|
||||
private long nextMillis(){
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
|
||||
//---------------测试---------------
|
||||
public static void main(String[] args) {
|
||||
IdWorker worker = new IdWorker(1,1,1);
|
||||
for (int i = 0; i < 30; i++) {
|
||||
System.out.println(worker.nextId());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
/**
|
||||
* 获取IP方法
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class IpUtils {
|
||||
|
||||
public static String getHostIp() {
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostAddress();
|
||||
} catch (UnknownHostException e) {
|
||||
}
|
||||
return "127.0.0.1";
|
||||
}
|
||||
|
||||
public static String getHostName() {
|
||||
try {
|
||||
return InetAddress.getLocalHost().getHostName();
|
||||
} catch (UnknownHostException e) {
|
||||
}
|
||||
return "未知";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
public class KRandom {
|
||||
|
||||
private static Random random = new Random();
|
||||
|
||||
private static final char[] passkey = { '2', '3', '4', '5', '6', '7', '8',
|
||||
'9', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'p', 'a', 's', 'd',
|
||||
'f', 'g', 'h', 'j', 'k', 'z', 'x', 'c', 'v', 'b', 'n', 'm' };
|
||||
|
||||
private static final char[] numberpasskey = { '0', '1', '2', '3', '4', '5',
|
||||
'6', '7', '8', '9' };
|
||||
|
||||
public static String getRandomNumber(int len) {
|
||||
char[] c = new char[len];
|
||||
c[0] = numberpasskey[random.nextInt(9) + 1];
|
||||
for (int i = 1; i < len; i++) {
|
||||
int ir = random.nextInt(10);
|
||||
c[i] = numberpasskey[ir];
|
||||
}
|
||||
return new String(c);
|
||||
}
|
||||
|
||||
public static String getRandomString(int len) {
|
||||
char[] c = new char[len];
|
||||
|
||||
for (int i = 0; i < len; i++) {
|
||||
int ir = random.nextInt(32);
|
||||
c[i] = passkey[ir];
|
||||
}
|
||||
return new String(c);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
public class MaskUtil {
|
||||
|
||||
/**
|
||||
*
|
||||
* @param telephone
|
||||
* @return
|
||||
*/
|
||||
public static String telephone(String telephone) {
|
||||
|
||||
return telephone.replaceAll("(\\d{3})\\d{5}(\\d{3})","$1*****$2");
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param name
|
||||
* @return
|
||||
*/
|
||||
public static String name(String name) {
|
||||
if (!StringUtils.isEmpty(name)) {
|
||||
String name_ = StringUtils.left(name, 1);
|
||||
return StringUtils.rightPad(name_, StringUtils.length(name), "*");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param id
|
||||
* @return
|
||||
*/
|
||||
public static String id(String id){
|
||||
if (!StringUtils.isEmpty(id)) {
|
||||
return StringUtils.left(id, 6).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(id, 3), StringUtils.length(id), "*"), "******"));
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param address
|
||||
* @return
|
||||
*/
|
||||
public static String address(String address){
|
||||
if (!StringUtils.isEmpty(address)) {
|
||||
return StringUtils.left(address, 3).concat(StringUtils.removeStart(StringUtils.leftPad(StringUtils.right(address, address.length()-11), StringUtils.length(address), "*"), "***"));
|
||||
}
|
||||
return address;
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试Main方法
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
|
||||
System.out.println("sss===" + telephone("17733877260"));
|
||||
System.out.println("sss===" + name("张晓"));
|
||||
System.out.println("sss===" + name("张晓华月"));
|
||||
System.out.println("sss===" + id("130105198001060"));
|
||||
System.out.println("sss===" + address("石家庄市裕华东路"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
/**
|
||||
* 精确的浮点数运算
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class MathUtil {
|
||||
|
||||
|
||||
public static Long string2long(String s) {
|
||||
try {
|
||||
return Long.valueOf(s);
|
||||
}catch(Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.kelp.common.utils;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.apache.commons.beanutils.BeanUtils;
|
||||
|
||||
import net.sf.json.JSONObject;
|
||||
|
||||
public class ObjectUtil {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map<String, Object> object2Map(Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Map<String, Object> returnMap = BeanUtils.describe(object);
|
||||
returnMap.remove("class");
|
||||
|
||||
return returnMap;
|
||||
} catch (Exception e) {
|
||||
Logger.getLogger(ObjectUtil.class.getName()).log(Level.SEVERE, null, e);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object map2Object(Map<String, Object> map, Class<?> clasz) {
|
||||
if (map == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Object object = clasz.newInstance();
|
||||
BeanUtils.populate(object, map);
|
||||
return object;
|
||||
} catch (Exception e) {
|
||||
Logger.getLogger(ObjectUtil.class.getName()).log(Level.SEVERE, null, e);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static JSONObject objectToJson(Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
JSONObject json = new JSONObject();
|
||||
Map<String, Object> map = object2Map(object);
|
||||
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
json.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.kelp.common.utils.file;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class FileType {
|
||||
|
||||
|
||||
private static final HashMap<String, String> IMAGE_FILE_TYPE_MAP = new HashMap<String, String>();
|
||||
private static final HashMap<String, String> VEDIO_FILE_TYPE_MAP = new HashMap<String, String>();
|
||||
|
||||
static {
|
||||
IMAGE_FILE_TYPE_MAP.put("jpeg", "jpeg"); //JPEG (jpg)
|
||||
IMAGE_FILE_TYPE_MAP.put("png", "png"); //PNG (png)
|
||||
|
||||
VEDIO_FILE_TYPE_MAP.put("mp4", "mp4");
|
||||
}
|
||||
|
||||
public static String getImageType(String type) {
|
||||
return IMAGE_FILE_TYPE_MAP.get(type);
|
||||
}
|
||||
|
||||
public static String getVedioType(String type) {
|
||||
return VEDIO_FILE_TYPE_MAP.get(type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.kelp.common.utils.file;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class FileTypeUtil {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(FileTypeUtil.class);
|
||||
|
||||
private static final HashMap<String, String> FILE_TYPE_MAP = new HashMap<String, String>();
|
||||
|
||||
static {
|
||||
FILE_TYPE_MAP.put("ffd8ffe000104a464946", "jpg"); //JPEG (jpg)
|
||||
FILE_TYPE_MAP.put("89504e470d0a1a0a0000", "png"); //PNG (png)
|
||||
|
||||
FILE_TYPE_MAP.put("00000018667479706d70", "mp4");
|
||||
FILE_TYPE_MAP.put("00000020667479706d70", "mp4");
|
||||
FILE_TYPE_MAP.put("00000020667479706973", "mp4");
|
||||
}
|
||||
|
||||
public static String getFileType(InputStream inputStream) {
|
||||
try {
|
||||
byte[] bytes = new byte[10];
|
||||
if (inputStream.read(bytes, 0, bytes.length) == -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String fileCode = getFileHex(bytes).toLowerCase();
|
||||
|
||||
for (String key : FILE_TYPE_MAP.keySet()) {
|
||||
if (fileCode.startsWith(key.toLowerCase())) {
|
||||
return FILE_TYPE_MAP.get(key);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private final static String getFileHex(byte[] b) {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
if (b == null || b.length <= 1) {
|
||||
return null;
|
||||
}
|
||||
for (int i = 0; i < b.length; i++) {
|
||||
int v = b[i] & 0xFF;
|
||||
String hv = Integer.toHexString(v);
|
||||
if (hv.length() < 2) {
|
||||
stringBuilder.append(0);
|
||||
}
|
||||
stringBuilder.append(hv);
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* http接口
|
||||
*
|
||||
*/
|
||||
package com.kelp.common.utils.http;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class HttpUtil {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(HttpUtil.class);
|
||||
|
||||
/**
|
||||
* http
|
||||
*
|
||||
* @param url --必须带有协议:http
|
||||
* @param method
|
||||
* @param params
|
||||
* @return
|
||||
*/
|
||||
public static String http(String url, String method, String params,String charset) {
|
||||
|
||||
StringBuffer buffer = null;
|
||||
try {
|
||||
URL url_ = new URL(url);
|
||||
HttpURLConnection conn = (HttpURLConnection) url_.openConnection();
|
||||
conn.setDoOutput(true);
|
||||
conn.setDoInput(true);
|
||||
conn.setRequestMethod(method);
|
||||
conn.connect();
|
||||
// 设置http请求需要带的参数
|
||||
if (null != params) {
|
||||
OutputStream os = conn.getOutputStream();
|
||||
os.write(params.getBytes(charset));
|
||||
os.close();
|
||||
}
|
||||
|
||||
// 读取返回的内容
|
||||
InputStream is = conn.getInputStream();
|
||||
InputStreamReader isr = new InputStreamReader(is, charset);
|
||||
BufferedReader br = new BufferedReader(isr);
|
||||
buffer = new StringBuffer();
|
||||
String line = null;
|
||||
while ((line = br.readLine()) != null) {
|
||||
buffer.append(line);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.toString());
|
||||
}
|
||||
|
||||
if(buffer == null || buffer.toString().length() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
public static String https(String url, String method, String xmlParam, String charSet){
|
||||
try {
|
||||
|
||||
URL url_ = new URL(url);
|
||||
HttpsURLConnection connection = (HttpsURLConnection) url_.openConnection();
|
||||
|
||||
connection.setDoOutput(true);
|
||||
connection.setDoInput(true);
|
||||
connection.setUseCaches(false);
|
||||
connection.setRequestMethod(method);
|
||||
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
|
||||
|
||||
// 当outputStr不为null时向输出流写数据
|
||||
if (null != xmlParam) {
|
||||
OutputStream outputStream = connection.getOutputStream();
|
||||
// 注意编码格式
|
||||
outputStream.write(xmlParam.getBytes(charSet));
|
||||
outputStream.close();
|
||||
}
|
||||
|
||||
// 从输入流读取返回内容
|
||||
InputStream inputStream = connection.getInputStream();
|
||||
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charSet);
|
||||
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
|
||||
String strLine = null;
|
||||
StringBuffer buffer = new StringBuffer();
|
||||
while ((strLine = bufferedReader.readLine()) != null) {
|
||||
buffer.append(strLine);
|
||||
}
|
||||
// 释放资源
|
||||
bufferedReader.close();
|
||||
inputStreamReader.close();
|
||||
inputStream.close();
|
||||
inputStream = null;
|
||||
connection.disconnect();
|
||||
return buffer.toString();
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
String result = http("http://www.qq.com","GET",null,"utf-8");
|
||||
System.out.println(result);
|
||||
|
||||
result = https("https://www.baidu.com/","GET",null,"utf-8");
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package com.kelp.common.utils.http;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.http.HttpEntity;
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicHeader;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
|
||||
import com.alibaba.fastjson.JSON;
|
||||
|
||||
public class HttpUtilJwb {
|
||||
|
||||
public static String get(String url) {
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
HttpGet httpGet = new HttpGet(url);
|
||||
String res = null;
|
||||
CloseableHttpResponse response = null;
|
||||
try {
|
||||
response = httpclient.execute(httpGet);
|
||||
HttpEntity entity = response.getEntity();
|
||||
res = EntityUtils.toString(entity);
|
||||
EntityUtils.consume(entity);
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (response != null)
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
public static String post(String url, Map<String, String> params) {
|
||||
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
|
||||
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
|
||||
for (String key : params.keySet()) {
|
||||
nvps.add(new BasicNameValuePair(key, params.get(key)));
|
||||
}
|
||||
String res = null;
|
||||
CloseableHttpResponse response = null;
|
||||
try {
|
||||
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
|
||||
// 设置请求的报文头部的编码
|
||||
httpPost.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
|
||||
// 设置期望服务端返回的编码
|
||||
httpPost.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
|
||||
response = httpclient.execute(httpPost);
|
||||
HttpEntity entity = response.getEntity();
|
||||
res = EntityUtils.toString(entity);
|
||||
EntityUtils.consume(entity);
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (response != null)
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
public static String postJSON(String url, Map<String, String> params) {
|
||||
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
|
||||
/*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
|
||||
for (String key : params.keySet()) {
|
||||
nvps.add(new BasicNameValuePair(key, params.get(key)));
|
||||
}*/
|
||||
String res = null;
|
||||
CloseableHttpResponse response = null;
|
||||
try {
|
||||
|
||||
httpPost.setEntity(new StringEntity(JSON.toJSONString(params)));
|
||||
//httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
|
||||
// 设置请求的报文头部的编码
|
||||
httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
|
||||
// 设置期望服务端返回的编码
|
||||
httpPost.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
|
||||
response = httpclient.execute(httpPost);
|
||||
HttpEntity entity = response.getEntity();
|
||||
res = EntityUtils.toString(entity);
|
||||
EntityUtils.consume(entity);
|
||||
}catch (IllegalArgumentException ec) {
|
||||
response = null;
|
||||
//interrupted();
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (response != null)
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
public static String postJSON(String url, String json) {
|
||||
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
|
||||
/*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
|
||||
for (String key : params.keySet()) {
|
||||
nvps.add(new BasicNameValuePair(key, params.get(key)));
|
||||
}*/
|
||||
String res = null;
|
||||
CloseableHttpResponse response = null;
|
||||
try {
|
||||
|
||||
httpPost.setEntity(new StringEntity(json));
|
||||
//httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
|
||||
// 设置请求的报文头部的编码
|
||||
httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
|
||||
// 设置期望服务端返回的编码
|
||||
httpPost.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));
|
||||
response = httpclient.execute(httpPost);
|
||||
HttpEntity entity = response.getEntity();
|
||||
res = EntityUtils.toString(entity);
|
||||
EntityUtils.consume(entity);
|
||||
}catch (IllegalArgumentException ec) {
|
||||
response = null;
|
||||
//interrupted();
|
||||
} catch (ClientProtocolException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (response != null)
|
||||
try {
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.kelp.common.utils.jwt;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTVerifier;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.JWTDecodeException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.kelp.common.constant.KeyConstant;
|
||||
|
||||
public class JwtUtil {
|
||||
private static final long EXPIRE_TIME = 5 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 校验token是否正确
|
||||
*
|
||||
* @param token 密钥
|
||||
* @param secret 用户的密码
|
||||
* @return 是否正确
|
||||
*/
|
||||
public static boolean verify(String token, String id, String host, String secret) {
|
||||
|
||||
try {
|
||||
// 根据密码生成JWT效验器
|
||||
Algorithm algorithm = Algorithm.HMAC256(secret);
|
||||
JWTVerifier verifier = JWT.require(algorithm).withClaim("id", id).withClaim("host", host).build();
|
||||
// 效验TOKEN
|
||||
verifier.verify(token);
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static boolean verify(String token, String secret) {
|
||||
try {
|
||||
// 根据密码生成JWT效验器
|
||||
Algorithm algorithm = Algorithm.HMAC256(secret);
|
||||
JWTVerifier verifier = JWT.require(algorithm).build();
|
||||
// 效验TOKEN
|
||||
verifier.verify(token);
|
||||
return true;
|
||||
} catch (Exception exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getId(String token) {
|
||||
try {
|
||||
DecodedJWT jwt = JWT.decode(token);
|
||||
return jwt.getClaim("id").asString();
|
||||
} catch (JWTDecodeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static String getHost(String token) {
|
||||
try {
|
||||
DecodedJWT jwt = JWT.decode(token);
|
||||
return jwt.getClaim("host").asString();
|
||||
} catch (JWTDecodeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成签名,5min后过期
|
||||
*
|
||||
* @param userId 用户名
|
||||
* @param secret 用户的密码
|
||||
* @return 加密的token
|
||||
*/
|
||||
public static String sign(String id, String host, String secret) {
|
||||
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
|
||||
Algorithm algorithm = Algorithm.HMAC256(secret);
|
||||
// 附带username信息
|
||||
return JWT.create().withClaim("id", id).withClaim("host", host).withExpiresAt(date).sign(algorithm);
|
||||
}
|
||||
|
||||
public static void main(String[] arg) {
|
||||
String aaa = sign("kelp", "127.0.0.2", KeyConstant.JWTKEY);
|
||||
System.out.println("token===" + aaa);
|
||||
System.out.println(getId(aaa));
|
||||
System.out.println(getHost(aaa));
|
||||
System.out.println(verify(aaa, KeyConstant.JWTKEY));
|
||||
System.out.println(verify(aaa, "kelp", "127.0.0.2", KeyConstant.JWTKEY));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.kelp.common.utils.object;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* java 动态调用实体的set/get方法,完成多字段快速赋值/取值【整理】
|
||||
* https://blog.csdn.net/qq_35377323/article/details/110000937
|
||||
*/
|
||||
public class BeanValueUtil {
|
||||
|
||||
/**
|
||||
* 动态调用实体的set方法
|
||||
*
|
||||
* @param dto 实体
|
||||
* @param name 动态拼接字段
|
||||
* @param value 值
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void setValue(Object dto, String name, Object value) {
|
||||
try {
|
||||
Method[] m = dto.getClass().getMethods();
|
||||
for (int i = 0; i < m.length; i++) {
|
||||
if (("set" + name).toLowerCase().equals(m[i].getName().toLowerCase())) {
|
||||
m[i].invoke(dto, value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// TODO Auto-generated catch block
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态调用实体的get方法(注意返回值)
|
||||
*
|
||||
* @param dto 实体
|
||||
* @param name 动态拼接字段
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String getValue(Object dto, String name) {
|
||||
try {
|
||||
Method m = (Method) dto.getClass().getMethod(("get" + name));
|
||||
|
||||
String val = (String) m.invoke(dto);// 调用getter方法获取属性值
|
||||
return val;
|
||||
} catch (NoSuchMethodException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
} catch (InvocationTargetException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.kelp.common.utils.object;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import org.apache.commons.beanutils.Converter;
|
||||
|
||||
public class DateConverter implements Converter{
|
||||
|
||||
public Object convert(Class arg0, Object arg1) {
|
||||
String p = (String)arg1;
|
||||
|
||||
if(p== null || p.trim().length()==0){
|
||||
return null;
|
||||
}
|
||||
|
||||
try{
|
||||
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
|
||||
return df.parse(p.trim());
|
||||
}
|
||||
catch(Exception e){
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.kelp.common.utils.object;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import org.apache.commons.beanutils.BeanUtils;
|
||||
import org.apache.commons.beanutils.ConvertUtils;
|
||||
|
||||
import net.sf.json.JSONObject;
|
||||
|
||||
public class ObjectUtil {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map<String, Object> object2Map(Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Map<String, Object> returnMap = BeanUtils.describe(object);
|
||||
returnMap.remove("class");
|
||||
|
||||
return returnMap;
|
||||
} catch (Exception e) {
|
||||
Logger.getLogger(ObjectUtil.class.getName()).log(Level.SEVERE, null, e);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Object map2Object(Map<String, Object> map, Class<?> clasz) {
|
||||
if (map == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Object object = clasz.newInstance();
|
||||
//处理日期
|
||||
ConvertUtils.register(new DateConverter(), java.util.Date.class);
|
||||
|
||||
BeanUtils.populate(object, map);
|
||||
return object;
|
||||
} catch (Exception e) {
|
||||
Logger.getLogger(ObjectUtil.class.getName()).log(Level.SEVERE, null, e);
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static JSONObject objectToJson(Object object) {
|
||||
if (object == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
JSONObject json = new JSONObject();
|
||||
Map<String, Object> map = object2Map(object);
|
||||
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
json.put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.kelp.common.utils.security;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.DigestUtils;
|
||||
|
||||
/**
|
||||
* Md5加密方法
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class Md5Utils {
|
||||
private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
|
||||
|
||||
private static byte[] md5(String s) {
|
||||
MessageDigest algorithm;
|
||||
try {
|
||||
algorithm = MessageDigest.getInstance("MD5");
|
||||
algorithm.reset();
|
||||
algorithm.update(s.getBytes("UTF-8"));
|
||||
byte[] messageDigest = algorithm.digest();
|
||||
return messageDigest;
|
||||
} catch (Exception e) {
|
||||
log.error("MD5 Error...", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static final String toHex(byte hash[]) {
|
||||
if (hash == null) {
|
||||
return null;
|
||||
}
|
||||
StringBuffer buf = new StringBuffer(hash.length * 2);
|
||||
int i;
|
||||
|
||||
for (i = 0; i < hash.length; i++) {
|
||||
if ((hash[i] & 0xff) < 0x10) {
|
||||
buf.append("0");
|
||||
}
|
||||
buf.append(Long.toString(hash[i] & 0xff, 16));
|
||||
}
|
||||
return buf.toString();
|
||||
}
|
||||
|
||||
public static String hash(String s) {
|
||||
try {
|
||||
return new String(toHex(md5(s)).getBytes("UTF-8"), "UTF-8");
|
||||
} catch (Exception e) {
|
||||
log.error("not supported charset...{}", e);
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
public static String hash(String word, String salt) {
|
||||
// 拼接原密码与盐值
|
||||
String str = salt + word + salt;
|
||||
// 循环加密5次
|
||||
for (int i = 0; i < 5; i++) {
|
||||
str = DigestUtils.md5DigestAsHex(str.getBytes());
|
||||
}
|
||||
// 返回结果
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试Main方法
|
||||
*
|
||||
* @param args
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
String sss = Md5Utils.hash("d1234567");
|
||||
System.err.println("加密后数据:" + sss);
|
||||
System.out.println(hash("d1234567",""));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* 初始化敏感词库,将敏感词加入到HashMap中,构建DFA算法模型
|
||||
*/
|
||||
package com.kelp.common.utils.security;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
public class SensitiveWordInit {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SensitiveWordInit.class);
|
||||
|
||||
private String ENCODING = "UTF-8";
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
public Map initDFAHash(String filePath) {
|
||||
try {
|
||||
return makeDFAHash(readDictFile(filePath));
|
||||
} catch (Exception e) {
|
||||
log.error("sensitive word init failed:" + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@SuppressWarnings({ "rawtypes", "unchecked" })
|
||||
private HashMap makeDFAHash(Set<String> keyWordSet) {
|
||||
HashMap dfaMap = new HashMap(keyWordSet.size());
|
||||
String key = null;
|
||||
Map nowMap = null;
|
||||
Map<String, String> worMap = null;
|
||||
Iterator<String> iterator = keyWordSet.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
key = iterator.next();
|
||||
nowMap = dfaMap;
|
||||
for (int i = 0; i < key.length(); i++) {
|
||||
char keyChar = key.charAt(i);
|
||||
Object wordMap = nowMap.get(keyChar);
|
||||
|
||||
if (wordMap != null) {
|
||||
nowMap = (Map) wordMap;
|
||||
} else {
|
||||
worMap = new HashMap<String, String>();
|
||||
worMap.put("isEnd", "0");
|
||||
nowMap.put(keyChar, worMap);
|
||||
nowMap = worMap;
|
||||
}
|
||||
|
||||
if (i == key.length() - 1) {
|
||||
nowMap.put("isEnd", "1");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return dfaMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件中的内容格式为每行一个词
|
||||
* @return
|
||||
*/
|
||||
@SuppressWarnings("resource")
|
||||
private Set<String> readDictFile(String filePath) {
|
||||
Set<String> set = null;
|
||||
File file = new File(filePath);
|
||||
try {
|
||||
InputStreamReader isreader = new InputStreamReader(new FileInputStream(file), ENCODING);
|
||||
if (file.isFile() && file.exists()) {
|
||||
set = new HashSet<String>();
|
||||
BufferedReader bufferedReader = new BufferedReader(isreader);
|
||||
String word = null;
|
||||
while ((word = bufferedReader.readLine()) != null) {
|
||||
set.add(word);
|
||||
}
|
||||
}
|
||||
isreader.close();
|
||||
} catch (Exception e) {
|
||||
log.error("sensitive word init failed:" + e.getMessage());
|
||||
}
|
||||
return set;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/**
|
||||
* 敏感词过滤
|
||||
*/
|
||||
package com.kelp.common.utils.security;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.ResourceUtils;
|
||||
|
||||
public class SensitivewordUtils {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SensitivewordUtils.class);
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
private static Map dfaMap = null;
|
||||
public static int minMatchTYpe = 1;
|
||||
public static int maxMatchType = 2;
|
||||
|
||||
/**
|
||||
* 构造函数,初始化敏感词库
|
||||
*/
|
||||
public SensitivewordUtils() {
|
||||
try {
|
||||
if(dfaMap == null) {
|
||||
dfaMap = new SensitiveWordInit().initDFAHash(ResourceUtils.getURL("classpath:").getPath() + "/sensitiveword.txt");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("sensitive word init failed : " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断文字是否包含敏感字符
|
||||
*
|
||||
* @param txt 文字
|
||||
* @param matchType 匹配规则 1:最小匹配规则,2:最大匹配规则
|
||||
* @return 若包含返回true,否则返回false
|
||||
*/
|
||||
public boolean isContaintSensitiveWord(String txt, int matchType) {
|
||||
boolean flag = false;
|
||||
for (int i = 0; i < txt.length(); i++) {
|
||||
int matchFlag = this.checkSensitiveWord(txt, i, matchType);
|
||||
if (matchFlag > 0) {
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
return flag;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文字中的敏感词
|
||||
*
|
||||
* @param txt 文字
|
||||
* @param matchType 匹配规则 1:最小匹配规则,2:最大匹配规则
|
||||
* @return
|
||||
*/
|
||||
public Set<String> getSensitiveWord(String txt, int matchType) {
|
||||
Set<String> sensitiveWordList = new HashSet<String>();
|
||||
|
||||
for (int i = 0; i < txt.length(); i++) {
|
||||
int length = checkSensitiveWord(txt, i, matchType);
|
||||
if (length > 0) {
|
||||
sensitiveWordList.add(txt.substring(i, i + length));
|
||||
i = i + length - 1;
|
||||
}
|
||||
}
|
||||
|
||||
return sensitiveWordList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换敏感字字符
|
||||
*
|
||||
* @param txt
|
||||
* @param matchType
|
||||
* @param replaceChar 替换字符,默认*
|
||||
*/
|
||||
public String replaceSensitiveWord(String txt, int matchType, String replaceChar) {
|
||||
String resultTxt = txt;
|
||||
Set<String> set = getSensitiveWord(txt, matchType);
|
||||
Iterator<String> iterator = set.iterator();
|
||||
String word = null;
|
||||
String replaceString = null;
|
||||
while (iterator.hasNext()) {
|
||||
word = iterator.next();
|
||||
replaceString = getReplaceChars(replaceChar, word.length());
|
||||
resultTxt = resultTxt.replaceAll(word, replaceString);
|
||||
}
|
||||
|
||||
return resultTxt;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取替换字符串
|
||||
*
|
||||
* @param replaceChar
|
||||
* @param length
|
||||
* @return
|
||||
*/
|
||||
private String getReplaceChars(String replaceChar, int length) {
|
||||
String resultReplace = replaceChar;
|
||||
for (int i = 1; i < length; i++) {
|
||||
resultReplace += replaceChar;
|
||||
}
|
||||
|
||||
return resultReplace;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查文字中是否包含敏感字符,检查规则如下:<br>
|
||||
*
|
||||
* @param txt
|
||||
* @param beginIndex
|
||||
* @param matchType
|
||||
* @return,如果存在,则返回敏感词字符的长度,不存在返回0
|
||||
*/
|
||||
@SuppressWarnings({ "rawtypes" })
|
||||
public int checkSensitiveWord(String txt, int beginIndex, int matchType) {
|
||||
boolean flag = false;
|
||||
int matchFlag = 0;
|
||||
char word = 0;
|
||||
Map nowMap = dfaMap;
|
||||
for (int i = beginIndex; i < txt.length(); i++) {
|
||||
word = txt.charAt(i);
|
||||
nowMap = (Map) nowMap.get(word);
|
||||
if (nowMap != null) {
|
||||
matchFlag++;
|
||||
if ("1".equals(nowMap.get("isEnd"))) {
|
||||
flag = true;
|
||||
if (SensitivewordUtils.minMatchTYpe == matchType) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matchFlag < 2 || !flag) {
|
||||
matchFlag = 0;
|
||||
}
|
||||
return matchFlag;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
SensitivewordUtils filter = new SensitivewordUtils();
|
||||
System.out.println("敏感词的数量:" + filter.dfaMap.size());
|
||||
String string = "太多的伤感情怀也许只局限于饲养基地 荧幕中的情节,主人公尝试着去用某种方式渐渐的很潇洒地释自杀指南怀那些自己经历的伤感。"
|
||||
+ "然后法轮功 我们的扮演的角色就是跟随着主人公的喜红客联盟 怒哀乐而过于牵强的把自己的情感也附加于银幕情节中,然后感动就流泪,"
|
||||
+ "难过就躺在某一个人的怀里尽情的阐述心扉或者手机卡复制器一个人一杯红酒一部电影在夜三级片 深人静的晚上,关上电话静静的发呆着。";
|
||||
System.out.println("待检测语句字数:" + string.length());
|
||||
long beginTime = System.currentTimeMillis();
|
||||
Set<String> set = filter.getSensitiveWord(string, 1);
|
||||
System.out.println("" + filter.replaceSensitiveWord(string,1,"*"));
|
||||
long endTime = System.currentTimeMillis();
|
||||
System.out.println("语句中包含敏感词的个数为:" + set.size() + "。包含:" + set);
|
||||
System.out.println("总共消耗时间为:" + (endTime - beginTime));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.kelp.common.utils.spring;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SpringUtil implements ApplicationContextAware {
|
||||
|
||||
private static ApplicationContext applicationContext;
|
||||
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
SpringUtil.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
public static ApplicationContext getApplicationContext() {
|
||||
return applicationContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据Bean名称获取实例
|
||||
*
|
||||
* @param name
|
||||
* Bean注册名称
|
||||
*
|
||||
* @return bean实例
|
||||
*
|
||||
* @throws BeansException
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T getBean(String name) throws BeansException {
|
||||
return (T)applicationContext.getBean(name);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param clasz
|
||||
* @return
|
||||
* @throws BeansException
|
||||
*/
|
||||
public static <T> T getBean(Class<T> clasz) throws BeansException {
|
||||
return (T)applicationContext.getBean(clasz);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package com.kelp.common.xss;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.servlet.Filter;
|
||||
import javax.servlet.FilterChain;
|
||||
import javax.servlet.FilterConfig;
|
||||
import javax.servlet.ServletException;
|
||||
import javax.servlet.ServletRequest;
|
||||
import javax.servlet.ServletResponse;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
/**
|
||||
* 防止XSS攻击的过滤器
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class XssFilter implements Filter {
|
||||
/**
|
||||
* 排除链接
|
||||
*/
|
||||
public List<String> excludes = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* xss过滤开关
|
||||
*/
|
||||
public boolean enabled = false;
|
||||
|
||||
@Override
|
||||
public void init(FilterConfig filterConfig) throws ServletException {
|
||||
String tempExcludes = filterConfig.getInitParameter("excludes");
|
||||
String tempEnabled = filterConfig.getInitParameter("enabled");
|
||||
if (StringUtils.isNotEmpty(tempExcludes)) {
|
||||
String[] url = tempExcludes.split(",");
|
||||
for (int i = 0; url != null && i < url.length; i++) {
|
||||
excludes.add(url[i]);
|
||||
}
|
||||
}
|
||||
if (StringUtils.isNotEmpty(tempEnabled)) {
|
||||
enabled = Boolean.valueOf(tempEnabled);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
HttpServletRequest req = (HttpServletRequest) request;
|
||||
HttpServletResponse resp = (HttpServletResponse) response;
|
||||
if (handleExcludeURL(req, resp)) {
|
||||
chain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
|
||||
chain.doFilter(xssRequest, response);
|
||||
}
|
||||
|
||||
private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
|
||||
if (!enabled) {
|
||||
return true;
|
||||
}
|
||||
if (excludes == null || excludes.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
String url = request.getServletPath();
|
||||
for (String pattern : excludes) {
|
||||
Pattern p = Pattern.compile("^" + pattern);
|
||||
Matcher m = p.matcher(url);
|
||||
if (m.find()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void destroy() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.kelp.common.xss;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletRequestWrapper;
|
||||
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
/**
|
||||
* XSS过滤处理
|
||||
*
|
||||
* @author kelp
|
||||
*/
|
||||
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
|
||||
/**
|
||||
* @param request
|
||||
*/
|
||||
public XssHttpServletRequestWrapper(HttpServletRequest request) {
|
||||
super(request);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] getParameterValues(String name) {
|
||||
String[] values = super.getParameterValues(name);
|
||||
if (values != null) {
|
||||
int length = values.length;
|
||||
String[] escapseValues = new String[length];
|
||||
for (int i = 0; i < length; i++) {
|
||||
// 防xss攻击和过滤前后空格
|
||||
escapseValues[i] = HtmlUtils.htmlEscape(values[i]).trim();
|
||||
}
|
||||
return escapseValues;
|
||||
}
|
||||
return super.getParameterValues(name);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user