Commit 549bd709 authored by ZWT's avatar ZWT

都删了

parent 1c2c1d75
package pps.core.auth;
/**
* 基础认证Auth
*
* @author ZWT
* @date 2023/01/09
*/
public interface Auth {
/**
* 基础认证Auth
*
* @return {@link String}
*/
String getAuth();
}
\ No newline at end of file
package pps.core.auth;
import org.apache.commons.codec.binary.Base64;
import java.nio.charset.StandardCharsets;
/**
* 用户名密码认证
*
* @author ZWT
* @date 2023/01/09
*/
public class BasicAuth implements Auth {
private String username;
private String password;
public BasicAuth(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public String getAuth() {
String auth = String.format("%s:%s", this.username, this.password);
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.ISO_8859_1));
return "Basic " + new String(encodedAuth);
}
}
\ No newline at end of file
package pps.core.auth;
/**
* Bearer Token 认证
*
* @author ZWT
* @date 2023/01/09
*/
public class BearerAuth implements Auth {
private String token;
public BearerAuth(String token) {
this.token = token;
}
@Override
public String getAuth() {
return "Bearer " + this.token;
}
}
\ No newline at end of file
package pps.core.auth;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* http请求客户端
*
* @author ZWT
* @date 2023/01/09
*/
@Slf4j
public class HttpRequestClient {
/**
* 默认连接超时(10s)
*/
private static final int DEFAULT_CONNECT_TIMEOUT = 30_000;
/**
* 默认读取超时(10s)
*/
private static final int DEFAULT_READ_TIMEOUT = 30_000;
/**
* 身份验证
*/
private Auth auth;
/**
* http客户端
*/
private HttpClient httpClient;
/**
* 用户名密码认证,默认的超时时间(10s)
*
* @param username 用户名
* @param password
* @param httpsFlag
*/
public HttpRequestClient(String username, String password, boolean httpsFlag) throws NoSuchAlgorithmException, KeyManagementException {
this(username, password,
DEFAULT_CONNECT_TIMEOUT,
DEFAULT_READ_TIMEOUT,
httpsFlag
);
}
/**
* 用户名密码认证,自定义超时时间
*
* @param username 用户名
* @param password
* @param connectTimeout
* @param readTimeout
* @param httpsFlag
*/
public HttpRequestClient(String username, String password, int connectTimeout, int readTimeout, boolean httpsFlag) throws NoSuchAlgorithmException, KeyManagementException {
this.auth = new BasicAuth(username, password);
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
httpClientBuilder.setDefaultRequestConfig(getRequestConfig(connectTimeout, readTimeout));
if (httpsFlag) {
httpClientBuilder.setSSLSocketFactory(this.createIgnoreVerifySSL());
}
this.httpClient = httpClientBuilder.build();
}
/**
* BearerToken 认证,默认的超时时间(10s)
*
* @param bearerToken
*/
public HttpRequestClient(String bearerToken) {
this(bearerToken,
DEFAULT_CONNECT_TIMEOUT,
DEFAULT_READ_TIMEOUT
);
}
/**
* BearerToken 认证,自定义超时时间
*
* @param bearerToken 不记名令牌
* @param connectTimeout 连接超时
* @param readTimeout 读取超时
*/
public HttpRequestClient(String bearerToken, int connectTimeout, int readTimeout) {
this.auth = new BearerAuth(bearerToken);
this.httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(getRequestConfig(connectTimeout, readTimeout))
.build();
}
/**
* 设置 HTTP 请求超时时间
*
* @param connectTimeout tcp 连接超时时间
* @param readTimeout 读取数据超时时间
* @return
*/
private RequestConfig getRequestConfig(int connectTimeout, int readTimeout) {
return RequestConfig.custom()
.setConnectTimeout(connectTimeout)
.setConnectionRequestTimeout(connectTimeout)
.setSocketTimeout(readTimeout)
.build();
}
/**
* 发送 GET 请求,不带参数
*
* @param url
* @return
*/
public String doGet(String url) {
return doGet(url, new HashMap<>());
}
/**
* 发送 GET 请求,不带参数
*
* @param uri
* @return
*/
public String doGet(URI uri) {
return doGet(uri, new HashMap<>());
}
/**
* 发送 GET 请求,K-V 形式参数
*
* @param url url
* @param params 参数个数
* @return {@link String}
*/
public String doGet(String url, Map<String, String> params) {
RequestBuilder reqBuilder = RequestBuilder.get(url);
return doGet(reqBuilder, params);
}
/**
* 发送 GET 请求,K-V 形式参数
*
* @param uri
* @param params
* @return
*/
public String doGet(URI uri, Map<String, String> params) {
RequestBuilder reqBuilder = RequestBuilder.get(uri);
return doGet(reqBuilder, params);
}
/**
* 发送 GET 请求,不带参数,返回指定类型的 class
*
* @param url url
* @param responseType 响应类型
* @return {@link T}
*/
public <T> T getForObject(String url, Class<T> responseType) {
RequestBuilder reqBuilder = RequestBuilder.get(url);
return getForObject(reqBuilder, responseType);
}
/**
* 发送 GET 请求,不带参数,返回指定类型的 class
*
* @param uri uri
* @param responseType 响应类型
* @return {@link T}
*/
public <T> T getForObject(URI uri, Class<T> responseType) {
RequestBuilder reqBuilder = RequestBuilder.get(uri);
return getForObject(reqBuilder, responseType);
}
/**
* 发送 GET 请求,不带参数,返回指定类型的 class(需要认证)
*
* @param reqBuilder 构造器
* @param responseType 响应类型
* @return {@link T}
*/
public <T> T getForObject(RequestBuilder reqBuilder, Class<T> responseType) {
reqBuilder.addHeader(HttpHeaders.AUTHORIZATION, auth.getAuth());
try {
HttpResponse resp = httpClient.execute(reqBuilder.build());
String result = EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
return JSONUtil.toBean(result, responseType);
} catch (IOException e) {
log.error("getForObject 异常: reqBuilder={}, responseType={}", reqBuilder, responseType, e);
return null;
}
}
/**
* 发送 POST 请求,JSON 形式
*
* @param url
* @param json json字符串
* @return
*/
public String doPost(String url, String json) {
try {
HttpResponse resp = this.exchange(HttpMethod.POST, url, json);
return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("doPost 异常: url={}, json={}", url, json, e);
return null;
}
}
/**
* 发送 POST 请求,x-www-form-urlencoded 形式
*
* @param url
* @param param 参数
* @return {@link String}
*/
public String doPostForm(String url, Map<String, Object> param) {
try {
HttpResponse resp = this.exchangeForm(url, param);
return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("doPost form 异常: url={}", url, e);
return null;
}
}
/**
* 发送 POST 请求,JSON 形式,返回 HttpResponse
*
* @param url
* @param json json字符串
* @return
*/
public HttpResponse doPostResp(String url, String json) {
return this.exchange(HttpMethod.POST, url, json);
}
/**
* 发送 PUT 请求,JSON 形式
*
* @param url
* @param json json字符串
* @return
*/
public HttpResponse doPut(String url, String json) {
return this.exchange(HttpMethod.PUT, url, json);
}
/**
* 发送 PUT 请求,JSON 形式
*
* @param url
* @param json json字符串
* @return
*/
public HttpResponse doDelete(String url, String json) {
return this.exchange(HttpMethod.DELETE, url, json);
}
/*---------------------------------------私有方法---------------------------------------*/
/**
* 发送请求POST x-www-form-urlencoded
*
* @param url
* @param param 参数
* @return {@link HttpResponse}
*/
private HttpResponse exchangeForm(String url, Map<String, Object> param) {
List<NameValuePair> params = new ArrayList<>();
for (Map.Entry<String, Object> entry : param.entrySet()) {
params.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
}
try {
String authString = auth.getAuth();
RequestBuilder reqBuilder = RequestBuilder.create(HttpMethod.POST.toString())
.setUri(url)
.addHeader(HttpHeaders.AUTHORIZATION, authString)
.addHeader("Content-Type", ContentType.APPLICATION_FORM_URLENCODED.toString());
log.info("exchangeForm,接口地址:{}", url);
log.info("exchangeForm,认证头:{} {}", HttpHeaders.AUTHORIZATION, authString);
log.info("exchangeForm,认证头:{} {}", "Content-Type", ContentType.APPLICATION_FORM_URLENCODED);
reqBuilder.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
return httpClient.execute(reqBuilder.build());
} catch (IOException e) {
log.error("doPost form 异常: url={}", url, e);
return null;
}
}
/**
* 发送请求
*
* @param method 方法
* @param url url
* @param json json
* @return {@link HttpResponse}
*/
private HttpResponse exchange(HttpMethod method, String url, String json) {
RequestBuilder reqBuilder = RequestBuilder.create(method.toString())
.setUri(url)
.addHeader(HttpHeaders.AUTHORIZATION, auth.getAuth())
.addHeader("Accept", ContentType.APPLICATION_JSON.toString())
.addHeader("Content-type", ContentType.APPLICATION_JSON.toString());
if (StringUtils.isNotBlank(json)) {
reqBuilder.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
}
try {
return httpClient.execute(reqBuilder.build());
} catch (IOException e) {
log.error("doPost 异常: url={}, json={}", url, json, e);
return null;
}
}
/**
* 发送get请求
*
* @param reqBuilder 构造器
* @param params 参数
* @return {@link String}
*/
private String doGet(RequestBuilder reqBuilder, Map<String, String> params) {
reqBuilder.addHeader(HttpHeaders.AUTHORIZATION, auth.getAuth());
for (Map.Entry<String, String> entry : params.entrySet()) {
reqBuilder.addParameter(entry.getKey(), entry.getValue());
}
try {
HttpResponse resp = httpClient.execute(reqBuilder.build());
return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
} catch (IOException e) {
log.error("doGet 异常: reqBuilder={}, params={}", reqBuilder, params, e);
return null;
}
}
/**
* 绕过SSL、TLS证书
*
* @return {@link SSLConnectionSocketFactory}
* @throws NoSuchAlgorithmException 没有这样算法异常
* @throws KeyManagementException 密钥管理例外
*/
private SSLConnectionSocketFactory createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
// 创建一个上下文(此处指定的协议类型似乎不是重点)
SSLContext ctx = SSLContext.getInstance("TLS");
// 创建一个跳过SSL证书的策略
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
// 使用上面的策略初始化上下文
ctx.init(null, new TrustManager[]{tm}, null);
// 创建一个包含各种SSL协议的SSLConnectionSocketFactory实例对象
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(ctx,
new String[]{"SSLv3", "TLSv1", "TLSv1.1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
return ssf;
}
}
package pps.core.common.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import xstartup.annotation.XText;
import java.util.Date;
/**
* 基础
*
* @author ZWT
* @date 2023/08/25 15:46
*/
@Data
public class BaseModel {
@XText("ID")
@TableId(type = IdType.ASSIGN_UUID)
private String id;
@XText("是否删除(0_是;1_否)")
@TableField
private Integer isDeleted;
@XText("创建人ID")
@TableField
private String createById;
@XText("创建人名称")
@TableField
private String createByName;
@XText("创建时间")
@TableField
private Date createTime;
@XText("修改人ID")
@TableField
private String modifyById;
@XText("修改人名称")
@TableField
private String modifyByName;
@XText("修改时间")
@TableField
private Date modifyTime;
}
package pps.core.common.enums;
import xstartup.error.XError;
/**
* 业务错误
*
* @author ZWT
* @date 2023/09/12
*/
public enum BusinessError implements XError {
FileFormatError(2204, "文件格式有误,请检查上传文件格式!"),
UndiscoveredData(2205, "未发现数据,请检查后重新导入!"),
;
private int code;
private String text;
BusinessError(int code, String text) {
this.code = code;
this.text = text;
}
@Override
public int getCode() {
return code;
}
@Override
public String getText() {
return text;
}
}
package pps.core.common.enums;
import com.baomidou.mybatisplus.annotation.EnumValue;
/**
* 作业计划影响状态字典
*/
public enum TaskPlanTaskAffectDic implements DictEnum {
Affect_Upload(11, "", null),
Affect_Upload_False(0, "否", Affect_Upload),
Affect_Upload_True(1, "是", Affect_Upload),
Affect_Ability(12, "", null),
Affect_Ability_False(0, "否", Affect_Ability),
Affect_Ability_True(1, "是(影响联络站转供能力)", Affect_Ability),
Affect_Ability_True2(2, "是(含截断、限压、限流、干线截断阀旁通流程30min以上)", Affect_Ability),
Affect_Venting(13, "", null),
Affect_Venting_False(0, "否", Affect_Venting),
Affect_Venting_True(1, "管道放空", Affect_Venting),
Affect_Venting_True2(2, "全站放空", Affect_Venting),
Affect_Venting_True3(3, "站内局部放空", Affect_Venting),
Affect_SupplyGas(14, "", null),
Affect_SupplyGas_False(0, "否", Affect_SupplyGas),
Affect_SupplyGas_True(1, "影响重要不可中断用户供气(用户暂不同意)", Affect_SupplyGas),
Affect_SupplyGas_True3(2, "影响重要不可中断用户供气(用户已同意)", Affect_SupplyGas),
Affect_SupplyGas_True2(3, "影响可中断用户供气", Affect_SupplyGas),
Affect_Run(15, "", null),
Affect_Run_False(0, "否", Affect_Run),
Affect_Run_True(1, "影响在用机组", Affect_Run),
Affect_Run_True2(2, "影响备用机组", Affect_Run),
Affect_Communication(16, "", null),
Affect_Communication_False(0, "否", Affect_Communication),
Affect_Communication_True(1, "是", Affect_Communication),
Affect_Alarm(17, "", null),
Affect_Alarm_False(0, "否", Affect_Alarm),
Affect_Alarm_True(1, "是", Affect_Alarm),
Affect_Other(99, "未知", null),
;
@EnumValue
private Integer value;
private String desc;
private TaskPlanTaskAffectDic parent;
TaskPlanTaskAffectDic(Integer value, String desc, TaskPlanTaskAffectDic parent) {
this.desc = desc;
this.value = value;
this.parent = parent;
}
public static TaskPlanTaskAffectDic findByValue(Integer value) {
for (TaskPlanTaskAffectDic item : values()) {
if (item.getValue().equals(value)) {
return item;
}
}
return Affect_Other;
}
public static TaskPlanTaskAffectDic findBySubValue(Integer parentValue, Integer value) {
TaskPlanTaskAffectDic parentDic = Affect_Other;
for (TaskPlanTaskAffectDic item : values()) {
if (item.getValue().equals(parentValue)) {
parentDic = item;
}
}
for (TaskPlanTaskAffectDic item : values()) {
if (item.getParent() != null && item.getParent().equals(parentDic) && item.getValue().equals(value)) {
return item;
}
}
return Affect_Other;
}
public static TaskPlanTaskAffectDic findBySubDesc(Integer parentValue, String desc) {
TaskPlanTaskAffectDic parentDic = Affect_Other;
for (TaskPlanTaskAffectDic item : values()) {
if (item.getValue().equals(parentValue)) {
parentDic = item;
}
}
for (TaskPlanTaskAffectDic item : values()) {
if (item.getParent() != null && item.getParent().equals(parentDic) && item.getDesc().equals(desc)) {
return item;
}
}
return Affect_Other;
}
@Override
public Integer getValue() {
return value;
}
@Override
public String getDesc() {
return desc;
}
public TaskPlanTaskAffectDic getParent() {
return parent;
}
}
package pps.core.common.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* @author lixueyan
* @date 2022/1/12 0012 10:46
*/
public class AESUtil {
private static String KEY = "abcdef0123456789"; // 长度必须是 16
private static String IV = "abcdef0123456789"; // 长度必须是 16
public static void main(String args[]) throws Exception {
String content = "dddddddddd";
//加密
String encrypted = encrypt(content, KEY, IV);
//解密
String decrypted = decrypt(encrypted, KEY, IV);
System.out.println("加密前:" + content);
System.out.println("加密后:" + encrypted);
System.out.println("解密后:" + decrypted);
}
public static String encrypt(String content) throws Exception {
return encrypt(content, KEY, IV);
}
/**
* 加密返回的数据转换成 String 类型
*
* @param content 明文
* @param key 秘钥
* @param iv 初始化向量是16位长度的字符串
* @return
* @throws Exception
*/
public static String encrypt(String content, String key, String iv) throws Exception {
// 将返回的加密过的 byte[] 转换成Base64编码字符串 !!!!很关键
return base64ToString(AES_CBC_Encrypt(content.getBytes(), key.getBytes(), iv.getBytes()));
}
public static String decrypt(String content) {
try {
return decrypt(content, KEY, IV);
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
/**
* 将解密返回的数据转换成 String 类型
*
* @param content Base64编码的密文
* @param key 秘钥
* @param iv 初始化向量是16位长度的字符串
* @return
* @throws Exception
*/
public static String decrypt(String content, String key, String iv) throws Exception {
// stringToBase64() 将 Base64编码的字符串转换成 byte[] !!!与base64ToString()配套使用
return new String(AES_CBC_Decrypt(stringToBase64(content), key.getBytes(), iv.getBytes()));
}
private static byte[] AES_CBC_Encrypt(byte[] content, byte[] keyBytes, byte[] iv) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
private static byte[] AES_CBC_Decrypt(byte[] content, byte[] keyBytes, byte[] iv) {
try {
SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
byte[] result = cipher.doFinal(content);
return result;
} catch (Exception e) {
System.out.println("exception:" + e.toString());
}
return null;
}
/**
* 字符串装换成 Base64
*/
public static byte[] stringToBase64(String key) throws Exception {
return Base64.decodeBase64(key.getBytes());
}
/**
* Base64装换成字符串
*/
public static String base64ToString(byte[] key) throws Exception {
return new Base64().encodeToString(key);
}
}
package pps.core.common.utils;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.regex.Pattern;
/**
* Description:
* date: 2020/11/18 16:47
*
* @author zhujiangwei
*/
public class BigDecimalUtil {
/**
* 小数格式化
*
* @param obj 原数据
* @return
*/
public static String parseBigDecimal2Str(Object obj) {
return removeLastZero(String.valueOf(parseBigDecimal(obj, 10)));
}
/**
* 小数格式化
*
* @param obj 原数据
* @return
*/
public static double parseBigDecimal2Double(Object obj) {
return Double.parseDouble(removeLastZero(String.valueOf(parseBigDecimal(obj, 10))));
}
/**
* 小数格式化(保留固定的小数位数)
*
* @param obj 原数据
* @param num 保留小数的位数
* @return
*/
public static String parseBigDecimal2Str(Object obj, int num) {
return String.valueOf(parseBigDecimal(obj, num));
}
public static BigDecimal parseBigDecimal(Object obj, int num) {
if (obj == null) return BigDecimal.ZERO.setScale(num, BigDecimal.ROUND_HALF_UP);
BigDecimal org = null;
if (obj instanceof BigDecimal) {
org = (BigDecimal) obj;
} else {
String pattern = "([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])";
if (!Pattern.matches(pattern, String.valueOf(obj))) { //非数字字符串
org = BigDecimal.ZERO;
} else {
org = parseObj2BigDecimal(obj);
}
}
return org.setScale(num, BigDecimal.ROUND_HALF_UP);
}
/**
* 空值转换
*/
public static BigDecimal parseNull2Zero(BigDecimal org) {
return org == null ? BigDecimal.ZERO : org;
}
/**
* 去掉数字字符串末尾的0
*/
public static String removeLastZero(String org) {
if (org == null || "".equals(org.trim())) return "0";
//String pattern = "(-?([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9]))";
//if(!Pattern.matches(pattern,org)) return "0"; //非数字字符串
DecimalFormat format = new DecimalFormat("###############.##########");
return format.format(new Double(org));
}
public static BigDecimal parseObj2BigDecimal(Object obj) {
if (obj == null) return BigDecimal.ZERO;
String str = String.valueOf(obj).trim();
if (str.length() == 0) return BigDecimal.ZERO;
BigDecimal result = null;
try {
result = new BigDecimal(str);
} catch (Exception e) {
e.printStackTrace();
result = BigDecimal.ZERO;
}
return result;
}
}
package pps.core.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* 转换工具类
*
* @author lixueyan
*/
public class ConvertUtils {
private static Logger logger = LoggerFactory.getLogger(ConvertUtils.class);
public static <T> T sourceToTarget(Object source, Class<T> target) {
if (source == null) {
return null;
}
T targetObject = null;
try {
targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
} catch (Exception e) {
logger.error("convert error ", e);
}
return targetObject;
}
public static <T> List<T> sourceToTarget(Collection<?> sourceList, Class<T> target) {
if (sourceList == null) {
return null;
}
List targetList = new ArrayList<>(sourceList.size());
try {
for (Object source : sourceList) {
T targetObject = target.newInstance();
BeanUtils.copyProperties(source, targetObject);
targetList.add(targetObject);
}
} catch (Exception e) {
logger.error("convert error ", e);
}
return targetList;
}
}
package pps.core.common.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DynamicPwd {
public static String buildDynPwd() {
String str = new SimpleDateFormat("dd:HH:mm").format(new Date());
String[] items = str.split(":");
String pwd = String.format("%02d%02d%02d", Integer.parseInt(items[2]), Integer.parseInt(items[1]) + 1, Integer.parseInt(items[0]));
return pwd;
}
public static void main(String[] args) throws Exception {
String pwd = buildDynPwd();
System.out.println(pwd);
}
}
package pps.core.common.utils;
/**
* @author lixueyan
* @date 2023/2/3 0003 17:36
*/
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 动态excel模板 工具类
*/
public class ExcelTemplateUtils {
/**
* @param @param filePath Excel文件路径
* @param @param handers Excel列标题(数组)
* @param @param downData 下拉框数据(数组)
* @param @param downRows 下拉列的序号(数组,序号从0开始)
* @param templateInputStream
* @return void
* @throws
* @Title: createExcelTemplate
* @Description: 生成Excel导入模板
*/
public static void createExcelTemplate(String filePath, //String[] handers,
InputStream templateInputStream, List<String[]> downData, String[] downRows) throws IOException {
//HSSFWorkbook wb = new HSSFWorkbook(templateInputStream);//创建工作薄
XSSFWorkbook wb = new XSSFWorkbook(templateInputStream);
//表头样式
XSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
//字体样式
XSSFFont fontStyle = wb.createFont();
fontStyle.setFontName("微软雅黑");
fontStyle.setFontHeightInPoints((short) 12);
fontStyle.setBold(true);
style.setFont(fontStyle);
//获取sheet
XSSFSheet sheet1 = wb.getSheetAt(0);
XSSFSheet sheet2 = wb.getSheetAt(1);
//新建sheet
//XSSFSheet sheet1 = wb.createSheet("Sheet1");
//XSSFSheet sheet2 = wb.createSheet("Sheet2");
//XSSFSheet sheet3 = wb.createSheet("Sheet3");
//生成sheet1内容
//XSSFRow rowFirst = sheet1.createRow(0);//第一个sheet的第一行为标题
//写标题
/*for(int i=0;i<handers.length;i++){
HSSFCell cell = rowFirst.createCell(i); //获取第一行的每个单元格
sheet1.setColumnWidth(i, 4000); //设置每列的列宽
cell.setCellStyle(style); //加样式
cell.setCellValue(handers[i]); //往单元格里写数据
}*/
//设置下拉框数据
String[] arr = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK"};
int index = 30; //下拉数据从25列开始
XSSFRow row = null;
for (int r = 0; r < downRows.length; r++) {
String[] dlData = downData.get(r);//获取下拉对象
int rownum = Integer.parseInt(downRows[r]);
if (StringUtils.join(dlData).length() < 250) { //255以内的下拉
//255以内的下拉,参数分别是:作用的sheet、下拉内容数组、起始行、终止行、起始列、终止列
sheet1.addValidationData(setDataValidation(sheet1, dlData, 1, 32767, rownum, rownum)); //超过255个报错
} else { //255以上的下拉,即下拉列表元素很多的情况
//1、设置有效性
//String strFormula = "Sheet2!$A$1:$A$5000" ; //Sheet2第A1到A5000作为下拉列表来源数据
String strFormula = "导入说明!$" + arr[index] + "$1:$" + arr[index] + "$5000"; //Sheet2第A1到A5000作为下拉列表来源数据
sheet2.setColumnWidth(r, 4000); //设置每列的列宽
//设置数据有效性加载在哪个单元格上,参数分别是:从sheet2获取A1到A5000作为一个下拉的数据、起始行、终止行、起始列、终止列
sheet1.addValidationData(SetDataValidation(sheet2, strFormula, 1, 32767, rownum, rownum)); //下拉列表元素很多的情况
sheet2.setColumnHidden(index, true);
//2、生成sheet2内容
for (int j = 0; j < dlData.length; j++) {
if (index == 0) { //第1个下拉选项,直接创建行、列
row = sheet2.createRow(j); //创建数据行
sheet2.setColumnWidth(j, 4000); //设置每列的列宽
row.createCell(0).setCellValue(dlData[j]); //设置对应单元格的值
} else { //非第1个下拉选项
int rowCount = sheet2.getLastRowNum();
//System.out.println("========== LastRowNum =========" + rowCount);
if (j <= rowCount) { //前面创建过的行,直接获取行,创建列
//获取行,创建列
sheet2.getRow(j).createCell(index).setCellValue(dlData[j]); //设置对应单元格的值
} else { //未创建过的行,直接创建行、创建列
sheet2.setColumnWidth(j, 4000); //设置每列的列宽
//创建行、创建列
sheet2.createRow(j).createCell(index).setCellValue(dlData[j]); //设置对应单元格的值
}
}
}
index++;
}
}
try {
File f = new File(filePath); //写文件
//不存在则新增
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
if (!f.exists()) {
f.createNewFile();
}
FileOutputStream out = new FileOutputStream(f);
out.flush();
wb.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param @param strFormula
* @param @param firstRow 起始行
* @param @param endRow 终止行
* @param @param firstCol 起始列
* @param @param endCol 终止列
* @param @return
* @return HSSFDataValidation
* @throws
* @Title: SetDataValidation
* @Description: 下拉列表元素很多的情况 (255以上的下拉)
*/
private static XSSFDataValidation SetDataValidation(XSSFSheet sheet, String strFormula,
int firstRow, int endRow, int firstCol, int endCol) {
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
// 设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
XSSFDataValidationConstraint constraint = (XSSFDataValidationConstraint) dvHelper.createFormulaListConstraint(strFormula);
XSSFDataValidation dataValidation = (XSSFDataValidation) dvHelper.createValidation(constraint, regions);
;//new XSSFDataValidation(regions,constraint);
dataValidation.createErrorBox("Error", "Error");
dataValidation.createPromptBox("", null);
return dataValidation;
}
/**
* @param @param sheet
* @param @param textList
* @param @param firstRow
* @param @param endRow
* @param @param firstCol
* @param @param endCol
* @param @return
* @return DataValidation
* @throws
* @Title: setDataValidation
* @Description: 下拉列表元素不多的情况(255以内的下拉)
*/
private static DataValidation setDataValidation(Sheet sheet, String[] textList, int firstRow, int endRow, int firstCol, int endCol) {
DataValidationHelper helper = sheet.getDataValidationHelper();
//加载下拉列表内容
DataValidationConstraint constraint = helper.createExplicitListConstraint(textList);
//DVConstraint constraint = new DVConstraint();
constraint.setExplicitListValues(textList);
//设置数据有效性加载在哪个单元格上。四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList((short) firstRow, (short) endRow, (short) firstCol, (short) endCol);
//数据有效性对象
DataValidation data_validation = helper.createValidation(constraint, regions);
//DataValidation data_validation = new DataValidation(regions, constraint);
return data_validation;
}
/**
* @param @param url 文件路径
* @param @param fileName 文件名
* @param @param response
* @return void
* @throws
* @Title: getExcel
* @Description: 下载指定路径的Excel文件
*/
public static void getExcel(String url, String fileName, HttpServletResponse response, HttpServletRequest request) {
try {
//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
response.setContentType("multipart/form-data");
//2.设置文件头:最后一个参数是设置下载文件名
response.setHeader("Content-disposition", "attachment; filename=\""
+ encodeChineseDownloadFileName(request, fileName + ".xls") + "\"");
// response.setHeader("Content-Disposition", "attachment;filename="
// + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xls"); //中文文件名
//通过文件路径获得File对象
File file = new File(url);
FileInputStream in = new FileInputStream(file);
//3.通过response获取OutputStream对象(out)
OutputStream out = new BufferedOutputStream(response.getOutputStream());
int b = 0;
byte[] buffer = new byte[2048];
while ((b = in.read(buffer)) != -1) {
out.write(buffer, 0, b); //4.写到输出流(out)中
}
in.close();
out.flush();
out.close();
} catch (IOException e) {
System.out.println("下载Excel模板异常");
}
}
/**
* @param @param request
* @param @param pFileName
* @param @return
* @param @throws UnsupportedEncodingException
* @return String
* @throws
* @Title: encodeChineseDownloadFileName
* @Description: TODO(这里用一句话描述这个方法的作用)
*/
private static String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName)
throws UnsupportedEncodingException {
String filename = null;
String agent = request.getHeader("USER-AGENT");
//System.out.println("agent==========》"+agent);
if (null != agent) {
if (-1 != agent.indexOf("Firefox")) {//Firefox
filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8")))) + "?=";
} else if (-1 != agent.indexOf("Chrome")) {//Chrome
filename = new String(pFileName.getBytes(), "ISO8859-1");
} else {//IE7+
filename = java.net.URLEncoder.encode(pFileName, "UTF-8");
filename = StringUtils.replace(filename, "+", "%20");//替换空格
}
} else {
filename = pFileName;
}
return filename;
}
public static void main(String[] args) {
String fileName = "C:\\Users\\Administrator\\Desktop\\员工信息表.xlsx"; //模板名称
String[] handers = {"姓名", "性别", "证件类型", "证件号码", "服务结束时间", "参保地", "民族"}; //列标题
//下拉框数据
List<String[]> downData = new ArrayList();
String[] str1 = {"男", "女", "未知"};
String[] str2 = {"北京", "上海", "广州", "深圳", "武汉", "长沙", "湘潭"};
String[] str3 = {"01-汉族", "02-蒙古族", "03-回族", "04-藏族", "05-维吾尔族", "06-苗族", "07-彝族", "08-壮族", "09-布依族",
"10-朝鲜族", "11-满族", "12-侗族", "13-瑶族", "14-白族", "15-土家族", "16-哈尼族", "17-哈萨克族", "18-傣族", "19-黎族", "20-傈僳族",
"21-佤族", "22-畲族", "23-高山族", "24-拉祜族", "25-水族", "26-东乡族", "27-纳西族", "28-景颇族", "29-柯尔克孜族", "30-土族",
"31-达斡尔族", "32-仫佬族", "33-羌族", "34-布朗族", "35-撒拉族", "36-毛难族", "37-仡佬族", "38-锡伯族", "39-阿昌族", "40-普米族",
"41-塔吉克族", "42-怒族", "43-乌孜别克族", "44-俄罗斯族", "45-鄂温克族", "46-德昂族", "47-保安族", "48-裕固族", "49-京族", "50-塔塔尔族",
"51-独龙族", "52-鄂伦春族", "53-赫哲族", "54-门巴族", "55-珞巴族", "56-基诺族", "98-外国血统", "99-其他"};
downData.add(str1);
downData.add(str2);
downData.add(str3);
String[] downRows = {"1", "5", "6"}; //下拉的列序号数组(序号从0开始)
try {
ExcelTemplateUtils.createExcelTemplate(fileName, null, downData, downRows);
} catch (Exception e) {
e.printStackTrace();
System.out.println("批量导入信息异常:");
}
}
}
package pps.core.common.utils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import xstartup.base.util.XDateUtils;
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;
import java.util.logging.Logger;
/**
* Author: lixueyan
* Date: 2021-01-01
* Time: 11:09
* Description: 生成Excel并写入数据
*/
public class ExcelUtils {
private static final String XLS = "xls";
private static final String XLSX = "xlsx";
private static Logger logger = Logger.getLogger(ExcelUtils.class.getName()); // 日志打印类
/**
* 生成Excel并写入数据信息
*
* @param dataList 数据列表
* @return 写入数据后的工作簿对象
*/
public static Workbook exportData(List<Map<String, Object>> dataList, List<String> headerList) {
// 生成xlsx的Excel
Workbook workbook = new SXSSFWorkbook();
CellStyle cs = workbook.createCellStyle();
cs.setWrapText(true);
cs.setWrapText(true); //内容自动换行
cs.setAlignment(HorizontalAlignment.CENTER); //水平居中
cs.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
// 如需生成xls的Excel,请使用下面的工作簿对象,注意后续输出时文件后缀名也需更改为xls
//Workbook workbook = new HSSFWorkbook();
// 生成Sheet表,写入第一行的列头
Sheet sheet = buildDataSheet(workbook, headerList);
//构建每行的数据内容
int rowNum = 1;
for (Iterator<Map<String, Object>> it = dataList.iterator(); it.hasNext(); ) {
Map<String, Object> data = it.next();
if (data == null) {
continue;
}
//输出行数据
Row row = sheet.createRow(rowNum++);
convertDataToRow(data, row, headerList, cs);
}
return workbook;
}
/**
* 生成Excel并写入数据信息
*
* @param dataSheetList 数据列表
* @return 写入数据后的工作簿对象
*/
public static void exportData(String filePath, InputStream inputStream, List<List<Map<String, Object>>> dataSheetList, List<String> headerList, Map<String, Integer> headerHiddenList, Boolean isAuto, Map<String, Integer> headerAutoList, List<String> sheetNames) throws IOException {
// 生成xlsx的Excel
//Workbook workbook = new SXSSFWorkbook();
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
CellStyle cs = workbook.createCellStyle();
XSSFFont whiteFont = workbook.createFont();
cs.setWrapText(true); //内容自动换行
cs.setAlignment(HorizontalAlignment.CENTER); //水平居中
cs.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
whiteFont.setFontHeightInPoints((short) 9);//大小
cs.setFont(whiteFont);
//创建多个sheet页
Sheet sheet0 = workbook.getSheetAt(0);
short lastCellNum = sheet0.getRow(0).getLastCellNum();
if (lastCellNum < headerList.size()) {
headerList = headerList.subList(0, lastCellNum);
}
workbook.setSheetName(0, sheetNames.get(0));
for (int i = 1; i < sheetNames.size(); i++) {
workbook.cloneSheet(0, sheetNames.get(i));
}
Integer index = 0;
for (Iterator<List<Map<String, Object>>> sheetIt = dataSheetList.iterator(); sheetIt.hasNext(); ) {
Sheet sheet = workbook.getSheetAt(index++);
//构建每行的数据内容
int rowNum = 1;
for (Iterator<Map<String, Object>> it = sheetIt.next().iterator(); it.hasNext(); ) {
Map<String, Object> data = it.next();
if (data == null) {
continue;
}
//输出行数据
Row row = sheet.createRow(rowNum++);
convertDataToRow(data, row, headerList, cs);
}
//根据headerList表头,判断需要隐藏的列
// sheet.autoSizeColumn(rowNum);
// int colwidth = sheet.getColumnWidth(rowNum) * 2;
// if(colwidth < 255 * 256){
// sheet.setColumnWidth(rowNum , colwidth < 3000 ? 3000 : colwidth);
// }else
// sheet.setColumnWidth(rowNum , 6000);
headerList.forEach(header -> {
if (null != headerHiddenList.get(header)) {
sheet.setColumnHidden(headerHiddenList.get(header), true);
}
if (isAuto && null != headerAutoList.get(header)) {
sheet.autoSizeColumn(headerAutoList.get(header));
}
});
}
FileOutputStream out = null;
try {
File f = new File(filePath); //写文件
//不存在则新增
if (!f.getParentFile().exists()) {
f.getParentFile().mkdirs();
}
if (!f.exists()) {
f.createNewFile();
}
out = new FileOutputStream(f);
out.flush();
workbook.write(out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 生成sheet表,并写入第一行数据(列头)
*
* @param workbook 工作簿对象
* @param headerList
* @return 已经写入列头的Sheet
*/
private static Sheet buildDataSheet(Workbook workbook, List<String> headerList) {
Sheet sheet = workbook.createSheet();
// 设置列头宽度
for (int i = 0; i < headerList.size(); i++) {
sheet.setColumnWidth(i, 4000);
}
// 设置默认行高
sheet.setDefaultRowHeight((short) 400);
// 构建头单元格样式
CellStyle cellStyle = buildHeadCellStyle(sheet.getWorkbook());
// 写入第一行各列的数据
Row head = sheet.createRow(0);
for (int i = 0; i < headerList.size(); i++) {
Cell cell = head.createCell(i);
cell.setCellValue(headerList.get(i));
cell.setCellStyle(cellStyle);
}
return sheet;
}
/**
* 设置第一行列头的样式
*
* @param workbook 工作簿对象
* @return 单元格样式对象
*/
private static CellStyle buildHeadCellStyle(Workbook workbook) {
CellStyle style = workbook.createCellStyle();
//对齐方式设置
style.setAlignment(HorizontalAlignment.CENTER);
//边框颜色和宽度设置
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 下边框
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 左边框
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 右边框
style.setBorderTop(BorderStyle.THIN);
style.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 上边框
//设置背景颜色
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//粗体字设置
Font font = workbook.createFont();
font.setBold(true);
style.setFont(font);
return style;
}
/**
* 将数据转换成行
*
* @param data 源数据
* @param row 行对象
* @param headerList
* @return
*/
private static void convertDataToRow(Map<String, Object> data, Row row, List<String> headerList, CellStyle cs) {
int cellNum = 0;
Cell cell;
for (int i = 0; i < headerList.size(); i++) {
Object val = data.get(headerList.get(i));
cell = row.createCell(cellNum++);
cell.setCellValue(null == val ? "" : val + "");
cell.setCellStyle(cs);
}
}
/**
* 根据文件后缀名类型获取对应的工作簿对象
*
* @param inputStream 读取文件的输入流
* @param fileType 文件后缀名类型(xls或xlsx)
* @return 包含文件数据的工作簿对象
* @throws IOException
*/
public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException {
Workbook workbook = null;
if (fileType.equalsIgnoreCase(XLS)) {
workbook = new HSSFWorkbook(inputStream);
} else if (fileType.equalsIgnoreCase(XLSX)) {
workbook = new XSSFWorkbook(inputStream);
}
return workbook;
}
/**
* 读取Excel文件内容
*
* @param fileName 要读取的Excel文件所在路径
* @param sheetIndex 要读取的指定sheet页,为空时读取全部
* @return 读取结果列表,读取失败时返回null
*/
public static List<Map<String, Object>> readExcel(InputStream inputStream, String fileName, List<String> headerList, Integer sheetIndex) {
Workbook workbook = null;
try {
// 获取Excel后缀名
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
// 获取Excel工作簿
workbook = getWorkbook(inputStream, fileType);
// 读取excel中的数据
List<Map<String, Object>> resultDataList = parseExcel(workbook, headerList, sheetIndex);
return resultDataList;
} catch (Exception e) {
logger.warning("解析Excel失败,文件名:" + fileName + " 错误信息:" + e.getMessage());
return null;
} finally {
try {
/*if (null != workbook) {
workbook.close();
}*/
if (null != inputStream) {
inputStream.close();
}
} catch (Exception e) {
logger.warning("关闭数据流出错!错误信息:" + e.getMessage());
return null;
}
}
}
/**
* 读取Excel文件内容
*
* @param file 上传的Excel文件
* @return 读取结果列表,读取失败时返回null
*/
public static List<Map<String, Object>> readExcel(MultipartFile file, List<String> headerList, Integer sheetIndex) {
Workbook workbook = null;
try {
// 获取Excel后缀名
String fileName = file.getOriginalFilename();
if (fileName == null || fileName.isEmpty() || fileName.lastIndexOf(".") < 0) {
logger.warning("解析Excel失败,因为获取到的Excel文件名非法!");
return null;
}
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
// 获取Excel工作簿
workbook = getWorkbook(file.getInputStream(), fileType);
// 读取excel中的数据
List<Map<String, Object>> resultDataList = parseExcel(workbook, headerList, sheetIndex);
return resultDataList;
} catch (Exception e) {
logger.warning("解析Excel失败,文件名:" + file.getOriginalFilename() + " 错误信息:" + e.getMessage());
return null;
} finally {
try {
/*if (null != workbook) {
workbook.close();
}*/
} catch (Exception e) {
logger.warning("关闭数据流出错!错误信息:" + e.getMessage());
return null;
}
}
}
/**
* 解析Excel数据
*
* @param workbook Excel工作簿对象
* @param headerList
* @param sheetIndex
* @return 解析结果
*/
public static List<Map<String, Object>> parseExcel(Workbook workbook, List<String> headerList, Integer sheetIndex) {
List<Map<String, Object>> resultDataList = new ArrayList<>();
// 解析sheet
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
if (sheetIndex != null && sheetNum != sheetIndex) {
continue;
}
Sheet sheet = workbook.getSheetAt(sheetNum);
// 校验sheet是否合法
if (sheet == null) {
continue;
}
// 获取第一行数据
int firstRowNum = sheet.getFirstRowNum();
Row firstRow = sheet.getRow(firstRowNum);
if (null == firstRow) {
logger.warning("解析Excel失败,在第一行没有读取到任何数据!");
}
// 解析每一行的数据,构造数据对象
int rowStart = firstRowNum + 1;
int rowEnd = sheet.getPhysicalNumberOfRows();
for (int rowNum = rowStart; rowNum < rowEnd; rowNum++) {
Row row = sheet.getRow(rowNum);
if (null == row) {
continue;
}
Map<String, Object> resultData = convertRowToData(row, headerList);
if (null == resultData) {
logger.warning("第 " + row.getRowNum() + "行数据不合法,已忽略!");
continue;
}
resultDataList.add(resultData);
}
}
return resultDataList;
}
/**
* 将单元格内容转换为字符串
*
* @param cell
* @return
*/
private static String convertCellValueToString(Cell cell) {
if (cell == null) {
return null;
}
String returnValue = null;
switch (cell.getCellType()) {
case NUMERIC: //数字
if (XSSFDateUtil.isCellDateFormatted(cell)) {
Date d = cell.getDateCellValue();
returnValue = XDateUtils.getDateTimeString(d);
} else {
Double doubleValue = cell.getNumericCellValue();
// 格式化科学计数法,取一位整数
DecimalFormat df = new DecimalFormat("0.00000");
returnValue = df.format(doubleValue);
}
break;
case STRING: //字符串
returnValue = cell.getStringCellValue();
break;
case BOOLEAN: //布尔
Boolean booleanValue = cell.getBooleanCellValue();
returnValue = booleanValue.toString();
break;
case BLANK: // 空值
break;
case FORMULA: // 公式
returnValue = cell.getCellFormula();
break;
case ERROR: // 故障
break;
default:
break;
}
return returnValue;
}
/**
* 提取每一行中需要的数据,构造成为一个结果数据对象
* <p>
* 当该行中有单元格的数据为空或不合法时,忽略该行的数据
*
* @param row 行数据
* @param headerList
* @return 解析后的行数据对象,行数据错误时返回null
*/
private static Map<String, Object> convertRowToData(Row row, List<String> headerList) {
Map<String, Object> resultData = new HashMap<>();
Cell cell;
int cellNum = 0;
for (int i = 0; i < headerList.size(); i++) {
cell = row.getCell(cellNum++);
String name = convertCellValueToString(cell);
resultData.put(headerList.get(i), name);
}
return resultData;
}
public static void main(String[] args) {
List<String> headerList = new ArrayList<>(); //列头
headerList.add("姓名");
headerList.add("年龄");
headerList.add("居住城市");
headerList.add("职业");
/************** 读取Excel流程 ******************/
// 设定Excel文件所在路径
String excelFileName = "C:\\Users\\Administrator\\Desktop\\phone.xlsx";
InputStream inputStream = null;
try {
// 获取Excel文件
File excelFile = new File(excelFileName);
if (!excelFile.exists()) {
logger.warning("指定的Excel文件不存在!");
return;
}
inputStream = new FileInputStream(excelFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// 读取Excel文件内容
List<Map<String, Object>> readResult = ExcelUtils.readExcel(inputStream, excelFileName, headerList, null);
/************** 写入Excel流程 ******************/
// 创建需要写入的数据列表
List<Map<String, Object>> dataVOList = new ArrayList<>(2);
Map<String, Object> dataVO = new HashMap<>();
dataVO.put("name", "小明");
dataVO.put("age", 18);
dataVO.put("location", "广州");
dataVO.put("job", "大学生");
Map<String, Object> dataVO2 = new HashMap<>();
dataVO2.put("name", "小花");
dataVO2.put("age", 19);
dataVO2.put("location", "深圳");
dataVO2.put("job", "大学生");
dataVOList.add(dataVO);
dataVOList.add(dataVO2);
// 写入数据到工作簿对象内
Workbook workbook = ExcelUtils.exportData(dataVOList, headerList);
// 以文件的形式输出工作簿对象
FileOutputStream fileOut = null;
try {
String exportFilePath = excelFileName;
File exportFile = new File(exportFilePath);
if (!exportFile.exists()) {
exportFile.createNewFile();
}
fileOut = new FileOutputStream(exportFilePath);
workbook.write(fileOut);
fileOut.flush();
} catch (Exception e) {
logger.warning("输出Excel时发生错误,错误原因:" + e.getMessage());
} finally {
try {
if (null != fileOut) {
fileOut.close();
}
/*if (null != workbook) {
workbook.close();
}*/
} catch (IOException e) {
logger.warning("关闭输出流时发生错误,错误原因:" + e.getMessage());
}
}
}
}
......@@ -8,28 +8,17 @@ public class ExceptionHelper {
public static final String LINE_SEPERTOR = System.getProperty("line.separator");
public static String getExceptionLogDetail(Throwable e) {
StringWriter writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
try {
e.printStackTrace(printWriter);
printWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("EXCEPTION:").append(e.getClass().getName()).append(LINE_SEPERTOR)
.append(" Message:").append(e.getMessage()).append(LINE_SEPERTOR)
.append(" Stack:").append(writer.toString());
.append(" Stack:").append(writer);
return stringBuilder.toString();
// return "EXCEPTION:" + e.getClass().getName() + lineSepertor
// + " Message:" + e.getMessage() + lineSepertor
// + " StackTrack:" + writer.toString();
} finally {
printWriter.close();
}
}
}
package pps.core.common.utils;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.util.JxlsHelper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
/**
* Description:模板导出工具类
* date: 2020/8/20 18:56
*
* @author zjw
*/
public class ExportExcelUtils {
public static void outputFileData(HttpServletResponse response, byte[] fileBuff, String fileName) throws Exception {
response.setContentType("application/octet-stream;charset=GBK");
response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
OutputStream out = null;
try {
out = response.getOutputStream();
out.write(fileBuff);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
}
public static void outputFileData(byte[] fileBuff, String filePath) throws Exception {
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
OutputStream out = new FileOutputStream(file);
try {
out.write(fileBuff);
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
}
/**
* 根据参数生成excel文件的二进制数据
*
* @param tempPath excel模板路径
* @param params 模板中相关参数的Map
* @return 生成文件的byte数组
*/
public static byte[] genSingleExcelFileData(String tempPath, Map<String, Object> params) {
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(new File(tempPath));
} catch (FileNotFoundException e) {
System.out.println("-----" + tempPath + "文件未找到,导出空数据");
return null;
}
Context context = new Context();
if (params != null) {
for (String key : params.keySet()) {
context.putVar(key, params.get(key));
}
}
ByteArrayOutputStream buff = new ByteArrayOutputStream();
try {
JxlsHelper jxlsHelper = JxlsHelper.getInstance();
Transformer transformer = jxlsHelper.createTransformer(fileInputStream, buff);
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
Map<String, Object> funcs = new HashMap<String, Object>();
funcs.put("utils", new JxlsUtils()); //添加自定义功能
evaluator.getJexlEngine().setFunctions(funcs);
jxlsHelper.processTemplate(context, transformer);
} catch (IOException e) {
e.printStackTrace();
}
return buff.toByteArray();
}
/**
* 根据参数生成excel文件的二进制数据
*
* @param inputStream excel模板路径
* @param params 模板中相关参数的Map
* @return 生成文件的byte数组
*/
public static byte[] genSingleExcelFileData(InputStream inputStream, Map<String, Object> params) {
Context context = new Context();
if (params != null) {
for (String key : params.keySet()) {
context.putVar(key, params.get(key));
}
}
ByteArrayOutputStream buff = new ByteArrayOutputStream();
try {
JxlsHelper jxlsHelper = JxlsHelper.getInstance();
Transformer transformer = jxlsHelper.createTransformer(inputStream, buff);
JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
Map<String, Object> funcs = new HashMap<String, Object>();
funcs.put("utils", new JxlsUtils()); //添加自定义功能
evaluator.getJexlEngine().setFunctions(funcs);
jxlsHelper.processTemplate(context, transformer);
} catch (IOException e) {
e.printStackTrace();
}
return buff.toByteArray();
}
}
package pps.core.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* @author lixueyan
* @date 2022/9/29 0029 21:34
*/
public class HttpTookit {
public static final String CHARSET = "UTF-8";
public static final int DEF_CONN_TIMEOUT = 30000;
public static final int DEF_READ_TIMEOUT = 30000;
private static final CloseableHttpClient httpClient;
/**
* 忽视证书HostName
*/
public static HostnameVerifier ignoreHostnameVerifier = new HostnameVerifier() {
public boolean verify(String s, SSLSession sslsession) {
System.out.println("WARNING: Hostname is not matched for cert.");
return true;
}
};
/**
* Ignore Certification
*/
public static TrustManager ignoreCertificationTrustManger = new X509TrustManager() {
private X509Certificate[] certificates;
public void checkClientTrusted(X509Certificate certificates[],
String authType) throws CertificateException {
if (this.certificates == null) {
this.certificates = certificates;
}
}
public void checkServerTrusted(X509Certificate[] ax509certificate,
String s) throws CertificateException {
if (this.certificates == null) {
this.certificates = ax509certificate;
}
}
public X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
};
private static Logger logger = LoggerFactory.getLogger(HttpTookit.class);
static {
RequestConfig config = RequestConfig.custom().setConnectTimeout(300000).setSocketTimeout(300000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}
public static String doGet(String url, Map<String, Object> params) {
if (isHttps(url)) {
return sendSSLPostMethod(url, params);
} else {
return doGet(url, params, CHARSET);
}
}
public static String doPost(String url, Map<String, Object> params) {
return doPost(url, params, CHARSET);
}
/**
* HTTP Get 获取内容
*
* @param url 请求的url地址 ?之前的地�?
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doGet(String url, Map<String, Object> params, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
HttpGet httpGet = null;
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue() != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
logger.info("=======HttpTookit 请求url地址: " + url + "==========");
httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("httpclient请求失败");
} finally {
if (httpGet != null) httpGet.releaseConnection();
}
}
/**
* HTTP Post 获取内容
*
* @param url 请求的url地址 ?之前的地�?
* @param params 请求的参�?
* @param charset 编码格式
* @return 页面内容
*/
public static String doPost(String url, Map<String, Object> params, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, Object> entry : params.entrySet()) {
if (entry.getValue() != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
}
}
}
httpPost = new HttpPost(url);
httpPost.setHeader("serialSeq", "1212121");
httpPost.setHeader("verChl", "0.0.1");
httpPost.setHeader("sendChl", "hzsmk.test");
httpPost.setHeader("sendClient", "hellohzsmk");
httpPost.setHeader("sendDev", "121aqweq");
if (pairs != null && pairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
}
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("httpclient请求失败");
} finally {
if (httpPost != null) httpPost.releaseConnection();
}
}
/**
* 初始化http请求参数
*
* @param url
* @param method
* @return
* @throws Exception
*/
protected static HttpsURLConnection initHttps(String url, String method,
Map<String, String> headers) throws Exception {
TrustManager[] tm = {new MyX509TrustManager()};
System.setProperty("https.protocols", "TLSv1");
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new java.security.SecureRandom());
//sslContext.init(null, tm, null);
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL _url = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) _url.openConnection();
// 设置域名校验
http.setHostnameVerifier(new TrustAnyHostnameVerifier());
// 连接超时
http.setConnectTimeout(DEF_CONN_TIMEOUT);
// 读取超时 --服务器响应比较慢,增大时间
http.setReadTimeout(DEF_READ_TIMEOUT);
http.setUseCaches(false);
http.setRequestMethod(method);
/* http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");*/
if (null != headers && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
http.setRequestProperty(entry.getKey(), entry.getValue());
}
}
http.setSSLSocketFactory(ssf);
http.setDoOutput(true);
http.setDoInput(true);
try {
http.connect();
} catch (Exception ex) {
logger.info(ex.getMessage());
}
return http;
}
/**
* 功能描述: 构造请求参数
*
* @return 返回类型:
* @throws Exception
*/
public static String initParams(String url, Map<String, Object> params)
throws Exception {
if (null == params || params.isEmpty()) {
return url;
}
StringBuilder sb = new StringBuilder(url);
if (url.indexOf("?") == -1) {
sb.append("?");
}
sb.append(map2Url(params));
return sb.toString();
}
/**
* map构造url
*
* @return 返回类型:
* @throws Exception
*/
public static String map2Url(Map<String, Object> paramToMap)
throws Exception {
if (null == paramToMap || paramToMap.isEmpty()) {
return null;
}
StringBuffer url = new StringBuffer();
boolean isfist = true;
for (Entry<String, Object> entry : paramToMap.entrySet()) {
if (isfist) {
isfist = false;
} else {
url.append("&");
}
url.append(entry.getKey()).append("=");
String value = entry.getValue().toString();
if (!StringUtils.isEmpty(value)) {
url.append(URLEncoder.encode(value, CHARSET));
}
}
return url.toString();
}
/**
* 检测是否https
*
* @param url
*/
protected static boolean isHttps(String url) {
return url.startsWith("https");
}
public static String sendSSLGetMethod(String urlString) throws Exception {
String repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(urlString);
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
connection = (HttpsURLConnection) url.openConnection();
// Prepare SSL Context
TrustManager[] tm = {ignoreCertificationTrustManger};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection.setSSLSocketFactory(ssf);
if (connection.getResponseCode() != 200) {
}
is = connection.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
return bufferRes.toString();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if (null != is) {
is.close();
is = null;
}
if (null != connection) {
connection.disconnect();
}
}
return repString;
}
public static String sendSSLPostMethod(String urlString, String postData) throws Exception {
String repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(urlString);
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
// Prepare SSL Context
TrustManager[] tm = {ignoreCertificationTrustManger};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssf);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type", "text/json");
connection.setRequestProperty("content-length", String.valueOf(postData.getBytes().length));
connection.getOutputStream().write(postData.getBytes("utf-8"));
connection.getOutputStream().flush();
connection.getOutputStream().close();
if (connection.getResponseCode() != 200) {
}
is = connection.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String valueString = null;
StringBuffer bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null) {
bufferRes.append(valueString);
}
return bufferRes.toString();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if (null != is) {
is.close();
is = null;
}
if (null != connection) {
connection.disconnect();
}
}
return repString;
}
public static String sendSSLPostMethod(String urlString, Map<String, Object> params) {
String repString = null;
InputStream is = null;
HttpsURLConnection connection = null;
try {
URL url = new URL(initParams(urlString, params));
/*
* use ignore host name verifier
*/
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
// Prepare SSL Context
TrustManager[] tm = {ignoreCertificationTrustManger};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection = (HttpsURLConnection) url.openConnection();
connection.setSSLSocketFactory(ssf);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("content-type", "text/json");
//connection.setRequestProperty("content-length",String.valueOf(postData.getBytes().length));
//connection.getOutputStream().write(postData.getBytes("utf-8"));
connection.getOutputStream().flush();
connection.getOutputStream().close();
if (connection.getResponseCode() != 200) {
}
is = connection.getInputStream();
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
} finally {
if (null != is) {
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
is = null;
}
if (null != connection) {
connection.disconnect();
}
}
return repString;
}
/**
* https 域名校验
*/
public static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;// 直接返回true
}
}
public static class MyX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
}
package pps.core.common.utils;
/**
* @Description 雪花算法
*/
public class IdWorker {
private final long twepoch = 1288834974657L;
private final long workerIdBits = 5L;
private final long datacenterIdBits = 5L;
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final long sequenceBits = 12L;
private final long workerIdShift = sequenceBits;
private final long datacenterIdShift = sequenceBits + workerIdBits;
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
private long workerId;
private long datacenterId;
private long sequence = 0L;
private long lastTimestamp = -1L;
public IdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
public static void main(String[] args) {
IdWorker idWorker = new IdWorker(0, 0);
for (int i = 0; i < 100; i++) {
long id = idWorker.nextId();
System.out.println(id);
}
}
/**
* 获得下一个ID (该方法是线程安全的)
*
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
//如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
//如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
//如果毫秒相同,则从0递增生成序列号
sequence = (sequence + 1) & sequenceMask;
//毫秒内序列溢出
if (sequence == 0) {
//阻塞到下一个毫秒,获得新的时间戳
timestamp = tilNextMillis(lastTimestamp);
}
}
//时间戳改变,毫秒内序列重置
else {
sequence = 0L;
}
//上次生成ID的时间截
lastTimestamp = timestamp;
//移位并通过或运算拼到一起组成64位的ID
return ((timestamp - twepoch) << timestampLeftShift) //
| (workerId << workerIdShift) //
| sequence;
}
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
protected long timeGen() {
return System.currentTimeMillis();
}
}
\ No newline at end of file
package pps.core.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import java.util.List;
public class ImportExcelUtils {
/**
* 判断Excel当前行是否为空
*
* @param row
* @return
*/
public static boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != CellType.BLANK)
return false;
}
return true;
}
/**
* 数据非空校验
* 规则:titles 中 含有 * 的 会进行非空校验
*
* @param row
* @param titles
* @return
*/
public static String checkData(Row row, List<String> titles) {
DataFormatter formatter = new DataFormatter();
for (int i = 0; i < titles.size(); i++) {
Cell cell = row.getCell(i);
if (titles.get(i).startsWith("*") && StringUtils.isBlank(formatter.formatCellValue(cell))) {
String msg = String.format("第%s行 %s 不能为空", (i + 1), titles.get(i).replace("*", ""));
return msg;
}
}
return null;
}
}
package pps.core.common.utils;
import pps.core.common.enums.TaskPlanTaskAffectDic;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Description:
* date: 2021/3/31 16:15
*
* @author zhujiangwei
*/
public class JxlsUtils {
public static void main(String[] args) {
String as = "ss";
System.out.println(as);
}
public String dateFormat(Date date) {
return this.dateFormat(date, "yyyy-MM-dd");
}
public String dateFormat(Date date, String pattern) {
if (date == null) {
return "";
}
try {
SimpleDateFormat dateFmt = new SimpleDateFormat(pattern);
return dateFmt.format(date);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public double bigDecimalFormat(Object data) {
return bigDecimalFormat(data, 2);
}
public double bigDecimalFormat(Object data, int num) {
if (data == null) {
return 0d;
}
try {
if (data instanceof BigDecimal) {
return BigDecimalUtil.parseBigDecimal(data, num).doubleValue();
} else if (data instanceof String) {
return BigDecimalUtil.parseBigDecimal(new BigDecimal((String) data), num).doubleValue();
} else {
return BigDecimalUtil.parseBigDecimal(new BigDecimal(data.toString()), num).doubleValue();
}
} catch (Exception e) {
e.printStackTrace();
}
return 0d;
}
public String enumFormat(Integer subValue, Integer parentValue) {
if (subValue == null) {
return "未知";
}
TaskPlanTaskAffectDic bySubValue = TaskPlanTaskAffectDic.findBySubValue(parentValue, subValue);
return bySubValue.getDesc();
}
}
package pps.core.common.utils;
import java.security.MessageDigest;
/**
* @author lixueyan
* @date 2022/11/11 0011 16:11
*/
public class MD5Util {
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) {
System.out.println("MD5 Error..." + e.getMessage());
}
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) {
System.out.println("not supported charset..." + e.getMessage());
return s;
}
}
/**
* 对密码按照用户名,密码,盐进行加密
*
* @param username 用户名
* @param password 密码
* @param salt 盐
* @return
*/
public static String encryptPassword(String username, String password, String salt) {
return MD5Util.hash(username + password + salt);
}
/**
* 对密码按照密码,盐进行加密
*
* @param password 密码
* @param salt 盐
* @return
*/
public static String encryptPassword(String password, String salt) {
return MD5Util.hash(password + salt);
}
/**
* 对密码按照密码,盐进行加密
*
* @param password 密码
* @return
*/
public static String encryptPassword(String password) {
return MD5Util.hash(password);
}
}
package pps.core.common.utils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import xstartup.base.util.XDateUtils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author lixueyan
* @date 2022/8/9 0009 15:38
*/
public class MapUtil {
private static Map<Class, List<Method>> classMethodMap = new ConcurrentHashMap<Class, List<Method>>();
private static Map<Class<?>, Map<String, Method>> getMethods = new HashMap<Class<?>, Map<String, Method>>();
public static Map<String, Object> objectToMapObject(Object bean) {
Map<String, Object> map = new HashMap<String, Object>();
Map<String, Method> fields = recursiveGetMethodMap(bean);
for (String fieldName : fields.keySet()) {
Method method = fields.get(fieldName);
if (method == null) continue;
JsonIgnore jsonIgnore = method.getAnnotation(JsonIgnore.class);
if (jsonIgnore != null)
continue;
Object value = invokeMethod(bean, method);
Class<?> returnType = method.getReturnType();
if (returnType != null && returnType == Date.class && value != null) {
map.put(fieldName, XDateUtils.getDateTimeString((Date) value));
} else {
map.put(fieldName, value);
}
}
return map;
}
public static Map<String, Object> objectToMapNotContainNull(Object bean) {
Map<String, Object> map = objectToMapObject(bean);
Map<String, Object> mapResult = new HashMap<String, Object>();
for (String key : map.keySet()) {
if (map.get(key) != null) {
mapResult.put(key, map.get(key));
}
}
return mapResult;
}
private static Map<String, Method> recursiveGetMethodMap(Object obj) {
return recursiveGetMethodMap(obj.getClass());
}
private static Object invokeMethod(Object obj, Method method, Object... args) {
if (method == null)
return null;
try {
return method.invoke(obj, args);
} catch (Exception e) {
}
return null;
}
private static Map<String, Method> recursiveGetMethodMap(Class<?> _class) {
Map<String, Method> methodMap = getMethods.get(_class);
if (methodMap == null) {
synchronized (getMethods) {
if ((methodMap = getMethods.get(_class)) == null) {
methodMap = new HashMap<String, Method>();
List<Method> methodList = getDeclaredMethods(_class);
for (Method method : methodList) {
String methodName = method.getName();
int modifiers = method.getModifiers();
if (!Modifier.isPublic(modifiers))
continue;
if (Modifier.isStatic(modifiers))
continue;
if (method.getParameterCount() != 0)
continue;
if (method.getDeclaringClass() == Object.class)
continue;
if (methodName.startsWith("get") && methodName.length() > 3) {
String propertyName = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4, methodName.length());
methodMap.put(propertyName, method);
}
}
getMethods.put(_class, methodMap);
}
}
}
return methodMap;
}
private static List<Method> getDeclaredMethods(Class<?> clazz) {
if (classMethodMap.containsKey(clazz))
return classMethodMap.get(clazz);
synchronized (classMethodMap) {
if (classMethodMap.containsKey(clazz))
return classMethodMap.get(clazz);
List<Method> methodList = Arrays.asList(clazz.getMethods());
classMethodMap.put(clazz, methodList);
return methodList;
}
}
public static <T> T mapToObj(Map<String, Object> map, Class<T> clz) throws Exception {
Object obj = clz.newInstance();
Field[] declaredFields = obj.getClass().getDeclaredFields();
for (Field field : declaredFields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
field.set(obj, objToValue(map.get(field.getName()), field.getType()));
}
return (T) obj;
}
public static <T> List<T> mapToList(List<Map<String, Object>> mapList, Class<T> clz) throws Exception {
List<T> list = new ArrayList<>();
for (Map<String, Object> map : mapList) {
list.add((T) mapToObj(map, clz));
}
return list;
}
public static Object objToValue(Object o, Class c) {
if (o == null || StringUtils.isBlank(String.valueOf(o))) {
if (c == String.class) {
return o;
} else {
return null;
}
}
if (c == Integer.class) {
if (o instanceof Long) {
return o;
}
return Integer.parseInt(String.valueOf(o));
} else if (c == Float.class) {
return Float.parseFloat(String.valueOf(o));
} else if (c == Double.class) {
return Double.parseDouble(String.valueOf(o));
} else if (c == BigDecimal.class) {
return new BigDecimal(String.valueOf(o));
} else if (c == Boolean.class) {
if (o != null) {
if ((Boolean.parseBoolean(String.valueOf(o))) == true)
return 1;
else
return 0;
} else {
return null;
}
} else if (c == Date.class) {
return XDateUtils.parse(String.valueOf(o));
} else {
return o;
}
}
}
package pps.core.common.utils;
public class NumUtils {
public static void main(String[] args) {
System.out.println(digitUppercase(11120.1));
}
/**
* 数字金额大写转换
*
* @param n 数字
* @return 中文大写数字
*/
public static String digitUppercase(double n) {
//String[] fraction = {"角", "分"};
String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
String[][] unit = {{"", "万", "亿"}, {"", "拾", "佰", "仟"}};
String head = n < 0 ? "负" : "";
n = Math.abs(n);
String s = "";
// for (int i = 0; i < fraction.length; i++) {
// s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
// }
if (s.length() < 1) {
//s = "整";
}
int integerPart = (int) Math.floor(n);
for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
String p = "";
for (int j = 0; j < unit[1].length && n > 0; j++) {
p = digit[integerPart % 10] + unit[1][j] + p;
integerPart = integerPart / 10;
}
s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
}
return head + s.replaceAll("(零.)*零", "").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零整");
}
public static String getCode() {
return String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
}
}
package pps.core.common.utils;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SqlFilter {
public static final List<String> BAD_KEYWORDS = Arrays.asList(
"select", "update", "delete", "insert", "truncate"
, "and", "or", "char", "into", "substr"
, "ascii", "declare", "exec", "count", "master"
, "drop", "execute", "table", "sitename", "xp_cmdshell"
, "like", "from", "grant", "use", "group_concat"
, "column_name", "information_schema.columns", "table_schema"
, "union", "where", "order", "by", "add"
, "all", "alter", "any", "as", "create"
, "in", "join", "inner", "not", "set"
, "--", "--;", ";--");
public static final Pattern PATTERN_WHITESPACE = Pattern.compile("\\s+");
public static final Splitter SPLITTER_WHITESPACE = Splitter.on(PATTERN_WHITESPACE);
public static final Joiner JOINER_WHITESPACE = Joiner.on(" ");
public static final Pattern BAD_FORM_PATTERN_KEYWORDS = Pattern.compile("^(" + String.join("|", BAD_KEYWORDS) + ")$", Pattern.CASE_INSENSITIVE);
public static final String BAD_FORM_PATTERN_STR = "'|\\*|/|\\\\|--.*";//过滤掉的sql关键字,特殊字符前面需要加\\进行转义
public static final Pattern BAD_FORM_PATTERN = Pattern.compile(BAD_FORM_PATTERN_STR, Pattern.CASE_INSENSITIVE);
public static final String filterValue(String original) {
if (Strings.isNullOrEmpty(original)) {
return original;
}
original = original.trim();
if (Strings.isNullOrEmpty(original)) {
return original;
}
if (!PATTERN_WHITESPACE.matcher(original).find()) {
//没有空格
return filterValueNoSpace(original);
}
List<String> keywords = SPLITTER_WHITESPACE.splitToList(original);
List<String> fixedKeywords = new ArrayList<String>(keywords.size());
keywords.forEach(keyword -> {
String fixed = filterValueNoSpace(keyword);
if (!Strings.isNullOrEmpty(fixed)) {
fixedKeywords.add(fixed);
}
});
if (fixedKeywords.isEmpty()) {
return "";
}
return JOINER_WHITESPACE.join(fixedKeywords);
}
private static String filterValueNoSpace(String original) {
//关键字查询
Matcher matcher = BAD_FORM_PATTERN_KEYWORDS.matcher(original);
if (matcher.find()) {
return "";
}
Matcher matcher1 = BAD_FORM_PATTERN.matcher(original);
if (matcher1.find()) {
original = matcher1.replaceAll("");
}
return original;
}
}
package pps.core.common.utils;
import java.math.BigDecimal;
/**
* 到大小数函数
*
* @author ZWT
* @date 2024/06/03
*/
@FunctionalInterface
public interface ToBigDecimalFunction<T> {
/**
* 应用为大小数
*
* @param value 价值
* @return {@link BigDecimal }
*/
BigDecimal applyAsBigDecimal(T value);
}
\ No newline at end of file
package pps.core.common.utils;
import org.apache.poi.ss.usermodel.DateUtil;
import java.util.Calendar;
/**
* @author lixueyan
* @date 2023/2/9 0009 13:41
*/
public class XSSFDateUtil extends DateUtil {
protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
return DateUtil.absoluteDay(cal, use1904windowing);
}
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment