Commit 8a198bc3 authored by 黄福新's avatar 黄福新

[add] 新增工具类

parent fdcc0c76
...@@ -770,8 +770,8 @@ public final class Constants { ...@@ -770,8 +770,8 @@ public final class Constants {
public static final String BPMN_CANDIDATES = "candidates"; public static final String BPMN_CANDIDATES = "candidates";
public static final String BPMN_COMPLETION_CONDITION = "completionCondition"; public static final String BPMN_COMPLETION_CONDITION = "completionCondition";
public static final String BPMN_COMPLETION_CONDITION_CONTENT = "${userTaskHandler.dealComplete(execution)}"; public static final String BPMN_COMPLETION_CONDITION_CONTENT = "${userTaskHandler.dealComplete(execution)}";
public static final String BPMN_PROCESS_EXECUTION_LISTENER_NAME = "com.wanji.design.engine.operate.impl.ProcessExecutionListener"; public static final String BPMN_PROCESS_EXECUTION_LISTENER_NAME = "net.wanji.design.engine.operate.impl.ProcessExecutionListener";
public static final String BPMN_ACTIVITI_CLASS_NAME = "com.wanji.design.engine.operate.impl.AutoNodeServiceTask"; public static final String BPMN_ACTIVITI_CLASS_NAME = "net.wanji.design.engine.operate.impl.AutoNodeServiceTask";
/*bpmn20.xml节点定义 end*/ /*bpmn20.xml节点定义 end*/
......
package net.wanji.common.utils;
import org.locationtech.jts.geom.Geometry;
import org.geotools.geojson.geom.GeometryJSON;
import org.locationtech.jts.geom.*;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.util.List;
public class FittingFunctionUntils {
private static final GeometryFactory geometryFactory = new GeometryFactory();
public static LineString calculateLineString(String wkt, int precision)
{
WKTReader reader = new WKTReader(geometryFactory);
LineString line = null;
try {
line = (LineString)reader.read(wkt);
} catch (ParseException e) {
e.printStackTrace();
}
//LineString lineByWKT = GeometryUtils.createLineByWKT(wkt);
return calculateLineString(line,precision);
}
public static LineString calculateLineString(LineString lineString, int precision) {
double[][] points = new double[lineString.getNumPoints()][2];
Coordinate[] coordinates = lineString.getCoordinates();
for (int i = 0; i < coordinates.length; i++) {
Coordinate coordinate = coordinates[i];
points[i][0] = coordinate.x;
points[i][1] = coordinate.y;
}
double[][] calculate = calculate(points, precision);
Coordinate[] coordinatesNew = new Coordinate[calculate.length + 1];
for (int i = 0; i < calculate.length; i++) {
coordinatesNew[i] = new Coordinate(calculate[i][0], calculate[i][1]);
}
coordinatesNew[calculate.length] = lineString.getEndPoint().getCoordinate();
return geometryFactory.createLineString(coordinatesNew);
}
public static double[][] calculate(List<String> list, int precision) {
double[][] points = new double[list.size()][2];
for (int i = 0; i < list.size(); i++) {
String point = (String)list.get(i);
String[] split = point.split(",");
points[i][0] = Double.parseDouble(split[0]);
points[i][1] = Double.parseDouble(split[1]);
}
return calculate(points, precision);
}
public static double[][] calculate(double[][] poss, int precision)
{
int dimersion = poss[0].length;
int number = poss.length;
if ((number < 2) || (dimersion < 2)) {
return (double[][])null;
}
double[][] result = new double[precision][dimersion];
int[] mi = new int[number];
int tmp43_42 = 1; mi[1] = tmp43_42; mi[0] = tmp43_42;
for (int i = 3; i <= number; i++)
{
int[] t = new int[i - 1];
for (int j = 0; j < t.length; j++)
t[j] = mi[j];
int tmp100_99 = 1; mi[(i - 1)] = tmp100_99; mi[0] = tmp100_99;
for (int j = 0; j < i - 2; j++) {
mi[(j + 1)] = (t[j] + t[(j + 1)]);
}
}
for (int i = 0; i < precision; i++) {
double t = new BigDecimal(i + "").divide(new BigDecimal(precision + ""), 80, 0).doubleValue();
for (int j = 0; j < dimersion; j++) {
double temp = 0.0D;
for (int k = 0; k < number; k++) {
temp += Math.pow(1.0D - t, number - k - 1) * poss[k][j] * Math.pow(t, k) * mi[k];
}
result[i][j] = temp;
}
}
return result;
}
public static void main(String []args){
LineString lineString = FittingFunctionUntils.calculateLineString("LINESTRING(118.700421223022 37.4278045360367,118.700798456007 37.4278045360367,118.700798456007 37.4276183268811)", 10);
String json = null;
try {
org.locationtech.jts.io.WKTReader reader = new org.locationtech.jts.io.WKTReader();
Geometry geometry = reader.read(lineString.toText());
StringWriter writer = new StringWriter();
GeometryJSON g = new GeometryJSON(20);
g.write(geometry, writer);
json = writer.toString();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println( json);
}
}
package net.wanji.common.utils.cookie;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @Description:
* @Author mapabc
* @Date 2020/6/23 14:35
*/
public class CookieUtil {
private CookieUtil() {
}
/**
* 添加cookie
*
* @param response
* @param name
* @param value
* @param maxAge
*/
public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
if (maxAge >= 0) {
cookie.setMaxAge(maxAge);
}
response.addCookie(cookie);
}
/**
* 删除cookie
*
* @param response
* @param name
*/
public static void removeCookie(HttpServletResponse response, String name) {
Cookie uid = new Cookie(name, null);
uid.setPath("/");
uid.setMaxAge(0);
response.addCookie(uid);
}
/**
* 获取cookie值
*
* @param request
* @return
*/
public static String getUid(HttpServletRequest request, String cookieName) {
Cookie cookies[] = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(cookieName)) {
return cookie.getValue();
}
}
}
return null;
}
}
package net.wanji.common.utils.file;
import com.github.tobato.fastdfs.domain.fdfs.FileInfo;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.fdfs.ThumbImageConfig;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.io.*;
/**
* 使用FastDFS访问和存储文件
*
* @author gl.dong
* @date 2020/5/26
*/
@Slf4j
@Component("fastDfsUtils")
@ConditionalOnProperty(value = "fdfs.groupName") //判断fastdfs的配置是否存在
public class FastDfsUtils {
@Autowired
private FastFileStorageClient storageClient;
@Autowired
private ThumbImageConfig thumbImageConfig;
@Value("${fdfs.groupName}")
private String groupName;
@Value("${fdfs.serverUrl}")
public String serverUrl;
@Value("${fdfs.fileDownUrl}")
public String fileDownUrl;
/**
* 判断文件或目录是否存在
*
* @param filePath
* @return
* @throws Exception
*/
public boolean exists(String filePath) throws Exception {
if (filePath.contains(groupName)) {
filePath = filePath.replace(groupName + "/", "");
}
FileInfo fileInfo;
try {
fileInfo = storageClient.queryFileInfo(groupName, filePath);
} catch (Exception e) {
return false;
}
return fileInfo != null;
}
/**
* 删除文件
*
* @param fullRemoteFileName
* @return
* @throws Exception
*/
public boolean delFile(String fullRemoteFileName) throws Exception {
boolean flag = false;
try {
if (fullRemoteFileName.contains(groupName)) {
fullRemoteFileName = fullRemoteFileName.replace(groupName + "/", "");
}
if (exists(fullRemoteFileName)) {
//删除文件服务器的文件信息
storageClient.deleteFile(groupName, fullRemoteFileName);
flag = true;
}
} catch (Exception e) {
throw new Exception("deleted remote exception by fileName(" + fullRemoteFileName + ")", e);
}
return flag;
}
/**
* @return boolean
* @throws
* @Author mapabc7
* @Description 删除本地文件
* @Date 9:26 2020/6/1
* @Param [fullRemoteFileName]
*/
public boolean delLocalFile(String fullRemoteFileName) throws Exception {
try {
if (!fullRemoteFileName.contains(fileDownUrl)) {
fullRemoteFileName = fileDownUrl + "/" + fullRemoteFileName;
}
File file = new File(fullRemoteFileName);
// 是文件
if (file.exists() && file.isFile()) {
file.delete();
} else {
// 是文件夹
delTempChild(file);
}
return true;
} catch (Exception e) {
throw new Exception("deleted local file exception by fileName(" + fullRemoteFileName + ")," + e.getMessage(), e);
}
}
private void delTempChild(File file) {
if (file.isDirectory()) {
String[] children = file.list();//获取文件夹下所有子文件夹
//递归删除目录中的子目录下
if (children != null) {
for (String child : children) {
delTempChild(new File(file, child));
}
}
} else {
// 目录空了,进行删除
file.delete();
}
}
/**
* 将数据流写入到远程文件系统中
*
* @return
* @throws Exception
*/
public String writeInputStreamToFile(File file) throws Exception {
try (FileInputStream in = new FileInputStream(file)) {
StorePath storePath = storageClient.uploadFile(in, file.length(), FilenameUtils.getExtension(file.getName()), null);
return storePath.getFullPath();
} catch (Exception e) {
throw new Exception("upload remote path exception," + e.getMessage(), e);
}
}
/**
* 将数据流写入到远程文件系统中
*
* @return
* @throws Exception
*/
public String writeInputStreamToFile(InputStream inputStream, long fileSize, String remoteFilename) throws Exception {
try {
StorePath storePath = storageClient.uploadFile(inputStream, fileSize, FilenameUtils.getExtension(remoteFilename), null);
return storePath.getFullPath();
} catch (Exception e) {
throw new Exception("upload remote path exception," + e.getMessage(), e);
} finally {
inputStream.close();
}
}
public boolean downloadToLocal(String localFilePath, String remoteDir) {
File file = new File(localFilePath);
return downloadToLocal(file, remoteDir);
}
public boolean downloadToLocal(File file, String remoteDir) {
// 先删 后下载
FileUtil.delFile(file);
byte[] bytes = null;
boolean flag = false;
OutputStream outputStream = null;
try {
if (remoteDir.contains(groupName)) {
remoteDir = remoteDir.replace(groupName + "/", "");
}
if (storageClient.queryFileInfo(groupName, remoteDir) != null) {
bytes = storageClient.downloadFile(groupName, remoteDir, new DownloadByteArray());
}
// 创建目录
FileUtil.newFolder(file.getParentFile());
outputStream = new FileOutputStream(file);
if (bytes == null || bytes.length <= 0) {
log.error("download remote(" + remoteDir + ") to local exception, 文件系统无此文件");
return false;
}
outputStream.write(bytes);
flag = true;
} catch (Exception e) {
log.error("download remote:{} to local:{} path exception error:{}", remoteDir, file.getPath(), e.getMessage());
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
log.error("文件流关闭失败:{}", e.getMessage());
}
}
}
return flag;
}
/**
* 根据当前图片地址返回缩略图图片地址
*
* @param url 当前图片地址
* @return 缩略图图片地址
* @throws Exception
* @Author gl.dong
*/
public String getThumbFromUrl(String url) throws Exception {
String thumbUrl = "";
if (url.contains(groupName)) {
url = url.replace(groupName + "/", "");
}
try {
if (exists(url)) {
thumbUrl = thumbImageConfig.getThumbImagePath(url);
}
} catch (Exception e) {
throw new Exception(" get thumb url fail", e);
}
return thumbUrl;
}
/**
* 将流转为字节
*
* @param inStream
* @return
* @throws Exception
*/
public static byte[] inputStreamToBytes(InputStream inStream) throws Exception {
byte[] bytes = null;
try (ByteArrayOutputStream swapStream = new ByteArrayOutputStream()) {
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
bytes = swapStream.toByteArray();
} catch (Exception e) {
log.error("将流转为字节失败", e);
throw new Exception("将流转为字节失败", e);
}
return bytes;
}
/**
* 传入文件路径 将文件转为字节
*
* @param filePath
* @return
* @throws Exception
*/
public byte[] readFileToBytes(String filePath) throws Exception {
byte[] bytes = null;
String group = "group1";
try {
if (storageClient.queryFileInfo(group, filePath) != null) {
bytes = storageClient.downloadFile(group, filePath, new DownloadByteArray());
}
} catch (Exception e) {
throw new Exception("download remote(" + filePath + ") path exception", e);
}
return bytes;
}
/**
* 将字节流数据写入到远程文件系统中
*
* @param bytes
* @return 远程文件路径
* @throws Exception
*/
public String writeByteArrayToFile(byte[] bytes, String remoteDir, String remoteName) throws Exception {
InputStream in = byteToInputStream(bytes);
return writeInputStreamToFile(in, bytes.length, remoteName);
}
/**
* 字节转换InputStream
*
* @param in
* @return
*/
public static InputStream byteToInputStream(byte[] in) throws Exception {
ByteArrayInputStream is = new ByteArrayInputStream(in);
return is;
}
public static void main(String[] args) {
String a = "http://219.142.87.76:8080/" + "group1/M00/00/19/wKgFwF7QpByAGClYAAA6xbqsNdg30.docx";
String b = a.replace("http://219.142.87.76:8080/", "");
System.out.println(a.lastIndexOf(")"));
System.out.println(a.substring(a.lastIndexOf(".")));
}
}
package net.wanji.common.utils.geo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.toilelibre.libe.curl.Curl.curl;
import static org.toilelibre.libe.curl.Curl.$;
/**
* GeoWebCache帮助类
* @author guoliang.dong@mapabc.com
*/
@Slf4j
public class GeoWebCacheUtils {
private String geoUrl;
private String geoUsername;
private String geoPassword;
private static GeoWebCacheUtils geoWebCacheUtils = null;
public static GeoWebCacheUtils getGeoServerRESTManager(String url,String username,String password) {
if (geoWebCacheUtils == null) {
geoWebCacheUtils = new GeoWebCacheUtils(url,username,password);
}
return geoWebCacheUtils;
}
public GeoWebCacheUtils(String url,String username,String password){
geoUrl=url;
geoUsername=username;
geoPassword=password;
}
/**
* 新增工作空间
*
* @param workspace 工作空间名
* @return boolean
*/
public boolean addWorkspace(String workspace) {
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -XPOST -H \"Content-type: text/xml\"\n" +
" -d \"<workspace><name>" + workspace + "</name></workspace>\"\n" +
" " + geoUrl + "/rest/workspaces";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==201;
}
/**
* 创建外存储geotiff
*
* @param workspace
* @param store
* @return
*/
public boolean addExternalGeotiffStore(String workspace ,String store,String fileurl){
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -XPUT -H \"Content-type: text/plain\"\n" +
" -d \"file://"+fileurl+"\"\n" +
" " + geoUrl + "/rest/workspaces/" + workspace + "/coveragestores/"+store+"/external.geotiff?configure=first&coverageName="+store;
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==201;
}
/**
* 获取geoWebCache中的图层
*
* @return Map
*/
public Map<String, Object> getLayers() {
Map<String, Object> map = new HashMap();
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " \"" + geoUrl + "/gwc/rest/layers\"";
List<String> shp = new ArrayList<>();
List<String> image = new ArrayList<>();
HttpResponse curl = curl(cmd);
HttpEntity entity = curl.getEntity();
if (entity != null) {
String result = null;
try {
result = EntityUtils.toString(entity, "UTF-8");
JSONArray jsonArray = JSONArray.parseArray(result);
for (Object o : jsonArray) {
String str = o.toString();
map.put(str,o);
}
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
/**
*
*
* @param layer
* @param zoomStart
* @param zoomStop
* @return boolean
*/
/**
* 指定图层进行切片操作
* @param layer 指定图层 shp:test
* @param type * seed (add tiles) * reseed (replace tiles) * truncate (remove tiles)
* @param srs 坐标系srid
* @param zoomStart 1 切片开始层级
* @param zoomStop 15 切片结束层级
* @return
*/
public boolean slice(String layer, String type,int srs,int zoomStart, int zoomStop,String gridSetId) {
int threadCount = 2;
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " \"" + geoUrl + "/gwc/rest/seed/"+layer+".xml\""+ " -XPOST -H \"Content-type: text/xml\" -d '<seedRequest><name>" + layer +
"</name><srs><number>"+srs+"</number></srs><zoomStart>" + zoomStart + "</zoomStart><zoomStop>" + zoomStop + "</zoomStop><format>image/png</format><type>"+type+"</type><threadCount>" + threadCount + "</threadCount><gridSetId>"+gridSetId+"</gridSetId></seedRequest>' \""
+ geoUrl + "/gwc/rest/seed/" + layer + ".xml\"";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==200;
}
/**
* 获取切片的情况
*
* @param layer 指定图层
* @return Map
*/
public Map getSliceType(String layer) {
Map map = new HashMap();
//返回所有图层切片情况 curl -u <user>:<password> -XGET http://localhost:8080/geoserver/gwc/rest/seed.json
//返回指定图层的切片情况
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -XGET " + geoUrl + "/gwc/rest/seed/" + layer + ".json";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
if (statusLine.getStatusCode()==200) {
HttpEntity entity = curl.getEntity();
try {
String result = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonArray = JSONObject.parseObject(result);
map.put("res", jsonArray.getJSONArray("long-array-array"));
} catch (IOException e) {
e.printStackTrace();
}
}
return map;
}
/**
* 停止所有正在进行的切片任务
*
* @return boolean
*/
public boolean stopAllSlice() {
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -d \"kill_all=all\" \"" + geoUrl + "/gwc/rest/seed\"";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==200;
}
/**
* 停止指定图层的切片任务
*
* @return boolean
*/
public boolean stopSliceByLayer(String layer) {
String cmd = "curl -u " + geoUsername + ":" + geoPassword + " -d \"kill_all=all\" \"" + geoUrl + "/gwc/rest/seed/" + layer + "\"";
HttpResponse curl = curl(cmd);
StatusLine statusLine = curl.getStatusLine();
return statusLine.getStatusCode()==200;
}
public static void main(String[]args){
GeoWebCacheUtils geoServerRESTManager=GeoWebCacheUtils.getGeoServerRESTManager("http://127.0.0.1:8080/geoserver","admin","geoserver");
//System.out.println(geoServerRESTManager.addWorkspace("zhangwei"));
//Map<String, Object> layers=geoServerRESTManager.getLayers();
//System.out.println("图层数:"+layers.size());
//System.out.println(layers);
System.out.println(geoServerRESTManager.slice("sf:result8","seed",4326,14,14,"My_EPSG:4326"));
//System.out.println(geoServerRESTManager.stopSliceByLayer("gisc_3f0786e36794%3Apoi"));
//System.out.println(geoServerRESTManager.getSliceType("gisc_3f0786e36794%3Apoi"));
//System.out.println(geoServerRESTManager.getSliceType("gisc_3f0786e36794%3Apoi"));
//System.out.println(geoServerRESTManager.stopAllSlice());
//System.out.println(geoServerRESTManager.addExternalGeotiffStore("sf","result8","D:/ProgramData/GeoServer/data/sf/result8/result.tif"));
}
}
package net.wanji.common.utils.licenseUtils;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class AESUtils {
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
private static final String ALGORITHM_AES = "AES";
private static final int DIGIT_AES = 128; // AES加密位数
private static final String ENCONDING_TAG = "UTF-8";
private static KeyGenerator keyGen;
private static Cipher cipher;
static boolean isInited = false;
private static void init() {
try {
/**
* 为指定算法生成一个 KeyGenerator 对象。 此类提供(对称)密钥生成器的功能。 密钥生成器是使用此类的某个 getInstance 类方法构造的。
* KeyGenerator 对象可重复使用,也就是说,在生成密钥后, 可以重复使用同一 KeyGenerator 对象来生成进一步的密钥。
* 生成密钥的方式有两种:与算法无关的方式,以及特定于算法的方式。 两者之间的惟一不同是对象的初始化: 与算法无关的初始化 所有密钥生成器都具有密钥长度 和随机源 的概念。
* 此 KeyGenerator 类中有一个 init 方法,它可采用这两个通用概念的参数。 还有一个只带 keysize 参数的 init 方法,
* 它使用具有最高优先级的提供程序的 SecureRandom 实现作为随机源 (如果安装的提供程序都不提供 SecureRandom 实现,则使用系统提供的随机源)。 此
* KeyGenerator 类还提供一个只带随机源参数的 inti 方法。 因为调用上述与算法无关的 init 方法时未指定其他参数,
* 所以由提供程序决定如何处理将与每个密钥相关的特定于算法的参数(如果有)。 特定于算法的初始化 在已经存在特定于算法的参数集的情况下, 有两个具有
* AlgorithmParameterSpec 参数的 init 方法。 其中一个方法还有一个 SecureRandom 参数, 而另一个方法将已安装的高优先级提供程序的
* SecureRandom 实现用作随机源 (或者作为系统提供的随机源,如果安装的提供程序都不提供 SecureRandom 实现)。 如果客户端没有显式地初始化
* KeyGenerator(通过调用 init 方法), 每个提供程序必须提供(和记录)默认初始化。
*/
keyGen = KeyGenerator.getInstance(ALGORITHM_AES);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 初始化此密钥生成器,使其具有确定的密钥长度。
keyGen.init(DIGIT_AES); // 128位的AES加密
try {
// 生成一个实现指定转换的 Cipher 对象。
cipher = Cipher.getInstance(ALGORITHM_STR);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
// 标识已经初始化过了的字段
isInited = true;
}
private static byte[] genKey() {
if (!isInited) {
init();
}
// 首先 生成一个密钥(SecretKey),
// 然后,通过这个秘钥,返回基本编码格式的密钥,如果此密钥不支持编码,则返回 null。
return keyGen.generateKey().getEncoded();
}
private static byte[] encrypt(byte[] content, byte[] keyBytes) {
byte[] encryptedText = null;
if (!isInited) {
init();
}
/**
* 类 SecretKeySpec 可以使用此类来根据一个字节数组构造一个 SecretKey, 而无须通过一个(基于 provider 的)SecretKeyFactory。
* 此类仅对能表示为一个字节数组并且没有任何与之相关联的钥参数的原始密钥有用 构造方法根据给定的字节数组构造一个密钥。 此构造方法不检查给定的字节数组是否指定了一个算法的密钥。
*/
Key key = new SecretKeySpec(keyBytes, ALGORITHM_AES);
try {
// 用密钥初始化此 cipher。
cipher.init(Cipher.ENCRYPT_MODE, key);
} catch (InvalidKeyException e) {
e.printStackTrace();
}
try {
// 按单部分操作加密或解密数据,或者结束一个多部分操作。(不知道神马意思)
encryptedText = cipher.doFinal(content);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return encryptedText;
}
private static byte[] encrypt(String content, String password) {
try {
byte[] keyStr = getKey(password);
SecretKeySpec key = new SecretKeySpec(keyStr, ALGORITHM_AES);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // algorithmStr
byte[] byteContent = content.getBytes(ENCONDING_TAG);
cipher.init(Cipher.ENCRYPT_MODE, key); // ʼ
byte[] result = cipher.doFinal(byteContent);
return result; //
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
private static byte[] decrypt(byte[] content, String password) {
try {
byte[] keyStr = getKey(password);
SecretKeySpec key = new SecretKeySpec(keyStr, ALGORITHM_AES);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // algorithmStr
cipher.init(Cipher.DECRYPT_MODE, key); // ʼ
byte[] result = cipher.doFinal(content);
return result; //
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
private static byte[] getKey(String password) {
byte[] rByte = null;
if (password != null) {
rByte = password.getBytes();
} else {
rByte = new byte[24];
}
return rByte;
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
// 注意: 这里的password(秘钥必须是16位的)
private static final String keyBytes = "vpa003icoreaims#";
/** 加密 */
public static String encode(String content, String key) {
// 加密之后的字节数组,转成16进制的字符串形式输出
return parseByte2HexStr(encrypt(content, key));
}
/** 解密 */
public static byte[] decode(String content, String key) {
// String decryptCode = null;
// 解密之前,先将输入的字符串按照16进制转成二进制的字节数组,作为待解密的内容输入
return decrypt(parseHexStr2Byte(content), key);
// try {
// decryptCode= new String(res, Constants.UTF8_ENCODING);
// } catch (UnsupportedEncodingException e) { }
// return decryptCode;
}
public static void main(String[] args) {
String content = "Y" + "," + "420FC7FC-1616-3382-0D20-664AE5A7CDD3" + "," + "20301218";
String encodeStr = encode("X,bill,2020-08-07", keyBytes);
System.out.print(encodeStr);
}
}
package net.wanji.common.utils.licenseUtils;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
/**
* 授权加密解密工具类,做成授权工具的话,主要就是用的这个类
*/
public class DESUtils {
/**
* 密钥
*/
public static final String DEFAULT_KEY = "BOTWAVEE";
public static String decrypt(String message) throws Exception {
return java.net.URLDecoder.decode(decrypt(message, DEFAULT_KEY), "utf-8");
}
/**
* 解密
* @param message 加密后的内容
* @param key 密钥
* @return
* @throws Exception
*/
public static String decrypt(String message, String key) throws Exception {
byte[] bytesrc = convertHexString(message);
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] retByte = cipher.doFinal(bytesrc);
return new String(retByte);
}
public static String encrypt(String message) throws Exception{
return toHexString(encrypt(message, DEFAULT_KEY)).toUpperCase();
}
/**
* 加密
*
* @param message
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(String message, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
return cipher.doFinal(message.getBytes("UTF-8"));
}
public static byte[] convertHexString(String ss) {
byte digest[] = new byte[ss.length() / 2];
for (int i = 0; i < digest.length; i++) {
String byteString = ss.substring(2 * i, 2 * i + 2);
int byteValue = Integer.parseInt(byteString, 16);
digest[i] = (byte) byteValue;
}
return digest;
}
public static void main(String[] args) throws Exception {
String key = "BOTWAVEE";
String jiami = "znxd,000000,7005-459C,2018-07-27,2022-02-02";
System.out.println("加密数据:" + jiami);
// Byte a = encrypt(jiami,key);
System.out.println("加密后的数据为:" + encrypt(jiami,key));
String b =decrypt(new String(encrypt(jiami,key)));
System.out.println("解密后的数据:" + b);
}
public static String toHexString(byte b[]) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < b.length; i++) {
String plainText = Integer.toHexString(0xff & b[i]);
if (plainText.length() < 2)
plainText = "0" + plainText;
hexString.append(plainText);
}
return hexString.toString();
}
}
package net.wanji.common.utils.licenseUtils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/** Created by JAVA on 2018/7/24. */
public class DateUtils {
public static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
public static boolean authorize_date(String date) {
TimeZone tz = TimeZone.getTimeZone("ETC/GMT-8");
TimeZone.setDefault(tz);
String currentTime = DateUtils.formatter.format(new Date());
if (compare_date(currentTime, date) >= 0) {
return true;
}
return false;
}
public static int compare_date(String date1, String date2) {
DateFormat df = new SimpleDateFormat("yyyyMMdd");
try {
Date dt1 = df.parse(date1);
Date dt2 = df.parse(date2);
if (dt1.getTime() < dt2.getTime()) {
// System.out.println("dt1 在dt2前");
return 1;
} else if (dt1.getTime() > dt2.getTime()) {
// System.out.println("dt1在dt2后");
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static void main(String[] args) {
System.out.println(authorize_date("20200807"));;
}
}
package net.wanji.common.utils.licenseUtils;
import java.io.*;
/**
* Created by JAVA on 2018/7/24.
*/
public class EncoderFile {
// public static void main(String[] args) throws FileNotFoundException {
// File cfgFile =new File("d:/license/encoder.txt");
// if(!cfgFile.exists()){
// cfgFile.getParentFile().mkdirs();
// try {
// cfgFile.createNewFile();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// String string = "znxd,100000,PF0AQGM7,"+ DateUtils.currenttime+",2022-02-02";
// System.out.println(string);
// try {
// string = DESUtils.encrypt(string);
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// write(cfgFile,string);
//
// String line = read(cfgFile);
//
// System.out.println(line);
//
// try {
// System.out.println(DESUtils.decrypt(line));
// } catch (Exception e) {
// e.printStackTrace();
// }
//
// }
// public static void write(File cfgFile ,String write){
// File file = cfgFile; //1、建立连接
// OutputStream os = null;
// try {
// //2、选择输出流,以追加形式(在原有内容上追加) 写出文件 必须为true 否则为覆盖
// os = new FileOutputStream(file);
//// //和上一句功能一样,BufferedInputStream是增强流,加上之后能提高输出效率,建议
//// os = new BufferedOutputStream(new FileOutputStream(file,true));
//
// byte[] data = write.getBytes(); //将字符串转换为字节数组,方便下面写入
//
// os.write(data, 0, data.length); //3、写入文件
// os.flush(); //将存储在管道中的数据强制刷新出去
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// System.out.println("文件没有找到!");
// } catch (IOException e) {
// e.printStackTrace();
// System.out.println("写入文件失败!");
// }finally {
// if (os != null) {
// try {
// os.close();
// } catch (IOException e) {
// e.printStackTrace();
// System.out.println("关闭输出流失败!");
// }
// }
// }
// }
public static String read(File cfgFile ){
StringBuilder sb = new StringBuilder();
try {
// 读取字符文件
BufferedReader in = new BufferedReader(new FileReader(cfgFile));
// 为什么单独在这里加上try块而不是直接使用外边的try块?
// 需要考虑这么一种情况,如果文件没有成功打开,则finally关闭文件会出问题
try {
String s;
while ((s = in.readLine()) != null) {
sb.append(s + "\n");
}
}finally{
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
package net.wanji.common.utils.licenseUtils;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
@Slf4j
public class HardWareUtils {
//安全性考虑,构造方法私有化
private HardWareUtils() {}
/**
* @Description: 获取当前操作系统名称
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 17:45
**/
public static String getOSName() {
return System.getProperty("os.name").toLowerCase();
}
/**
* @Description: 判断当前操作系统
*
* @return boolean,true-unix系统,false,其他,本工具类内其他会按照windows系统处理
* @Author mapabc
* @Date 2020/7/28 17:47
**/
public static boolean isUnixOs() {
System.out.println(getOSName());
return getOSName().contains("linux")||getOSName().contains("mac")||getOSName().contains("unix");
}
/**
* @Description: 获取主板序列号,windows实现
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 17:53
**/
public static String getDosMotherboardSN() throws IOException {
StringBuffer result = new StringBuffer();
String vbs =
"Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
exeDosCmd(vbs).forEach(item -> {
if (Objects.nonNull(item) && StringUtils.isNotBlank(item.toString()))
result.append(item.toString().trim());
});
return result.toString();
}
/**
* @Description: 获取unix系统 主板序列号
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 20:26
**/
public static String getUnixMotherboardSN() throws IOException {
StringBuffer stringBuffer = new StringBuffer();
String maniBordCmd = "dmidecode | grep 'Serial Number' | awk '{print $3}' | tail -1";
exeShellCmd(maniBordCmd).forEach(item -> {
if (Objects.nonNull(item) && StringUtils.isNotBlank(item.toString())) {
stringBuffer.append(item.toString());
}
});
return stringBuffer.toString();
}
/**
* @Description: 获取unix系统 cpu序列号
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 19:41
**/
public static String getUnixCPUSerial() throws IOException {
StringBuffer result = new StringBuffer();
exeShellCmd("dmidecode").forEach(item -> {
if (Objects.nonNull(item) &&
StringUtils.isNotBlank(item.toString()) &&
StringUtils.containsIgnoreCase(item.toString(), "uuid")) {
result.append(StringUtils.substringAfter(item.toString(), "uuid").trim());
}
});
return result.toString();
}
/**
* @Description: 执行unix shell脚本
*
* @param cmd 命令
* @return java.util.List<java.lang.Object>
* @Author mapabc
* @Date 2020/7/28 20:30
**/
private static List<Object> exeShellCmd(String cmd) throws IOException {
List<Object> result;
Process p;
p = Runtime.getRuntime().exec(new String[] { "sh", "-c", cmd }); //管道
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
result = Arrays.asList(bufferedReader.lines().toArray());
bufferedReader.close();
return result;
}
/**
* @Description: 执行dos脚本
*
* @param cmd 命令
* @return java.util.List<java.lang.Object>
* @Author mapabc
* @Date 2020/7/28 20:25
**/
private static List<Object> exeDosCmd(String cmd) throws IOException {
List<Object> result;
File file = File.createTempFile("tmp", ".vbs");
file.deleteOnExit();
FileWriter fw = new FileWriter(file);
fw.write(cmd);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
result = Arrays.asList(input.lines().toArray());
input.close();
file.delete();
return result;
}
/**
* @Description: 获取CPU序列号
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 17:53
**/
public static String getDosCPUSerial() throws IOException {
StringBuffer result = new StringBuffer();
String vbs =
"Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_Processor\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.ProcessorId \n"
+ " exit for ' do the first cpu only! \n"
+ "Next \n";
exeDosCmd(vbs).forEach(item -> {
if (Objects.nonNull(item) && StringUtils.isNotBlank(item.toString()))
result.append(item.toString().trim());
});
return result.toString();
}
/**
* @Description: 获取MAC地址,多网卡环境存在计算不准的问题
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 19:46
**/
public static String getMac() {
try {
byte[] mac =
NetworkInterface.getByInetAddress(InetAddress.getLocalHost())
.getHardwareAddress();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < mac.length; i++) {
if (i != 0) {
sb.append("-");
}
String s = Integer.toHexString(mac[i] & 0xFF);
sb.append(s.length() == 1 ? 0 + s : s);
}
return sb.toString().toUpperCase();
} catch (Exception e) {
return "";
}
}
/**
* @Description: 获取主板序列号,支持unix和dos系统
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 20:25
**/
public static String getMotherboardSN() throws IOException {
return isUnixOs() ? getUnixMotherboardSN() : getDosMotherboardSN();
}
/**
* @Description: 获取cpu序列号,支持unix和dos系统
*
* @return java.lang.String
* @Author mapabc
* @Date 2020/7/28 20:24
**/
public static String getCPUSerial() throws IOException {
return isUnixOs() ? getUnixCPUSerial() : getDosCPUSerial();
}
public static void main(String[] args) throws IOException {
System.out.println("CPU SN: " + HardWareUtils.getCPUSerial());
System.out.println("主板 SN: " + HardWareUtils.getMotherboardSN());
System.out.println("MAC SN: " + HardWareUtils.getMac());
try {
System.out.println(DESUtils.encrypt(HardWareUtils.getCPUSerial() + "," + HardWareUtils.getMotherboardSN() +","+ HardWareUtils.getMac() +","+ "2020-08-05 23:59:59"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Author mapabc
* @Description 获取机器码
* @Date 18:49 2020/8/3
* @Param []
* @return java.lang.String
* @throws
*/
public static String getMachineCode() throws IOException{
return getCPUSerial() + "-" + getMotherboardSN() ;
}
}
package net.wanji.common.utils.tool;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName BeanListUtils
* @Description
* @Author mapabc7
* @Date 2020/6/30 17:54
* @Version 1.0
*/
public class BeanListUtils {
public static <T> ArrayList beanToList(T bean) throws NoSuchFieldException, IllegalAccessException {
ArrayList<String> list = new ArrayList<String>();
if (bean == null)
return null;
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
Field f = bean.getClass().getDeclaredField(field.getName());
f.setAccessible(true);
Object o = f.get(bean);
list.add(o.toString());
}
return list;
}
/**
*
* 将dto和entity之间的属性互相转换,dto中属性一般为String等基本类型,
* 但是entity中可能有复合主键等复杂类型,需要注意同名问题
* @param src
* @param target
*/
public static Object populate(Object src, Object target) {
Method[] srcMethods = src.getClass().getMethods();
Method[] targetMethods = target.getClass().getMethods();
for (Method m : srcMethods) {
String srcName = m.getName();
if (srcName.startsWith("get")) {
try {
Object result = m.invoke(src);
for (Method mm : targetMethods) {
String targetName = mm.getName();
if (targetName.startsWith("set")
&& targetName.substring(3, targetName.length())
.equals(srcName.substring(3, srcName.length()))) {
mm.invoke(target, result);
}
}
} catch (Exception e) {
}
}
}
return target;
}
/**
*
* dto集合和实体类集合间的互相属性映射
*
* @param src
* @param target
* @param targetClass
* @return
*/
@SuppressWarnings("unchecked")
public static <S, T> List<T> populateList(List<S> src, List<T> target, Class<?> targetClass) {
for (int i = 0; i < src.size(); i++) {
try {
Object object = targetClass.newInstance();
target.add((T) object);
populate(src.get(i), object);
} catch (Exception e) {
continue;// 某个方法反射异常
}
}
return target;
}
}
package net.wanji.common.utils.tool;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.cglib.beans.BeanMap;
import java.lang.reflect.Field;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @ClassName BeanMapUtils
* @Description 用于Map和domain类的相互转换,比fastjson效率高
* @Author ${mapabc}
* @Date 2020/6/19 13:42
* @Version 1.0
*/
public class BeanMapUtils {
private static Pattern linePattern = Pattern.compile("_(\\w)");
private static Pattern humpPattern = Pattern.compile("[A-Z]");
/** 下划线转驼峰 */
public static String lineToHump(String str) {
str = str.toLowerCase();
Matcher matcher = linePattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/** 驼峰转下划线 */
public static String humpToLine(String str) {
Matcher matcher = humpPattern.matcher(str);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* 将对象装换为map
* @param bean
* @return
*/
public static <T> Map<String, Object> beanToMap(T bean) {
Map<String, Object> map = Maps.newHashMap();
if (bean != null) {
BeanMap beanMap = BeanMap.create(bean);
for (Object key : beanMap.keySet()) {
map.put(key+"", beanMap.get(key));
}
}
return map;
}
/**
* 将map装换为javabean对象 TODO bug 待处理,将map对象转换为bean时,如果属性中首字母为大写会转换不过去,待处理
* @param map
* @param clazz
* @return
*/
/*public static <T> T mapToBean(Map<String, Object> map,T bean) {
BeanMap beanMap = BeanMap.create(bean);
beanMap.putAll(map);
return bean;
}*/
public static <T> T mapToBean(Map<String, Object> map,Class<T> clazz) throws Exception {
T bean = null;
try {
bean = clazz.newInstance();
for (Field field : getAllFields(clazz)) {
if (map.containsKey(humpToLine(field.getName()))) {
boolean flag = field.isAccessible();
field.setAccessible(true);
Object object = map.get(humpToLine(field.getName()));
if (object != null) {
if (field.getType().isAssignableFrom(object.getClass())) {
field.set(bean, object);
} else {
//判断属性类型 进行转换,map中存放的是Object对象需要转换 实体类中有多少类型就加多少类型,实体类属性用包装类;
if (field.getType().toString().contains("Long")) {
field.set(bean, Long.parseLong(object.toString()));
}
if (field.getType().toString().contains("String")) {
field.set(bean, object.toString());
}
if (field.getType().toString().contains("Integer")) {
field.set(bean, Integer.parseInt(object.toString()));
}
if (field.getType().toString().contains("Float")) {
field.set(bean, Float.valueOf(object.toString()));
}
//处理LocalDateTime类型
/*if (field.getType().toString().contains("LocalDateTime")) {
field.set(bean, stringConvertLocalDateTime(object.toString()));
}*/
}
}
field.setAccessible(flag);
}
}
return bean;
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return bean;
}
/**
* 获取自身和上一级父类属性
* @param clazz
* @param <T>
* @return
*/
public static <T> Field[] getAllFields(Class<T> clazz){
List<Field> fieldList = new ArrayList<>();
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
if(clazz.getSuperclass()!=null){
//写死的 取一层父类 TODO 没有好的解决方案
fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getSuperclass().getDeclaredFields())));
}
Field[] fields = new Field[fieldList.size()];
fieldList.toArray(fields);
return fields;
}
public static void main(String[] args) {
Map map = new HashMap();
map.put("resName","1111");
map.put("resType","123");
// mapToBean(map,new OperationLog)
//// String indexName = map.get("indexName").toString();
//// String typeName = map.get("typeName").toString();
}
/**
* 将List<T>转换为List<Map<String, Object>>
* @param objList
* @return
*
*/
public static <T> List<Map<String, Object>> objectsToMaps(List<T> objList) {
List<Map<String, Object>> list = Lists.newArrayList();
if (objList != null && objList.size() > 0) {
Map<String, Object> map = null;
T bean = null;
for (int i = 0,size = objList.size(); i < size; i++) {
bean = objList.get(i);
map = beanToMap(bean);
list.add(map);
}
}
return list;
}
/**
* 将List<Map<String,Object>>转换为List<T>
* @param maps
* @param clazz
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public static <T> List<T> mapsToObjects(List<Map<String, Object>> maps,Class<T> clazz) throws Exception {
List<T> list = Lists.newArrayList();
if (maps != null && maps.size() > 0) {
Map<String, Object> map = null;
T bean = null;
for (int i = 0,size = maps.size(); i < size; i++) {
map = maps.get(i);
bean = mapToBean(map, clazz);
list.add(bean);
}
}
return list;
}
}
package net.wanji.common.utils.tool;
import org.apache.commons.lang3.StringUtils;
public class CamelUnderlineUtil {
private static final char UNDERLINE ='_';
public static String camelToUnderline(String param) {
if (StringUtils.isEmpty(param)) {
return "";
}
StringBuilder sb = new StringBuilder();
int len = param.length();
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (Character.isUpperCase(c)) {
sb.append(UNDERLINE);
sb.append(Character.toLowerCase(c));
} else {
sb.append(c);
}
}
return sb.toString();
}
public static String underlineToCamel(String param){
if (StringUtils.isEmpty(param)) {
return "";
}
StringBuilder sb = new StringBuilder();
int len = param.length();
for (int i = 0; i < len; i++) {
char c = param.charAt(i);
if (c==UNDERLINE) {
if(++i<len){
sb.append(Character.toUpperCase(param.charAt(i)));
}
} else {
sb.append(c);
}
}
return sb.toString();
}
}
\ No newline at end of file
package net.wanji.common.utils.tool;
import java.math.BigInteger;
import java.util.Stack;
/**
* @author hfx
* @date 2023/1/16 15:45
* @desc ConvertBaseUtils
*/
public class ConvertBaseUtils {
private static final String TARGET_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final char[] chs = TARGET_STR.toCharArray();
private static final BigInteger INTEGER0 = new BigInteger("0");
private static final Integer SHIFT = 5;
private static final Integer RADIX32 = 32;
/**
* 基数转换32进制,不足五位,补齐五位字符
* @param number
* @return
*/
public static String numToRadix32(long number) {
String buf = numToRadix(number +"", RADIX32);
if(buf.length() < SHIFT) {
int num = SHIFT - buf.length();
for(int i = 0; i < num; i++) {
buf = "0" + buf;
}
}
return buf;
}
/**
* 10进制转任意进制
* @param number
* @param radix
* @return
*/
public static String numToRadix(String number, int radix) {
if (radix < 0 || radix > TARGET_STR.length()) {
radix = TARGET_STR.length();
}
BigInteger bigNumber = new BigInteger(number);
BigInteger bigRadix = new BigInteger(radix + "");
Stack<Character> stack = new Stack<>();
StringBuilder result = new StringBuilder(0);
while (!bigNumber.equals(INTEGER0)) {
stack.add(chs[bigNumber.remainder(bigRadix).intValue()]);
bigNumber = bigNumber.divide(bigRadix);
}
for (; !stack.isEmpty(); ) {
result.append(stack.pop());
}
return result.length() == 0 ? "0" : result.toString();
}
}
package net.wanji.common.utils.tool;
import net.wanji.common.tool.wsdltool.DoSoapTool;
import org.dom4j.DocumentException;
import org.json.JSONObject;
import org.json.XML;
import java.io.IOException;
/**
* @ClassName JsonXmlUtils
* @Description
* @Author mapabc7
* @Date 2020/7/28 10:34
* @Version 1.0
*/
public class JsonXmlUtils {
private static JSONObject xmlToJson(String xml, boolean keepStrings) {
if (StringUtils.isNotBlank(xml)) {
JSONObject jsonObject = XML.toJSONObject(xml, keepStrings);
StringBuilder stringBuilder = new StringBuilder();
JSONObject json = new JSONObject();
String envelope = null;
for (String s : jsonObject.keySet()) {
if (StringUtils.containsIgnoreCase(s, "Envelope")) {
envelope = s;
break;
}
}
stringBuilder.append(envelope);
JSONObject envelopeValue = jsonObject.getJSONObject(envelope);
// 组装重构生成的json
packageJson(stringBuilder, envelopeValue);
json.put(stringBuilder.toString(), envelopeValue);
return json;
}
return null;
}
public static String xmlToJsonString(String xml) {
return xmlToJsonString(xml, true);
}
public static String soapXmlToJsonString(String xml) {
return xmlToJsonString(xml, true);
}
public static String xmlToJsonString(String xml, boolean keepStrings) {
if (StringUtils.isNotBlank(xml)) {
JSONObject jsonObject = xmlToJson(xml, keepStrings);
if (jsonObject != null) {
return jsonObject.toString();
}
}
return null;
}
public static String jsonToXml(Object json) {
if (json != null) {
String s = XML.toString(new JSONObject(json + ";"));
return s.substring(0, s.lastIndexOf(":Envelope")) + ":Envelope>";
}
return null;
}
public static String jsonToSoapXml(Object json) {
if (json != null) {
String s = XML.toString(new JSONObject(json + ";"));
return s.substring(0, s.lastIndexOf(":Envelope")) + ":Envelope>";
}
return null;
}
private static void packageJson(StringBuilder stringBuilder, JSONObject envelopeValue) {
for (String s : envelopeValue.keySet()) {
if (s.startsWith("xmlns:")) {
stringBuilder.append(" ").append(s).append("=").append("\"").append(envelopeValue.getString(s)).append("\"");
envelopeValue.remove(s);
if (envelopeValue.length() > 0) {
packageJson(stringBuilder, envelopeValue);
}
return;
}
}
}
public static void main(String[] args) throws DocumentException, IOException {
String xml = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:web=\"http://WebXml.com.cn/\">\n" +
" <soap:Header/>\n" +
" <soap:Body>\n" +
" <web:getSupportCity>\n" +
" <!--Optional:-->\n" +
" <web:byProvinceName>河北</web:byProvinceName>\n" +
" </web:getSupportCity>\n" +
" </soap:Body>\n" +
"</soap:Envelope>";
String s2 = DoSoapTool.doPostSoap("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl", xml);
System.out.println(s2);
}
}
package net.wanji.common.utils.webservice;
import com.alibaba.fastjson.JSON;
import java.util.HashMap;
import java.util.Map;
/**
* @ClassName SoapUtils
* @Description
* @Author mapabc7
* @Date 2020/6/1 18:20
* @Version 1.0
*/
public class SoapUtils {
/**
* 生成soapxml
*
* @param targetNamespace
* @param functionName
* @param bodyMap
* @return
*/
public static String buildSoapXml(String targetNamespace, String functionName, Map<String, Object> bodyMap) {
StringBuilder stringBuilder = new StringBuilder("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"" +
" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n")
.append("\t<soap:Body>\n")
.append("\t\t<" + functionName + " xmlns=\"" + targetNamespace + "\">\n")
.append(paramTransformSoapXml(bodyMap))
.append("\t\t</" + functionName + ">\n")
.append("\t</soap:Body>\n")
.append("</soap:Envelope>");
return String.valueOf(stringBuilder);
}
/**
* 将参数转化为soapXml中的一部分
*
* @param paramMap
* @return
*/
private static String paramTransformSoapXml(Map<String, Object> paramMap) {
if (paramMap.isEmpty()) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
stringBuilder.append(paramTransformSoapXml(entry));
}
return String.valueOf(stringBuilder);
}
private static String paramTransformSoapXml(Map.Entry<String, Object> entry) {
StringBuilder stringBuilder = new StringBuilder();
String entryKey = entry.getKey();
Object entryValue = entry.getValue();
if (entryValue instanceof Map) {
stringBuilder.append("\t\t\t").append("<" + entryKey + ">\n");
stringBuilder.append(paramTransformSoapXml(JSON.parseObject(JSON.toJSONString(entryValue))));
stringBuilder.append("\t\t\t").append("</" + entryKey + ">\n");
} else {
stringBuilder.append("\t\t\t").append("<" + entryKey + ">").append(entryValue).append("</" + entryKey + ">\n");
}
return String.valueOf(stringBuilder);
}
public static void main(String[] args) {
String targetNamespace = "http://WebXml.com.cn/";
String funName = "getSupportCity";
Map bodyMap = new HashMap() {{
put("byProvinceName", "河北");
}};
String soapXml = SoapUtils.buildSoapXml(targetNamespace, funName, bodyMap);
System.out.println(soapXml);
}
}
package net.wanji.common.utils.webservice;
import net.wanji.common.framework.exception.DubboProviderException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/**
* Created by mapabc4 on 2019/5/22.
*/
@Slf4j
public class WebServiceUtils {
// 请求超时时间
static int socketTimeout = 30000;
// 传输超时时间
static int connectTimeout = 30000;
/**
* 使用SOAP1.1发送消息
*
* @param postUrl
* @param soapXml
* @return
*/
public static String doPostSoap1_1(String postUrl, String soapXml, Map<String, Object> headerMap) throws DubboProviderException {
String retStr = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(postUrl);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
try {
// httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
httpPost.setHeader("Content-Type", String.valueOf(headerMap.get("Content-Type")));
StringEntity data = new StringEntity(soapXml,
Charset.forName("UTF-8"));
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印响应内容
retStr = EntityUtils.toString(httpEntity, "UTF-8");
log.info("response:" + retStr);
}
// 释放资源
closeableHttpClient.close();
} catch (Exception e) {
log.error("exception in doPostSoap1_1", e);
throw new DubboProviderException(e);
}
return retStr;
}
/**
* 使用SOAP1.2发送消息
*
* @param postUrl
* @param soapXml
* @param soapAction
* @return
*/
public static String doPostSoap1_2(String postUrl, String soapXml,
String soapAction, Map<String, Object> headerMap) {
String retStr = "";
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// HttpClient
CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
HttpPost httpPost = new HttpPost(postUrl);
// 设置请求和传输超时时间
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(socketTimeout)
.setConnectTimeout(connectTimeout).build();
httpPost.setConfig(requestConfig);
try {
// httpPost.setHeader("Content-Type",
// "application/soap+xml;charset=UTF-8");
httpPost.setHeader("Content-Type", String.valueOf(headerMap.get("Content-Type")));
httpPost.setHeader("SOAPAction", soapAction);
StringEntity data = new StringEntity(soapXml,
Charset.forName("UTF-8"));
httpPost.setEntity(data);
CloseableHttpResponse response = closeableHttpClient
.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (httpEntity != null) {
// 打印响应内容
retStr = EntityUtils.toString(httpEntity, "UTF-8");
log.info("response:" + retStr);
}
// 释放资源
closeableHttpClient.close();
} catch (Exception e) {
log.error("exception in doPostSoap1_2", e);
}
return retStr;
}
public static void main(String[] args) {
String url = "http://192.168.10.179:8080/helloService?wsdl";
String targetNamespace = "http://webservice.restful.design.bp.com/";
String funName = "sayHello";
Map bodyMap = new HashMap() {{
put("message", "你好");
}};
String xml = SoapUtils.buildSoapXml(targetNamespace, funName, bodyMap);
System.out.println(xml);
try {
System.out.println(doPostSoap1_1(url, xml, new HashMap<String, Object>() {{
put("Content-Type", "text/xml; charset=utf-8");
}}));
} catch (DubboProviderException e) {
e.printStackTrace();
}
}
}
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