Commit 2b81c7d2 by zhoutianguoji

init commit

parents

Too many changes to show.

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

/web/jeesite-web.iml
/root/jeesite-root.iml
/parent/jeesite-parent.iml
/modules/admin/jeesite-module-admin.iml
/modules/api/jeesite-module-api.iml
/modules/core/jeesite-core.iml
/common/jeesite-common.iml
/.idea/
/web/src/main/resources/config/
/web/target/
/modules/admin/target/
/modules/api/target/
/modules/core/target/
/common/target/
@echo off
rem /**
rem * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
rem *
rem * Author: ThinkGem@163.com
rem */
echo.
echo [信息] 部署工程版本到Nexus服务器。
echo.
%~d0
cd %~dp0
cd ..
call mvn clean deploy -Dmaven.test.skip=true -Pdeploy
pause
\ No newline at end of file
@echo off
rem /**
rem * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
rem *
rem * Author: ThinkGem@163.com
rem */
echo.
echo [信息] 编译工程Javadoc,生成jar包文件。
echo.
%~d0
cd %~dp0
cd ..
call mvn clean package -Pjavadoc
pause
\ No newline at end of file
@echo off
rem /**
rem * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
rem *
rem * Author: ThinkGem@163.com
rem */
echo.
echo [信息] 打包安装工程,生成jar包文件。
echo.
%~d0
cd %~dp0
cd ..
call mvn clean install -Dmaven.test.skip=true -Ppackage
pause
\ No newline at end of file
This diff is collapsed. Click to expand it.
////
//// Source code recreated from a .class file by IntelliJ IDEA
//// (powered by Fernflower decompiler)
////
//
//package com.github.tobato.fastdfs.service;
//
//import com.github.tobato.fastdfs.domain.MetaData;
//import com.github.tobato.fastdfs.domain.StorageNode;
//import com.github.tobato.fastdfs.domain.StorePath;
//import com.github.tobato.fastdfs.domain.ThumbImageConfig;
//import com.github.tobato.fastdfs.exception.FdfsUnsupportImageTypeException;
//import com.github.tobato.fastdfs.exception.FdfsUploadImageException;
//import com.github.tobato.fastdfs.proto.storage.StorageSetMetadataCommand;
//import com.github.tobato.fastdfs.proto.storage.StorageUploadFileCommand;
//import com.github.tobato.fastdfs.proto.storage.StorageUploadSlaveFileCommand;
//import com.github.tobato.fastdfs.proto.storage.enums.StorageMetadataSetType;
//
//import java.io.ByteArrayInputStream;
//import java.io.ByteArrayOutputStream;
//import java.io.IOException;
//import java.io.InputStream;
//import java.util.Arrays;
//import java.util.List;
//import java.util.Set;
//
//import net.coobird.thumbnailator.Thumbnails;
//import org.apache.commons.io.IOUtils;
//import org.apache.commons.lang3.Validate;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//@Component
//public class DefaultFastFileStorageClient extends DefaultGenerateStorageClient implements FastFileStorageClient {
// private static final String[] SUPPORT_IMAGE_TYPE = new String[]{"JPG", "JPEG", "PNG", "GIF", "BMP", "WBMP"};
// private static final List<String> SUPPORT_IMAGE_LIST;
// private static final String FRP_IP = "120.79.79.115";
// private static final int FRP_PORT = 23001;
// @Autowired
// private ThumbImageConfig thumbImageConfig;
//
// public DefaultFastFileStorageClient() {
// }
//
// public StorePath uploadFile(InputStream inputStream, long fileSize, String fileExtName, Set<MetaData> metaDataSet) {
// Validate.notNull(inputStream, "上传文件流不能为空", new Object[0]);
// Validate.notBlank(fileExtName, "文件扩展名不能为空", new Object[0]);
// StorageNode client = this.trackerClient.getStoreStorage();
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// return this.uploadFileAndMetaData(client, inputStream, fileSize, fileExtName, metaDataSet);
// }
//
// public StorePath uploadImageAndCrtThumbImage(InputStream inputStream, long fileSize, String fileExtName, Set<MetaData> metaDataSet) {
// Validate.notNull(inputStream, "上传文件流不能为空", new Object[0]);
// Validate.notBlank(fileExtName, "文件扩展名不能为空", new Object[0]);
// if (!this.isSupportImage(fileExtName)) {
// throw new FdfsUnsupportImageTypeException("不支持的图片格式" + fileExtName);
// } else {
// StorageNode client = this.trackerClient.getStoreStorage();
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// byte[] bytes = this.inputStreamToByte(inputStream);
// StorePath path = this.uploadFileAndMetaData(client, new ByteArrayInputStream(bytes), fileSize, fileExtName, metaDataSet);
// this.uploadThumbImage(client, new ByteArrayInputStream(bytes), path.getPath(), fileExtName);
// bytes = null;
// return path;
// }
// }
//
// private byte[] inputStreamToByte(InputStream inputStream) {
// try {
// return IOUtils.toByteArray(inputStream);
// } catch (IOException var3) {
// LOGGER.error("image inputStream to byte error", var3);
// throw new FdfsUploadImageException("upload ThumbImage error", var3.getCause());
// }
// }
//
// private boolean hasMetaData(Set<MetaData> metaDataSet) {
// return null != metaDataSet && !metaDataSet.isEmpty();
// }
//
// private boolean isSupportImage(String fileExtName) {
// return SUPPORT_IMAGE_LIST.contains(fileExtName.toUpperCase());
// }
//
// private StorePath uploadFileAndMetaData(StorageNode client, InputStream inputStream, long fileSize, String fileExtName, Set<MetaData> metaDataSet) {
// StorageUploadFileCommand command = new StorageUploadFileCommand(client.getStoreIndex(), inputStream, fileExtName, fileSize, false);
// StorePath path = (StorePath) this.connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// if (this.hasMetaData(metaDataSet)) {
// StorageSetMetadataCommand setMDCommand = new StorageSetMetadataCommand(path.getGroup(), path.getPath(), metaDataSet, StorageMetadataSetType.STORAGE_SET_METADATA_FLAG_OVERWRITE);
// this.connectionManager.executeFdfsCmd(client.getInetSocketAddress(), setMDCommand);
// }
//
// return path;
// }
//
// private void uploadThumbImage(StorageNode client, InputStream inputStream, String masterFilename, String fileExtName) {
// ByteArrayInputStream thumbImageStream = null;
//
// try {
// thumbImageStream = this.getThumbImageStream(inputStream);
// long fileSize = (long) thumbImageStream.available();
// String prefixName = this.thumbImageConfig.getPrefixName();
// StorageUploadSlaveFileCommand command = new StorageUploadSlaveFileCommand(thumbImageStream, fileSize, masterFilename, prefixName, fileExtName);
// this.connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// } catch (IOException var13) {
// LOGGER.error("upload ThumbImage error", var13);
// throw new FdfsUploadImageException("upload ThumbImage error", var13.getCause());
// } finally {
// IOUtils.closeQuietly(thumbImageStream);
// }
//
// }
//
// private ByteArrayInputStream getThumbImageStream(InputStream inputStream) throws IOException {
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// Thumbnails.of(new InputStream[]{inputStream}).size(this.thumbImageConfig.getWidth(), this.thumbImageConfig.getHeight()).toOutputStream(out);
// return new ByteArrayInputStream(out.toByteArray());
// }
//
// public void deleteFile(String filePath) {
// StorePath storePath = StorePath.praseFromUrl(filePath);
// super.deleteFile(storePath.getGroup(), storePath.getPath());
// }
//
// static {
// SUPPORT_IMAGE_LIST = Arrays.asList(SUPPORT_IMAGE_TYPE);
// }
//}
//package com.github.tobato.fastdfs.service;
//
//import java.io.InputStream;
//import java.util.Set;
//
//import com.github.tobato.fastdfs.domain.*;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import com.github.tobato.fastdfs.conn.ConnectionManager;
//import com.github.tobato.fastdfs.domain.MetaData;
//import com.github.tobato.fastdfs.proto.storage.DownloadCallback;
//import com.github.tobato.fastdfs.proto.storage.StorageDeleteFileCommand;
//import com.github.tobato.fastdfs.proto.storage.StorageDownloadCommand;
//import com.github.tobato.fastdfs.proto.storage.StorageGetMetadataCommand;
//import com.github.tobato.fastdfs.proto.storage.StorageQueryFileInfoCommand;
//import com.github.tobato.fastdfs.proto.storage.StorageSetMetadataCommand;
//import com.github.tobato.fastdfs.proto.storage.StorageUploadFileCommand;
//import com.github.tobato.fastdfs.proto.storage.StorageUploadSlaveFileCommand;
//import com.github.tobato.fastdfs.proto.storage.enums.StorageMetadataSetType;
//
///**
// * 基本存储客户端操作实现
// *
// * @author tobato
// */
//@Component
//public class DefaultGenerateStorageClient implements GenerateStorageClient {
//
// private static final String FRP_IP = "120.79.79.115";
// private static final int FRP_PORT = 23001;
//
// /**
// * trackerClient
// */
// @Autowired
// protected TrackerClient trackerClient;
//
// /**
// * connectManager
// */
// @Autowired
// protected ConnectionManager connectionManager;
//
// /**
// * 日志
// */
// protected static Logger LOGGER = LoggerFactory.getLogger(DefaultGenerateStorageClient.class);
//
// /**
// * 上传不支持断点续传的文件
// */
// @Override
// public StorePath uploadFile(String groupName, InputStream inputStream, long fileSize, String fileExtName) {
// StorageNode client = trackerClient.getStoreStorage(groupName);
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// StorageUploadFileCommand command = new StorageUploadFileCommand(client.getStoreIndex(), inputStream,
// fileExtName, fileSize, false);
// return connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// }
//
// /**
// * 上传从文件
// */
// @Override
// public StorePath uploadSlaveFile(String groupName, String masterFilename, InputStream inputStream, long fileSize,
// String prefixName, String fileExtName) {
// StorageNodeInfo client = trackerClient.getUpdateStorage(groupName, masterFilename);
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// StorageUploadSlaveFileCommand command = new StorageUploadSlaveFileCommand(inputStream, fileSize, masterFilename,
// prefixName, fileExtName);
// return connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// }
//
// /**
// * 获取metadata
// */
// @Override
// public Set<MetaData> getMetadata(String groupName, String path) {
// StorageNodeInfo client = trackerClient.getFetchStorage(groupName, path);
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// StorageGetMetadataCommand command = new StorageGetMetadataCommand(groupName, path);
// return connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// }
//
// /**
// * 覆盖metadata
// */
// @Override
// public void overwriteMetadata(String groupName, String path, Set<MetaData> metaDataSet) {
// StorageNodeInfo client = trackerClient.getUpdateStorage(groupName, path);
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// StorageSetMetadataCommand command = new StorageSetMetadataCommand(groupName, path, metaDataSet,
// StorageMetadataSetType.STORAGE_SET_METADATA_FLAG_OVERWRITE);
// connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// }
//
// /**
// * 合并metadata
// */
// @Override
// public void mergeMetadata(String groupName, String path, Set<MetaData> metaDataSet) {
// StorageNodeInfo client = trackerClient.getUpdateStorage(groupName, path);
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// StorageSetMetadataCommand command = new StorageSetMetadataCommand(groupName, path, metaDataSet,
// StorageMetadataSetType.STORAGE_SET_METADATA_FLAG_MERGE);
// connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// }
//
// /**
// * 查询文件信息
// */
// @Override
// public FileInfo queryFileInfo(String groupName, String path) {
// StorageNodeInfo client = trackerClient.getFetchStorage(groupName, path);
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// StorageQueryFileInfoCommand command = new StorageQueryFileInfoCommand(groupName, path);
// return connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// }
//
// /**
// * 删除文件
// */
// @Override
// public void deleteFile(String groupName, String path) {
// StorageNodeInfo client = trackerClient.getUpdateStorage(groupName, path);
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// StorageDeleteFileCommand command = new StorageDeleteFileCommand(groupName, path);
// connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// }
//
// /**
// * 下载整个文件
// */
// @Override
// public <T> T downloadFile(String groupName, String path, DownloadCallback<T> callback) {
// long fileOffset = 0;
// long fileSize = 0;
// return downloadFile(groupName, path, fileOffset, fileSize, callback);
// }
//
// /**
// * 下载文件片段
// */
// @Override
// public <T> T downloadFile(String groupName, String path, long fileOffset, long fileSize,
// DownloadCallback<T> callback) {
// StorageNodeInfo client = trackerClient.getFetchStorage(groupName, path);
// client.setIp(FRP_IP);
// client.setPort(FRP_PORT);
// StorageDownloadCommand<T> command = new StorageDownloadCommand<T>(groupName, path, fileOffset, fileSize, callback);
// return connectionManager.executeFdfsCmd(client.getInetSocketAddress(), command);
// }
//
// public void setTrackerClientService(TrackerClient trackerClientService) {
// this.trackerClient = trackerClientService;
// }
//
// public void setConnectionManager(ConnectionManager connectionManager) {
// this.connectionManager = connectionManager;
// }
//
//}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.callback;
/**
* 方法回调接口
* @author ThinkGem
*/
public interface MethodCallback {
Object execute(Object... params);
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.codec;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import com.jeesite.common.lang.ExceptionUtils;
/**
* AES加密解密工具类
* @author ThinkGem
*/
public class AesUtils {
private static final String AES = "AES";
private static final String AES_CBC = "AES/CBC/PKCS5Padding";
private static final int DEFAULT_AES_KEYSIZE = 128; // 生成AES密钥, 默认长度为128位(16字节).
private static final int DEFAULT_IVSIZE = 16; // 生成随机向量, 默认大小为cipher.getBlockSize(), 16字节
private static final SecureRandom RANDOM = new SecureRandom(); // 用于 生成 generateIV随机数对象
private static final String DEFAULT_URL_ENCODING = "UTF-8";
private static final byte[] DEFAULT_KEY = new byte[]{-97,88,-94,9,70,-76,126,25,0,3,-20,113,108,28,69,125};
/**
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
*/
public static String genKeyString() {
return EncodeUtils.encodeHex(genKey(DEFAULT_AES_KEYSIZE));
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
*/
public static String encode(String input) {
try {
return EncodeUtils.encodeHex(encode(input.getBytes(DEFAULT_URL_ENCODING), DEFAULT_KEY));
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
* @param key 符合AES要求的密钥
*/
public static String encode(String input, String key) {
try {
return EncodeUtils.encodeHex(encode(input.getBytes(DEFAULT_URL_ENCODING), EncodeUtils.decodeHex(key)));
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
*/
public static String decode(String input) {
try {
return new String(decode(EncodeUtils.decodeHex(input), DEFAULT_KEY), DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
* @param key 符合AES要求的密钥
*/
public static String decode(String input, String key) {
try {
return new String(decode(EncodeUtils.decodeHex(input), EncodeUtils.decodeHex(key)), DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
*/
public static byte[] genKey() {
return genKey(DEFAULT_AES_KEYSIZE);
}
/**
* 生成AES密钥,可选长度为128,192,256位.
*/
public static byte[] genKey(int keysize) {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
keyGenerator.init(keysize);
SecretKey secretKey = keyGenerator.generateKey();
return secretKey.getEncoded();
} catch (GeneralSecurityException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* 生成随机向量,默认大小为cipher.getBlockSize(), 16字节.
*/
public static byte[] genIV() {
byte[] bytes = new byte[DEFAULT_IVSIZE];
RANDOM.nextBytes(bytes);
return bytes;
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
* @param key 符合AES要求的密钥
*/
public static byte[] encode(byte[] input, byte[] key) {
return aes(input, key, Cipher.ENCRYPT_MODE);
}
/**
* 使用AES加密原始字符串.
*
* @param input 原始输入字符数组
* @param key 符合AES要求的密钥
* @param iv 初始向量
*/
public static byte[] encode(byte[] input, byte[] key, byte[] iv) {
return aes(input, key, iv, Cipher.ENCRYPT_MODE);
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
* @param key 符合AES要求的密钥
*/
public static byte[] decode(byte[] input, byte[] key) {
return aes(input, key, Cipher.DECRYPT_MODE);
}
/**
* 使用AES解密字符串, 返回原始字符串.
*
* @param input Hex编码的加密字符串
* @param key 符合AES要求的密钥
* @param iv 初始向量
*/
public static byte[] decode(byte[] input, byte[] key, byte[] iv) {
return aes(input, key, iv, Cipher.DECRYPT_MODE);
}
/**
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
*
* @param input 原始字节数组
* @param key 符合AES要求的密钥
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
*/
private static byte[] aes(byte[] input, byte[] key, int mode) {
try {
SecretKey secretKey = new SecretKeySpec(key, AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(mode, secretKey);
return cipher.doFinal(input);
} catch (GeneralSecurityException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
*
* @param input 原始字节数组
* @param key 符合AES要求的密钥
* @param iv 初始向量
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
*/
private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) {
try {
SecretKey secretKey = new SecretKeySpec(key, AES);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
Cipher cipher = Cipher.getInstance(AES_CBC);
cipher.init(mode, secretKey, ivSpec);
return cipher.doFinal(input);
} catch (GeneralSecurityException e) {
throw ExceptionUtils.unchecked(e);
}
}
// public static void main(String[] args) {
//
// String s = "hello word!";
// System.out.println(s);
//
// String k = genKeyString();
// System.out.println(k);
// String ss = encode(s, k);
// System.out.println(ss);
// String sss = decode(ss, k);
// System.out.println(sss);
//
// }
}
\ No newline at end of file
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.codec;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import org.apache.commons.lang3.Validate;
import com.jeesite.common.lang.ExceptionUtils;
/**
* 不可逆加密工具类
* @author ThinkGem
*/
public class DigestUtils {
private static SecureRandom random = new SecureRandom();
/**
* 生成随机的Byte[]作为salt密钥.
* @param numBytes byte数组的大小
*/
public static byte[] genSalt(int numBytes) {
Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
byte[] bytes = new byte[numBytes];
random.nextBytes(bytes);
return bytes;
}
/**
* 对字符串进行散列, 支持md5与sha1算法.
* @param input 需要散列的字符串
* @param algorithm 散列算法("SHA-1"、"MD5")
* @param salt
* @param iterations 迭代次数
* @return
*/
public static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
if (salt != null) {
digest.update(salt);
}
byte[] result = digest.digest(input);
for (int i = 1; i < iterations; i++) {
digest.reset();
result = digest.digest(result);
}
return result;
} catch (GeneralSecurityException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* 对文件进行sha1散列.
* @param input 需要散列的流
* @param algorithm 散列算法("SHA-1"、"MD5")
*/
public static byte[] digest(InputStream input, String algorithm) throws IOException {
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
int bufferLength = 8 * 1024;
byte[] buffer = new byte[bufferLength];
int read = input.read(buffer, 0, bufferLength);
while (read > -1) {
messageDigest.update(buffer, 0, read);
read = input.read(buffer, 0, bufferLength);
}
return messageDigest.digest();
} catch (GeneralSecurityException e) {
throw ExceptionUtils.unchecked(e);
}
}
}
/**
* Copyright (c) 2005-2012 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jeesite.common.codec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.text.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.lang.ExceptionUtils;
import com.jeesite.common.lang.StringUtils;
/**
* 封装各种格式的编码解码工具类.
* 1.Commons-Codec的 hex/base64 编码
* 2.自制的base62 编码
* 3.Commons-Lang的xml/html escape
* 4.JDK提供的URLEncoder
* @author calvin
* @version 2013-01-15
*/
public class EncodeUtils {
private static final Logger logger = LoggerFactory.getLogger(EncodeUtils.class);
private static final String DEFAULT_URL_ENCODING = "UTF-8";
private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
/**
* Hex编码.
*/
public static String encodeHex(byte[] input) {
return new String(Hex.encodeHex(input));
}
/**
* Hex解码.
*/
public static byte[] decodeHex(String input) {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* Base64编码.
*/
public static String encodeBase64(byte[] input) {
return new String(Base64.encodeBase64(input));
}
/**
* Base64编码.
*/
public static String encodeBase64(String input) {
try {
return new String(Base64.encodeBase64(input.getBytes(DEFAULT_URL_ENCODING)));
} catch (UnsupportedEncodingException e) {
return "";
}
}
// /**
// * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
// */
// public static String encodeUrlSafeBase64(byte[] input) {
// return Base64.encodeBase64URLSafe(input);
// }
/**
* Base64解码.
*/
public static byte[] decodeBase64(String input) {
return Base64.decodeBase64(input.getBytes());
}
/**
* Base64解码.
*/
public static String decodeBase64String(String input) {
try {
return new String(Base64.decodeBase64(input.getBytes()), DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
return "";
}
}
/**
* Base62编码。
*/
public static String encodeBase62(byte[] input) {
char[] chars = new char[input.length];
for (int i = 0; i < input.length; i++) {
chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
}
return new String(chars);
}
/**
* Html 转码.
*/
public static String encodeHtml(String html) {
return StringEscapeUtils.escapeHtml4(html);
}
/**
* Html 解码.
*/
public static String decodeHtml(String htmlEscaped) {
return StringEscapeUtils.unescapeHtml4(htmlEscaped);
}
/**
* Xml 转码.
*/
public static String encodeXml(String xml) {
return StringEscapeUtils.escapeXml10(xml);
}
/**
* Xml 解码.
*/
public static String decodeXml(String xmlEscaped) {
return StringEscapeUtils.unescapeXml(xmlEscaped);
}
/**
* URL 编码, Encode默认为UTF-8.
*/
public static String encodeUrl(String part) {
return encodeUrl(part, DEFAULT_URL_ENCODING);
}
/**
* URL 编码, Encode默认为UTF-8.
*/
public static String encodeUrl(String part, String encoding) {
if (part == null){
return null;
}
try {
return URLEncoder.encode(part, encoding);
} catch (UnsupportedEncodingException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* URL 解码, Encode默认为UTF-8.
*/
public static String decodeUrl(String part) {
return decodeUrl(part, DEFAULT_URL_ENCODING);
}
/**
* URL 解码, Encode默认为UTF-8.
*/
public static String decodeUrl(String part, String encoding) {
if (part == null){
return null;
}
try {
return URLDecoder.decode(part, encoding);
} catch (UnsupportedEncodingException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* URL 解码(两次), Encode默认为UTF-8.
*/
public static String decodeUrl2(String part) {
return decodeUrl(decodeUrl(part));
}
// 预编译XSS过滤正则表达式
private static List<Pattern> xssPatterns = ListUtils.newArrayList(
Pattern.compile("(<\\s*(script|link|style|iframe)([\\s\\S]*?)(>|<\\/\\s*\\1\\s*>))|(</\\s*(script|link|style|iframe)\\s*>)", Pattern.CASE_INSENSITIVE),
Pattern.compile("\\s*(href|src)\\s*=\\s*(\"\\s*(javascript|vbscript):[^\"]+\"|'\\s*(javascript|vbscript):[^']+'|(javascript|vbscript):[^\\s]+)\\s*(?=>)", Pattern.CASE_INSENSITIVE),
Pattern.compile("\\s*on[a-z]+\\s*=\\s*(\"[^\"]+\"|'[^']+'|[^\\s]+)\\s*(?=>)", Pattern.CASE_INSENSITIVE),
Pattern.compile("(eval\\((.|\\n)*\\)|xpression\\((.|\\n)*\\))", Pattern.CASE_INSENSITIVE)
);
/**
* XSS 非法字符过滤,内容以<!--HTML-->开头的用以下规则(保留标签)
* @author ThinkGem
*/
public static String xssFilter(String text) {
String oriValue = StringUtils.trim(text);
if (text != null){
String value = oriValue;
for (Pattern pattern : xssPatterns) {
Matcher matcher = pattern.matcher(value);
if (matcher.find()) {
value = matcher.replaceAll(StringUtils.EMPTY);
}
}
// 如果开始不是HTML,XML,JOSN格式,则再进行HTML的 "、<、> 转码。
if (!StringUtils.startsWithIgnoreCase(value, "<!--HTML-->") // HTML
&& !StringUtils.startsWithIgnoreCase(value, "<?xml ") // XML
&& !StringUtils.contains(value, "id=\"FormHtml\"") // JFlow
&& !(StringUtils.startsWith(value, "{") && StringUtils.endsWith(value, "}")) // JSON Object
&& !(StringUtils.startsWith(value, "[") && StringUtils.endsWith(value, "]")) // JSON Array
){
value = value.replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
}
if (logger.isInfoEnabled() && !value.equals(oriValue)){
logger.info("xssFilter: {} <=<=<= {}", value, text);
}
return value;
}
return null;
}
// 预编译SQL过滤正则表达式
private static Pattern sqlPattern = Pattern.compile("(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\\b(select|update|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)\\b)", Pattern.CASE_INSENSITIVE);
/**
* SQL过滤,防止注入,传入参数输入有select相关代码,替换空。
* @author ThinkGem
*/
public static String sqlFilter(String text){
if (text != null){
String value = text;
Matcher matcher = sqlPattern.matcher(text);
if (matcher.find()) {
value = matcher.replaceAll(StringUtils.EMPTY);
}
if (logger.isWarnEnabled() && !value.equals(text)){
logger.info("sqlFilter: {} <=<=<= {}", value, text);
return StringUtils.EMPTY;
}
return value;
}
return null;
}
// public static void main(String[] args) {
// xssFilter("你好,<script>alert(document.cookie)</script>我还在。");
// xssFilter("你好,<strong>加粗文字</strong>我还在。");
// xssFilter("<!--HTML-->你好,\"><strong>加粗文字</strong>我还在。");
// xssFilter("<!--HTML-->你好,<iframe src=\"abcdef\"></iframe><strong>加粗文字</strong>我还在。");
// xssFilter("<!--HTML-->你好,<iframe src=\"abcdef\"/><strong>加粗文字</strong>我还在。");
// xssFilter("<!--HTML-->你好,<iframe src=\"abcdef\"><strong>加粗文字</strong>我还在。");
// xssFilter("<!--HTML-->你好,<script type=\"text/javascript\">alert(document.cookie)</script>我还在。");
// xssFilter("<!--HTML-->你好,<script\n type=\"text/javascript\">\nalert(document.cookie)\n</script>我还在。");
// xssFilter("<!--HTML-->你好,<script src='' onerror='alert(document.cookie)'></script>我还在。");
// xssFilter("<!--HTML-->你好,<script type=text/javascript>alert()我还在。");
// xssFilter("<!--HTML-->你好,<script>alert(document.cookie)</script>我还在。");
// xssFilter("<!--HTML-->你好,<script>window.location='url'我还在。");
// xssFilter("<!--HTML-->你好,</script></iframe>我还在。");
// xssFilter("<!--HTML-->你好,eval(abc)我还在。");
// xssFilter("<!--HTML-->你好,xpression(abc)我还在。");
// xssFilter("<!--HTML-->你好,<img src='abc.jpg' onerror='location='';alert(document.cookie);'></img>我还在。");
// xssFilter("<!--HTML-->你好,<img src='abc.jpg' onerror='alert(document.cookie);'/>我还在。");
// xssFilter("<!--HTML-->你好,<img src='abc.jpg' onerror='alert(document.cookie);'>我还在。");
// xssFilter("<!--HTML-->你好,<a onload='alert(\"abc\")'>hello</a>我还在。");
// xssFilter("<!--HTML-->你好,<a href=\"/abc\">hello</a>我还在。");
// xssFilter("<!--HTML-->你好,<a href='/abc'>hello</a>我还在。");
// xssFilter("<!--HTML-->你好,<a href='vbscript:alert(\"abc\");'>hello</a>我还在。");
// xssFilter("<!--HTML-->你好,<a href='javascript:alert(\"abc\");'>hello</a>我还在。");
// xssFilter("<!--HTML-->你好,?abc=def&hello=123&world={\"a\":1}我还在。");
// sqlFilter("你好,select * from xxx where abc=def and 1=1我还在。");
// sqlFilter("你好,insert into xxx values(1,2,3,4,5)我还在。");
// sqlFilter("你好,delete from xxx我还在。");
// }
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.codec;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import com.jeesite.common.io.IOUtils;
/**
* MD5不可逆加密工具类
* @author ThinkGem
*/
public class Md5Utils {
private static final String MD5 = "MD5";
private static final String DEFAULT_ENCODING = "UTF-8";
/**
* 对输入字符串进行md5散列.
* @param input 加密字符串
*/
public static String md5(String input) {
return md5(input, 1);
}
/**
* 对输入字符串进行md5散列.
* @param input 加密字符串
* @param iterations 迭代次数
*/
public static String md5(String input, int iterations) {
try {
return EncodeUtils.encodeHex(DigestUtils.digest(input.getBytes(DEFAULT_ENCODING), MD5, null, iterations));
} catch (UnsupportedEncodingException e) {
return StringUtils.EMPTY;
}
}
/**
* 对输入字符串进行md5散列.
* @param input 加密字符串
*/
public static byte[] md5(byte[] input) {
return md5(input, 1);
}
/**
* 对输入字符串进行md5散列.
* @param input 加密字符串
* @param iterations 迭代次数
*/
public static byte[] md5(byte[] input, int iterations) {
return DigestUtils.digest(input, MD5, null, iterations);
}
/**
* 对文件进行md5散列.
*/
public static byte[] md5(InputStream input) throws IOException {
return DigestUtils.digest(input, MD5);
}
/**
* 获取文件的MD5值
*/
public static String md5File(File file) {
return md5File(file, -1);
}
/**
* 获取文件的MD5值,支持获取文件部分的MD5值
* uploader.md5File(file, 0, 10 * 1024 * 1024)
*/
public static String md5File(File file, int size) {
if (file != null && file.exists()){
try (InputStream in = FileUtils.openInputStream(file)){
byte[] bytes = null;
if (size != -1 && file.length() >= size){
bytes = IOUtils.toByteArray(in, size);
}else{
bytes = IOUtils.toByteArray(in);
}
return EncodeUtils.encodeHex(md5(bytes));
} catch (IOException e) {
return StringUtils.EMPTY;
}
}
return StringUtils.EMPTY;
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.codec;
import java.io.IOException;
import java.io.InputStream;
/**
* SHA-1不可逆加密工具类
* @author ThinkGem
*/
public class Sha1Utils {
private static final String SHA1 = "SHA-1";
/**
* 生成随机的Byte[]作为salt密钥.
* @param numBytes byte数组的大小
*/
public static byte[] genSalt(int numBytes) {
return DigestUtils.genSalt(numBytes);
}
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(byte[] input) {
return DigestUtils.digest(input, SHA1, null, 1);
}
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(byte[] input, byte[] salt) {
return DigestUtils.digest(input, SHA1, salt, 1);
}
/**
* 对输入字符串进行sha1散列.
*/
public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
return DigestUtils.digest(input, SHA1, salt, iterations);
}
/**
* 对文件进行sha1散列.
*/
public static byte[] sha1(InputStream input) throws IOException {
return DigestUtils.digest(input, SHA1);
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.collect;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;
import com.jeesite.common.lang.StringUtils;
/**
* Map工具类,实现 Map <-> Bean 互相转换
* @author ThinkGem
* @version 2015-01-15
*/
public class MapUtils extends org.apache.commons.collections.MapUtils {
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
public static <K, V> HashMap<K, V> newHashMap(int initialCapacity) {
return new HashMap<K, V>(initialCapacity);
}
public static <K, V> HashMap<K, V> newHashMap(Map<? extends K, ? extends V> map) {
return new HashMap<K, V>(map);
}
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<K, V>();
}
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map) {
return new LinkedHashMap<K, V>(map);
}
public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
return new ConcurrentHashMap<K, V>();
}
@SuppressWarnings("rawtypes")
public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
return new TreeMap<K, V>();
}
public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) {
return new TreeMap<K, V>(map);
}
public static <C, K extends C, V> TreeMap<K, V> newTreeMap(Comparator<C> comparator) {
return new TreeMap<K, V>(comparator);
}
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) {
return new EnumMap<K, V>((type));
}
public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Map<K, ? extends V> map) {
return new EnumMap<K, V>(map);
}
public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
return new IdentityHashMap<K, V>();
}
/**
* List<Map<String, V>转换为List<T>
* @param clazz
* @param list
*/
public static <T, V> List<T> toObjectList(Class<T> clazz, List<HashMap<String, V>> list) throws IllegalAccessException,
InvocationTargetException, NoSuchMethodException, InstantiationException {
List<T> retList = new ArrayList<T>();
if (list != null && !list.isEmpty()) {
for (HashMap<String, V> m : list) {
retList.add(toObject(clazz, m));
}
}
return retList;
}
/**
* 将Map转换为Object
* @param clazz 目标对象的类
* @param map 待转换Map
*/
public static <T, V> T toObject(Class<T> clazz, Map<String, V> map) throws InstantiationException, IllegalAccessException,
InvocationTargetException {
T object = clazz.newInstance();
return toObject(object, map);
}
/**
* 将Map转换为Object
* @param clazz 目标对象的类
* @param map 待转换Map
* @param toCamelCase 是否去掉下划线
*/
public static <T, V> T toObject(Class<T> clazz, Map<String, V> map, boolean toCamelCase) throws InstantiationException, IllegalAccessException,
InvocationTargetException {
T object = clazz.newInstance();
return toObject(object, map, toCamelCase);
}
/**
* 将Map转换为Object
* @param clazz 目标对象的类
* @param map 待转换Map
*/
public static <T, V> T toObject(T object, Map<String, V> map) throws InstantiationException, IllegalAccessException, InvocationTargetException {
return toObject(object, map, false);
}
/**
* 将Map转换为Object
* @param object 目标对象的类
* @param map 待转换Map
* @param toCamelCase 是否采用驼峰命名法转换
*/
public static <T, V> T toObject(T object, Map<String, V> map, boolean toCamelCase) throws InstantiationException, IllegalAccessException,
InvocationTargetException {
if (toCamelCase) {
map = toCamelCaseMap(map);
}
BeanUtils.populate(object, map);
return object;
}
/**
* 对象转Map
* @param object 目标对象
* @return 转换出来的值都是String
*/
public static Map<String, String> toMap(Object object) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return BeanUtils.describe(object);
}
/**
* 对象转Map
* @param object 目标对象
* @return 转换出来的值类型是原类型
*/
public static Map<String, Object> toNavMap(Object object) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
return PropertyUtils.describe(object);
}
/**
* 转换为Collection<Map<K, V>>
* @param collection 待转换对象集合
* @return 转换后的Collection<Map<K, V>>
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
public static <T> Collection<Map<String, String>> toMapList(Collection<T> collection) throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
List<Map<String, String>> retList = new ArrayList<Map<String, String>>();
if (collection != null && !collection.isEmpty()) {
for (Object object : collection) {
Map<String, String> map = toMap(object);
retList.add(map);
}
}
return retList;
}
/**
* 转换为Collection,同时为字段做驼峰转换<Map<K, V>>
* @param collection 待转换对象集合
* @return 转换后的Collection<Map<K, V>>
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
public static <T> Collection<Map<String, String>> toMapListForFlat(Collection<T> collection) throws IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
List<Map<String, String>> retList = new ArrayList<Map<String, String>>();
if (collection != null && !collection.isEmpty()) {
for (Object object : collection) {
Map<String, String> map = toMapForFlat(object);
retList.add(map);
}
}
return retList;
}
/**
* 转换成Map并提供字段命名驼峰转平行
* @param clazz 目标对象所在类
* @param object 目标对象
* @param map 待转换Map
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static Map<String, String> toMapForFlat(Object object) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Map<String, String> map = toMap(object);
return toUnderlineStringMap(map);
}
/**
* 将Map的Keys去下划线<br>
* (例:branch_no -> branchNo )<br>
* @param map 待转换Map
* @return
*/
public static <V> Map<String, V> toCamelCaseMap(Map<String, V> map) {
Map<String, V> newMap = new HashMap<String, V>();
for (String key : map.keySet()) {
safeAddToMap(newMap, StringUtils.camelCase(key), map.get(key));
}
return newMap;
}
/**
* 将Map的Keys转译成下划线格式的<br>
* (例:branchNo -> branch_no)<br>
* @param map 待转换Map
* @return
*/
public static <V> Map<String, V> toUnderlineStringMap(Map<String, V> map) {
Map<String, V> newMap = new HashMap<String, V>();
for (String key : map.keySet()) {
newMap.put(StringUtils.uncamelCase(key), map.get(key));
}
return newMap;
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.collect;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Set工具类
* @author ThinkGem
* @version 2015-01-15
*/
public class SetUtils extends org.apache.commons.collections.SetUtils {
public static <E> HashSet<E> newHashSet() {
return new HashSet<E>();
}
@SafeVarargs
public static <E> HashSet<E> newHashSet(E... elements) {
HashSet<E> set = newHashSet(elements.length);
Collections.addAll(set, elements);
return set;
}
public static <E> HashSet<E> newHashSet(int initialCapacity) {
return new HashSet<E>(initialCapacity);
}
public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
return (elements instanceof Collection) ? new HashSet<E>(cast(elements)) : newHashSet(elements.iterator());
}
public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
HashSet<E> set = newHashSet();
addAll(set, elements);
return set;
}
public static <E> Set<E> newConcurrentHashSet() {
return Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}
public static <E> Set<E> newConcurrentHashSet(Iterable<? extends E> elements) {
Set<E> set = newConcurrentHashSet();
addAll(set, elements);
return set;
}
public static <E> LinkedHashSet<E> newLinkedHashSet() {
return new LinkedHashSet<E>();
}
public static <E> LinkedHashSet<E> newLinkedHashSet(int initialCapacity) {
return new LinkedHashSet<E>(initialCapacity);
}
public static <E> LinkedHashSet<E> newLinkedHashSet(Iterable<? extends E> elements) {
if (elements instanceof Collection) {
return new LinkedHashSet<E>(cast(elements));
}
LinkedHashSet<E> set = newLinkedHashSet();
addAll(set, elements);
return set;
}
@SuppressWarnings("rawtypes")
public static <E extends Comparable> TreeSet<E> newTreeSet() {
return new TreeSet<E>();
}
@SuppressWarnings("rawtypes")
public static <E extends Comparable> TreeSet<E> newTreeSet(Iterable<? extends E> elements) {
TreeSet<E> set = newTreeSet();
addAll(set, elements);
return set;
}
public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) {
return new TreeSet<E>(comparator);
}
public static <E> Set<E> newIdentityHashSet() {
return Collections.newSetFromMap(MapUtils.<E, Boolean> newIdentityHashMap());
}
public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
return new CopyOnWriteArraySet<E>();
}
public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(Iterable<? extends E> elements) {
Collection<? extends E> elementsCollection = (elements instanceof Collection) ? cast(elements) : ListUtils.newArrayList(elements);
return new CopyOnWriteArraySet<E>(elementsCollection);
}
private static <T> Collection<T> cast(Iterable<T> iterable) {
return (Collection<T>) iterable;
}
private static <T> boolean addAll(Collection<T> addTo, Iterator<? extends T> iterator) {
boolean wasModified = false;
while (iterator.hasNext()) {
wasModified |= addTo.add(iterator.next());
}
return wasModified;
}
public static <T> boolean addAll(Collection<T> addTo, Iterable<? extends T> elementsToAdd) {
if (elementsToAdd instanceof Collection) {
Collection<? extends T> c = cast(elementsToAdd);
return addTo.addAll(c);
}
return addAll(addTo, elementsToAdd.iterator());
}
}
package com.jeesite.common.config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/***配置文件统一读取类****/
@Component
@PropertySource("classpath:constant-${profileActive}.properties")
public class ConstantProperty implements InitializingBean {
//----------------------和风天气-----------------------
@Value("${WEATHER_KEY}")
public String WEATHER_KEY; //请求认证Key
@Value("${WEATHER_BASE_URL}")
public String WEATHER_BASE_URL;//免费请求天气接口地址
@Value("${WEATHER_CACHE_TIME}")
public Integer WEATHER_CACHE_TIME; //天气数据缓存时间,单位:ms
// -------------------和风天气---------------
// -------------------fastDFS文件服务器地址前缀---------------
@Value("${FASTDFS_HOST_PREIX}")
public String FASTDFS_HOST_PREIX; //文件服务器地址请求前缀
@Value("${NGINX_FASTDFS_HOST_PREIX}")
public String NGINX_FASTDFS_HOST_PREIX; //需要跨域的图片文件服务器地址请求前缀,反向代理
// -------------------fastDFS文件服务器地址前缀---------------
//-------------------------AI服务器连接信息------------------------
@Value("${AI_HOST}")
public String AI_HOST; //AI服务器ip
@Value("${AI_IMAGE_PORT}")
public Integer AI_IMAGE_PORT; //AI服务器脸部检测端口
@Value("${AI_FACE_PORT}")
public Integer AI_FACE_PORT; //AI服务器毛孔皱纹检测端口
@Value(("${AI_HTTP_PORT}"))
public String AI_HTTP_PORT;
@Value("${AI_ILL_PORT}")
public Integer AI_ILL_PORT; //病症图检测端口
@Value("${AI_HOST_BASE_URI}")
public String AI_HOST_BASE_URI; //Ai服务器端通讯的tomcat请求路径
@Value("${AI_BASE_FILE_DIR}")
public String AI_BASE_FILE_DIR; //AI服务器端通讯的上传的文件临时目录
//-------------------------AI服务器连接信息------------------------
//---------------------------后台域名、路径信息--------------------------
@Value("${REQ_HOST_PERIX}")
public String REQ_HOST_PERIX; //主机的域名前缀
@Value("${REQ_QRCODE_PATH}")
public String REQ_QRCODE_PATH; // 二维码请求详情查询路径
@Value("${REQ_QRCODE_SHORT_URL}")
public String REQ_QRCODE_SHORT_URL;//二维码请求短连接路径
//---------------------------后台域名、路径信息--------------------------
//---------------------------国外上传视频,商品限制的数量--------------------------
@Value("${ORDINARY_NUM}")
public Integer ORDINARY_NUM; //普通用户上传的最大数目
@Value("${VIP1_NUM}")
public Integer VIP1_NUM; // vip1用户上传的最大数目
@Value("${VIP2_NUM}")
public Integer VIP2_NUM;//Vip2用户上传的最大数目
@Value("${VIP3_PRODUCT_NUM}")
public Integer VIP3_PRODUCT_NUM;//Vip3用户上传商品的最大数目
@Value("${VIP3_VIDEO_NUM}")
public Integer VIP3_VIDEO_NUM;//Vip3用户上传视频的最大数目
//---------------------------国外上传视频,商品限制的数量--------------------------
//---------------------------阿里 OSS 对象存储 配置--------------------------
@Value("${oss.file.endpoint}")
public String oss_file_endpoint; //oss服务器地址
@Value("${oss.file.keyid}")
public String oss_file_keyid; // oss秘钥id
@Value("${oss.file.keysecret}")
public String oss_file_keysecret;//oss秘钥
@Value("${oss.file.bucketname1}")
public String oss_file_bucketname1;//oss秘钥
@Value("${oss.file.filehost}")
public String oss_file_filehost;//oss秘钥
//---------------------------阿里 OSS 对象存储 配置--------------------------
public static String OSS_END_POINT;
public static String OSS_ACCESS_KEY_ID;
public static String OSS_ACCESS_KEY_SECRET;
public static String OSS_BUCKET_NAME1;
public static String OSS_FILE_HOST;
public static String AI_HTTP_REQUEST_PREIX;
//---------------------------微信公众号 APPID 密钥 配置--------------------------
@Value("${wechat_appid}")
public String WECHAT_APPID; //oss服务器地址
@Value("${wechat_secret}")
public String WECHAT_SECRET; // oss秘钥id
//---------------------------检测记录二维码2.0跳转h5地址--------------------------
@Value("${h5_qrcode}")
public String H5_QRCODE; //oss服务器地址
@Value("${h5_skinlink}")
public String H5_SKINLINK; //H5人脸测肤主页
@Value("${is_qrcode_limit}")
public boolean IS_QRCODE_LIMIT; //二维码是否通过语言控制展示
@Override
public void afterPropertiesSet() throws Exception {
OSS_END_POINT = oss_file_endpoint;
OSS_ACCESS_KEY_ID = oss_file_keyid;
OSS_ACCESS_KEY_SECRET = oss_file_keysecret;
OSS_BUCKET_NAME1 = oss_file_bucketname1;
OSS_FILE_HOST = oss_file_filehost;
AI_HTTP_REQUEST_PREIX = "http://" + AI_HOST + ":" + AI_HTTP_PORT;
}
}
package com.jeesite.common.detect;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @Description: 检测项type与描述的枚举类
* @Author: xufangzhou
* @CreateDate: 2018/12/6 11:22
* @UpdateUser: xufangzhou
* @UpdateDate: 2018/12/6 11:22
* @UpdateRemark: 修改内容
* @Version: 1.0
*/
public enum DetectItemEnum {
/**
* 毛孔检测项
*/
PORE_ITEM(11, "pore","粗大毛孔"),
/**
* 斑点检测项
*/
SPOTS_ITEM(12, "spots","色斑"),
/**
* 皱纹检测项
*/
WRINKLE_ITEM(13, "wrinkle","细纹"),
/**
* 肤色检测项
*/
SKIN_COLOR_ITEM(14, "skinColor","肤色"),
/**
* 黑头检测项
*/
BLACK_HEAD_ITEM(15, "blackHead","黑头"),
/**
* 皮肤敏感度
*/
SKIN_SENSITIVITY(16, "skinSensitivity","皮肤敏感度"),
/**
* 病理图
*/
ILLNESS_ITEM(17, "illness","病理");
private DetectItemEnum(Integer type, String itemName,String itemNameCN) {
this.type = type;
this.itemName = itemName;
this.itemNameCN = itemNameCN;
}
public Integer type() {
return type;
}
public String itemName() {
return itemName;
}
public String itemNameCN() {
return itemNameCN;
}
/**
* 检测项类别标记
**/
private Integer type;
/**
* 检测项类别名称
**/
private String itemName;
/**
* 检测项类别中文名
**/
private String itemNameCN;
public static Map getHashMapData(Object object) {
LinkedHashMap<String, Object> map = new LinkedHashMap<>();
Class clazz = DetectItemEnum.class;
Field[] declaredFields = clazz.getDeclaredFields();
for (int i = 0; i < declaredFields.length; i++) {
Field field = declaredFields[i];
try {
String key = field.getName();
if ("type".equals(key) || "itemName".equals(key))
map.put(key, field.get(object));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return map;
}
// 根据value返回枚举类型,主要在switch中使用
public static DetectItemEnum getDetectItemByCodeName(String codeName) {
for (DetectItemEnum itemEnum : values()) {
if (itemEnum.itemName().equals(codeName)) {
return itemEnum;
}
}
return null;
}
// 根据value返回枚举类型,主要在switch中使用
public static DetectItemEnum getDetectItemByType(Integer type) {
for (DetectItemEnum itemEnum : values()) {
if (itemEnum.type() == (type)) {
return itemEnum;
}
}
return null;
}
}
package com.jeesite.common.detect;
/**
* @Description: 脸型的枚举类
* @Author: tanhonghang
*/
public enum FaceTypeEnum {
// 圆脸=Round Face
// 方脸=Square Face
// 椭圆脸=Elliptical Face
// 长脸=Long Face
// 偏圆脸=Round Face
// 偏方脸=Square Face
// 偏椭圆脸=Elliptical Face
// 偏长脸=Long Face
// 左脸=Left Face
// 右脸=Right Face
// 脸型,目前有 0:圆脸 1:方脸 2:椭圆脸 3:长脸 4:偏圆脸 5:偏方脸 6:偏椭圆脸 7:偏长脸 8:左侧脸 9:右侧脸
ROUND_FACE(0, "圆脸"),
SQUARE_FACE(1, "方脸"),
ELLIPTICAL_FACE(2, "椭圆脸"),
LONG_FACE(3, "长脸"),
FEW_ROUND_FACE(4, "偏圆脸"),
FEW_SQUARE_FACE(5, "偏方脸"),
FEW_ELLIPTICAL_FACE(6, "偏椭圆脸"),
FEW_LONG_FACE(7, "偏长脸"),
LEFT_FACE(8, "左侧脸"),
RIGHT_FACE(9, "右侧脸");
private FaceTypeEnum(Integer type, String faceType) {
this.type = type;
this.faceType = faceType;
}
public Integer type() {
return type;
}
public String faceType() {
return faceType;
}
/**
*
**/
private Integer type;
/**
* 检测项类别名称
**/
private String faceType;
// public static Map getHashMapData(Object object) {
// LinkedHashMap<String, Object> map = new LinkedHashMap<>();
// Class clazz = FaceTypeEnum.class;
// Field[] declaredFields = clazz.getDeclaredFields();
// for (int i = 0; i < declaredFields.length; i++) {
// Field field = declaredFields[i];
// try {
// String key = field.getName();
// if ("type".equals(key) || "itemName".equals(key))
// map.put(key, field.get(object));
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
// }
// return map;
// }
// 根据value返回枚举类型,主要在switch中使用
public static String getFaceByType(Integer type) {
for (FaceTypeEnum faceTypeEnum : values()) {
if (faceTypeEnum.type().equals(type)) {
return faceTypeEnum.faceType();
}
}
return null;
}
}
package com.jeesite.common.entity;
/**
* 百度脸型枚举类
*/
public enum BaiDuFaceType {
ROUND(0, "round", "圆脸"),//圆脸
SQUARE(1, "square", "方脸"),//方形脸--->方脸
OVAL(2, "oval", "鹅蛋脸"),//椭圆脸--->鹅蛋脸
TRIANGLE(3, "triangle", "长脸"),//三角形脸--->长脸
HEART(4, "heart", "瓜子脸");//心形脸--->瓜子脸
private Integer type;//数据库存储值
private String val;
private String chin;//中文描述值
private BaiDuFaceType(Integer type, String val, String chin) {
this.type = type;
this.val = val;
this.chin = chin;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public String getChin() {
return chin;
}
public void setChin(String chin) {
this.chin = chin;
}
public String getVal() {
return val;
}
public void setVal(String val) {
this.val = val;
}
// 根据value返回枚举类型,主要在switch中使用
public static BaiDuFaceType getByVal(String val) {
for (BaiDuFaceType faceType : values()) {
if (faceType.getVal().equalsIgnoreCase(val)) {
return faceType;
}
}
return BaiDuFaceType.SQUARE;
}
public static BaiDuFaceType getByType(Integer type) {
for (BaiDuFaceType faceType : values()) {
if (faceType.getType() == type) {
return faceType;
}
}
return BaiDuFaceType.SQUARE;
}
}
package com.jeesite.common.entity;
import java.io.Serializable;
/**
* @Description: 公共参数请求基类
* @Author: xufangzhou
* @CreateDate: 2019/1/4 14:48
* @UpdateUser: xufangzhou
* @UpdateDate: 2019/1/4 14:48
* @UpdateRemark: 修改内容
* @Version: 1.0
*/
public class BaseReqEntity implements Serializable {
protected String versionNum; // 版本号
protected String language; // 语言
protected String sn; //上传机身号
protected String appId; //上传所属应用编码
public String getVersionNum() {
return versionNum;
}
public void setVersionNum(String versionNum) {
this.versionNum = versionNum;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getSn() {
return sn;
}
public void setSn(String sn) {
this.sn = sn;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
}
package com.jeesite.common.entity;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager implements X509TrustManager {
// 检查客户端证书
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.exec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
/**
* Command
* @author ThinkGem
* @version 2017年2月17日
*/
public class CommandUtils {
public static String execute(String command) throws IOException {
return execute(command, "GBK");
}
public static String execute(String command, String charsetName) throws IOException {
Process process = Runtime.getRuntime().exec(command);
// 记录dos命令的返回信息
StringBuffer stringBuffer = new StringBuffer();
// 获取返回信息的流
InputStream in = process.getInputStream();
Reader reader = new InputStreamReader(in, charsetName);
BufferedReader bReader = new BufferedReader(reader);
String res = bReader.readLine();
while (res != null) {
stringBuffer.append(res);
stringBuffer.append("\n");
res = bReader.readLine();
}
bReader.close();
reader.close();
return stringBuffer.toString();
}
}
//package com.jeesite.common.fastdfs;
//
//import com.github.tobato.fastdfs.domain.FileInfo;
//import com.github.tobato.fastdfs.domain.StorePath;
//import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
//import com.github.tobato.fastdfs.service.FastFileStorageClient;
//import com.jeesite.common.lang.StringUtils;
//import org.apache.commons.io.FilenameUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//import org.springframework.web.multipart.MultipartFile;
//
//import java.io.*;
//
///**
// * FastDFS文件上传下载包装类
// *
// * @author xufangzhou
// * @Version 2018年11月21日
// */
//@Component
//public class FastDFSClientWrapper {
// private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);
//
// @Autowired
// private FastFileStorageClient storageClient;
//
// /*
// * @Autowired private AppConfig appconfig; //项目参数配置
// */
//
//
// /**
// * 上传文件
// *
// * @param file 文件对象
// * @return 文件访问地址
// * @throws IOException
// */
// public String uploadFile(MultipartFile file) {
// try {
// StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(),
// FilenameUtils.getExtension(file.getOriginalFilename()), null);
// String filePath = getResAccessUrl(storePath);
// logger.info("文件上传成功! 原文件地址为: {},文件存储ID为: {}", file.getOriginalFilename(), filePath);
// return filePath;
// } catch (IOException e) {
// logger.error("文件上传失败! 原文件地址为: {}", file.getOriginalFilename());
// e.printStackTrace();
// }
// return null;
// }
//
// public String uploadFile(File file) {
// try {
// InputStream inputStream = new FileInputStream(file);
//
// StorePath storePath = storageClient.uploadFile(inputStream, file.length(), FilenameUtils.getExtension(file.getName()), null);
// String filePath = getResAccessUrl(storePath);
// logger.info("文件上传成功! 原文件地址为: {},文件存储ID为: {}", file.getAbsolutePath(), filePath);
// return filePath;
// } catch (FileNotFoundException e) {
// logger.error("文件上传失败! 原文件地址为: {}", file.getAbsolutePath());
// e.printStackTrace();
// }
// return null;
// }
//
// private String getResAccessUrl(StorePath storePath) {
// String fileUrl = storePath.getFullPath();
// return fileUrl;
// }
//
//
// /**
// * 删除文件
// *
// * @param fileUrl 文件访问地址
// * @return
// **/
// public void deleteFile(String fileUrl) {
// if (StringUtils.isEmpty(fileUrl))
// return;
// try {
// StorePath storePath = StorePath.praseFromUrl(fileUrl);
// storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
// logger.info("文件删除成功! 文件ID为: {}", fileUrl);
// } catch (Exception e) {
// e.printStackTrace();
// logger.error("文件删除失败::" + fileUrl);
// }
// }
//
//
// public byte[] downFile(String fileUrl) throws Exception {
// if (StringUtils.isEmpty(fileUrl))
// return null;
// try {
// DownloadByteArray downloadByteArray = new DownloadByteArray();
// StorePath storePath = StorePath.praseFromUrl(fileUrl);
// byte[] bytes = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), downloadByteArray);
// logger.info("文件下载成功! 文件ID为: {}", fileUrl);
// return bytes;
// } catch (Exception e) {
// e.printStackTrace();
// logger.error("文件下载失败::" + fileUrl);
// throw new Exception("文件下载失败!" + e.getMessage());
// }
// }
//
// public boolean checkFileExist(String fileUrl) throws Exception {
// if (StringUtils.isEmpty(fileUrl))
// return false;
// try {
// StorePath storePath = StorePath.praseFromUrl(fileUrl);
// FileInfo fileInfo = storageClient.queryFileInfo(storePath.getGroup(), storePath.getPath());
// if (null != fileInfo && fileInfo.getFileSize() > 0) {
// return true;
// }
//
// } catch (Exception e) {
// //e.printStackTrace();
// logger.error("文件信息获取失败::" + e.getMessage());
// }
// return false;
// }
//
//
//}
package com.jeesite.common.fastdfs;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.oss.AliyunFileUrlUtil;
import com.jeesite.common.oss.AliyunOSSUtil;
import com.jeesite.modules.sys.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
/**
* @Description: 上传到文件服务器FastDFS的工具类
* @Author: xufangzhou
* @CreateDate: 2019/3/15 15:36
* @UpdateUser: xufangzhou
* @UpdateDate: 2019/3/15 15:36
* @UpdateRemark: 修改内容
* @Version: 1.0
*/
@Component
public class UploadDFSUtils {
/**
* 多文件上传,获取文件名(key)和文件路径(value)的Map数据
*
* @param request
* @param sn
* @return
* @throws
* @author xfz
* @date 2019/3/15 16:42
*/
public Map<String, String> uploadFile(HttpServletRequest request, String sn) throws Exception {
//不用MultipartFile是为了防止没有上传文件的情况出现
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//StringBuffer stringBuffer = new StringBuffer();
Map<String, String> fileData = new HashMap<>();
//设置编码
commonsMultipartResolver.setDefaultEncoding("utf-8");
try {
//判断是否有文件上传
if (commonsMultipartResolver.isMultipart(request)) {//有文件上传时
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> files = multiRequest.getFiles("files");
//Iterator<String> fileNames = multiRequest.getFileNames();
//文件上传成功,拼接多个文件地址信息,用逗号","隔开
Date date = new Date();
for (MultipartFile multipartFile : files) {
String originalFilename = multipartFile.getOriginalFilename();
String uploadPath = AliyunFileUrlUtil.generateAppLogFileUrl(sn, date);
uploadPath = AliyunOSSUtil.upload(multipartFile, uploadPath);
fileData.put(originalFilename, uploadPath);
}
}
} catch (Exception e) {
e.printStackTrace();
throw new Exception("文件上传失败!" + e.getMessage());
}
return fileData;
}
public String uploadImgeBase64(String fileBase64, HttpServletRequest request,User ownUser) throws Exception {
String UploadPath = null;
try {
if (StringUtils.isBlank(fileBase64)) {
return null;
}
String localDirPath = request.getServletContext().getRealPath("/") + "/upload/";
File Dir = new File(localDirPath);
if (!Dir.exists()) {
Dir.mkdirs();
}
String largeFileName = UUID.randomUUID().toString() + ".jpg";
String localPath1 = localDirPath + largeFileName;
FileUtils.writeToFileByImageBase64(localPath1, fileBase64);
//文件上传到FastDFS
String fileUrl = AliyunFileUrlUtil.generateAdminNotVideoFileUrl(ownUser, AliyunFileUrlUtil.AD_FILE_TYPE.PICTURE, ".jpg");
UploadPath = AliyunOSSUtil.upload(fileBase64, request, fileUrl);
} catch (Exception e) {
if (StringUtils.isNotBlank(UploadPath)) {
AliyunOSSUtil.deleteFileSingle(UploadPath);
}
throw new Exception("文件上传失败!", e);
}
return UploadPath;
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.idgen;
import java.security.SecureRandom;
import java.util.UUID;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.lang.StringUtils;
/**
* 封装各种生成唯一性ID算法的工具类.
* @author ThinkGem
* @version 2014-8-19
*/
public class IdGenerate {
private static SecureRandom random = new SecureRandom();
private static IdWorker idWorker = new IdWorker(-1, -1);
/**
* 生成UUID, 中间无-分割.
*/
public static String uuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
/**
* 使用SecureRandom随机生成Long.
*/
public static long randomLong() {
return Math.abs(random.nextLong());
}
/**
* 基于Base62编码的SecureRandom随机生成bytes.
*/
public static String randomBase62(int length) {
byte[] randomBytes = new byte[length];
random.nextBytes(randomBytes);
return EncodeUtils.encodeBase62(randomBytes);
}
/**
* 获取新唯一编号(18为数值)
* 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序。
* 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
*/
public static String nextId() {
return String.valueOf(idWorker.nextId());
}
/**
* 获取新代码编号
*/
public static String nextCode(String code){
//如果编号过长,则重新生成
if(code!=null&&code.length()>28){
code = code.substring(0,5)+UUID.randomUUID().toString().substring(0,3);
}
if (code != null){
String str = code.trim();
int len = str.length() - 1;
int lastNotNumIndex = 0;
for (int i = len; i >= 0; i--) {
if (!(str.charAt(i) >= '0' && str.charAt(i) <= '9')) {
lastNotNumIndex = i;
break;
}
}
// 如果最后一位是数字,并且last索引位置还在最后,则代表是纯数字,则最后一个不是数字的索引为-1
if ((str.charAt(len) >= '0' && str.charAt(len) <= '9') && (lastNotNumIndex == len)) {
lastNotNumIndex = -1;
}
String prefix = str.substring(0, lastNotNumIndex + 1);
String numStr = str.substring(lastNotNumIndex + 1, str.length());
long num = ObjectUtils.toLong(numStr);
// System.out.println("处理前:"+str);
str = prefix + StringUtils.leftPad(String.valueOf(num + 1), numStr.length(), "0")+UUID.randomUUID().toString().replace("-", "").substring(0,1);
// System.out.println("处理后:"+str);
return str;
}
return null;
}
// public static void main(String[] args) {
// System.out.println(uuid());
// System.out.println(nextId());
// System.out.println(nextCode("8"));
// System.out.println(nextCode("09"));
// System.out.println(nextCode("009"));
// System.out.println(nextCode("E09"));
// System.out.println(nextCode("EC09"));
// System.out.println(nextCode("EC0101"));
// System.out.println(nextCode("EC0109"));
// System.out.println(nextCode("EC02T03"));
// System.out.println(nextCode("EC02T099"));
// System.out.println(nextCode("EC02T100"));
// System.out.println(nextCode("EC02T10A"));
//// // 数值型ID重复验证测试
//// Set<String> set = SetUtils.newHashSet();
//// try{
//// for (int i=0; i<100; i++){
//// String id = String.valueOf(nextId());
//// if (set.contains(id)){
//// throw new Exception(id + " exists");
//// }
//// set.add(id);
//// System.out.println(id);
//// Thread.sleep(100);
//// }
//// }catch (Exception e) {
//// e.printStackTrace();
//// }
// }
//public static void main(String[] args) {
// String starCode = "GDJHY";
// for(int i=0;i<=1000;i++){
// starCode = nextCode(starCode);
// System.out.println(starCode);
// }
//}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.idgen;
import java.util.Random;
/**
* 来自于twitter项目snowflake的id产生方案,全局唯一,时间有序。
* 64位ID (42(毫秒)+5(机器ID)+5(业务编码)+12(重复累加))
* https://github.com/twitter/snowflake/blob/scala_28/src/main/
* scala/com/twitter/service/snowflake/IdWorker.scala
*/
public class IdWorker {
private final static long twepoch = 1288834974657L;
// 机器标识位数
private final static long workerIdBits = 5L;
// 数据中心标识位数
private final static long datacenterIdBits = 5L;
// 机器ID最大值
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 数据中心ID最大值
private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒内自增位
private final static long sequenceBits = 12L;
// 机器ID偏左移12位
private final static long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private final static long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private final static long timestampLeftShift = sequenceBits + workerIdBits
+ datacenterIdBits;
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
private static long lastTimestamp = -1L;
private long sequence = 0L;
private final long workerId;
private final long datacenterId;
public IdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
if (workerId == -1){
this.workerId = new Random().nextInt((int)maxWorkerId);
}else{
throw new IllegalArgumentException(
"worker Id can't be greater than %d or less than 0");
}
}else{
this.workerId = workerId;
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
if (datacenterId == -1){
this.datacenterId = new Random().nextInt((int)maxDatacenterId);
}else{
throw new IllegalArgumentException(
"datacenter Id can't be greater than %d or less than 0");
}
}else{
this.datacenterId = datacenterId;
}
}
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
try {
throw new Exception(
"Clock moved backwards. Refusing to generate id for "
+ (lastTimestamp - timestamp) + " milliseconds");
} catch (Exception e) {
e.printStackTrace();
}
}
if (lastTimestamp == timestamp) {
// 当前毫秒内,则+1
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
// 当前毫秒内计数满了,则等待下一秒
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
lastTimestamp = timestamp;
// ID偏移组合生成最终的ID,并返回ID
long nextId = ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
return nextId;
}
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
// //////////// test ////////////
//
// public static void main(String[] args) throws Exception {
// final Set<Long> set = SetUtils.newHashSet();
//
// final IdWorker w1 = new IdWorker(-1, -1);
// final IdWorker w2 = new IdWorker(-1, -1);
// final CyclicBarrier cdl = new CyclicBarrier(100);
//
// for (int i = 0; i < 1000; i++) {
// new Thread(new Runnable() {
// @Override
// public void run() {
// try {
// cdl.await();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (BrokenBarrierException e) {
// e.printStackTrace();
// }
//
// // id
// Long id = w1.nextId();
// if (set.contains(id)){
// System.out.println(id + " exists");
// }
// set.add(id);
// System.out.println(id);
//
// // id2
// Long id2 = w2.nextId();
// if (set.contains(id2)){
// System.out.println(id2 + " exists");
// }
// set.add(id2);
// System.out.println(id2);
// }
// }).start();
// }
// try {
// TimeUnit.SECONDS.sleep(5);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
}
\ No newline at end of file
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.image;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import org.patchca.background.BackgroundFactory;
import org.patchca.color.ColorFactory;
import org.patchca.filter.predefined.CurvesRippleFilterFactory;
import org.patchca.filter.predefined.DiffuseRippleFilterFactory;
import org.patchca.filter.predefined.DoubleRippleFilterFactory;
import org.patchca.filter.predefined.MarbleRippleFilterFactory;
import org.patchca.filter.predefined.WobbleRippleFilterFactory;
import org.patchca.font.RandomFontFactory;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.text.renderer.BestFitTextRenderer;
import org.patchca.utils.encoder.EncoderHelper;
import org.patchca.word.RandomWordFactory;
/**
* 验证码工具
* @author ThinkGem
* @version 2017年12月23日
*/
public class CaptchaUtils {
private static Random random = new Random();
private static ConfigurableCaptchaService ccs;
private static WobbleRippleFilterFactory wrff; // 摆波纹
private static DoubleRippleFilterFactory doff; // 双波纹
private static CurvesRippleFilterFactory crff; // 曲线波纹
private static DiffuseRippleFilterFactory drff; // 漫纹波
private static MarbleRippleFilterFactory mrff; // 大理石
private static void initialize(){
if (ccs == null){
synchronized (CaptchaUtils.class) {
if (ccs == null){
// 配置初始化
ccs = new ConfigurableCaptchaService();
// 设置图片大小
ccs.setWidth(100);
ccs.setHeight(28);
// 设置文字数量
RandomWordFactory wf = new RandomWordFactory();
wf.setCharacters("ABDEFGHKMNRSWX2345689");
wf.setMinLength(4);
wf.setMaxLength(4);
ccs.setWordFactory(wf);
// 设置字体大小
RandomFontFactory ff = new RandomFontFactory();
ff.setMinSize(28);
ff.setMaxSize(28);
ccs.setFontFactory(ff);
// 设置文字渲染边距
BestFitTextRenderer tr = new BestFitTextRenderer();
tr.setTopMargin(3);
tr.setRightMargin(3);
tr.setBottomMargin(3);
tr.setLeftMargin(3);
ccs.setTextRenderer(tr);
// 设置字体颜色
ccs.setColorFactory(new ColorFactory() {
@Override
public Color getColor(int x) {
int r = random.nextInt(90);
int g = random.nextInt(90);
int b = random.nextInt(90);
return new Color(r, g, b);
}
});
// 设置背景
ccs.setBackgroundFactory(new BackgroundFactory() {
@Override
public void fillBackground(BufferedImage image) {
Graphics graphics = image.getGraphics();
// 验证码图片的宽高
int imgWidth = image.getWidth();
int imgHeight = image.getHeight();
// 填充为白色背景
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, imgWidth, imgHeight);
// 画 50 个噪点(颜色及位置随机)
for (int i = 0; i < 50; i++) {
// 随机颜色
int rInt = random.nextInt(100)+50;
int gInt = random.nextInt(100)+50;
int bInt = random.nextInt(100)+50;
graphics.setColor(new Color(rInt, gInt, bInt));
// 随机位置
int xInt = random.nextInt(imgWidth - 3);
int yInt = random.nextInt(imgHeight - 2);
// 随机旋转角度
int sAngleInt = random.nextInt(360);
int eAngleInt = random.nextInt(360);
// 随机大小
int wInt = random.nextInt(6);
int hInt = random.nextInt(6);
// 填充背景
graphics.fillArc(xInt, yInt, wInt, hInt, sAngleInt, eAngleInt);
// 画5条干扰线
if (i % 10 == 0) {
int xInt2 = random.nextInt(imgWidth);
int yInt2 = random.nextInt(imgHeight);
graphics.drawLine(xInt, yInt, xInt2, yInt2);
}
}
}
});
// 效果初始化
wrff = new WobbleRippleFilterFactory(); // 摆波纹
doff = new DoubleRippleFilterFactory(); // 双波纹
crff = new CurvesRippleFilterFactory(ccs.getColorFactory()); // 曲线波纹
drff = new DiffuseRippleFilterFactory(); // 漫纹波
mrff = new MarbleRippleFilterFactory(); // 大理石
}
}
}
}
/**
* 生成验证码
* @param request
* @param response
* @throws IOException
* @return 验证码字符
*/
public static String generateCaptcha(OutputStream outputStream) throws IOException{
// 初始化设置
initialize();
// 随机选择一个样式
switch (random.nextInt(3)) {
case 0:
ccs.setFilterFactory(wrff); // 摆波纹
break;
case 1:
ccs.setFilterFactory(doff); // 双波纹
break;
case 2:
ccs.setFilterFactory(crff); // 曲线波纹
break;
case 3:
ccs.setFilterFactory(drff); // 漫纹波
break;
case 4:
ccs.setFilterFactory(mrff); // 大理石
break;
}
// 生成验证码
String s = EncoderHelper.getChallangeAndWriteImage(ccs, "png", outputStream);
// System.out.println(s);
return s;
}
// public static void main(String[] args) throws IOException {
//
// FileOutputStream fos = new FileOutputStream("x:\\captcha.png");
// String s = generateCaptcha(fos);
// System.out.println(s);
// fos.close();
//
// }
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.image;
import java.io.File;
import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.lang.Rational;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.GpsDirectory;
/**
* 图片地理信息获取
* @author ThinkGem
*/
public class ImageGeo {
public double lat = 0.0;
public double lon = 0.0;
public double alt = 0.0;
public boolean error = false;
public ImageGeo(String filename) {
try {
error = false;
File jpegFile = new File(filename);
Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
GpsDirectory gpsdir = (GpsDirectory) metadata.getDirectoriesOfType(GpsDirectory.class);
Rational latpart[] = gpsdir.getRationalArray(GpsDirectory.TAG_LATITUDE);
Rational lonpart[] = gpsdir.getRationalArray(GpsDirectory.TAG_LONGITUDE);
String northing = gpsdir.getString(GpsDirectory.TAG_LATITUDE_REF);
String easting = gpsdir.getString(GpsDirectory.TAG_LONGITUDE_REF);
try {
alt = gpsdir.getDouble(GpsDirectory.TAG_ALTITUDE);
} catch (Exception ex) {}
double latsign = 1.0d;
if (northing.equalsIgnoreCase("S")) {
latsign = -1.0d;
}
double lonsign = 1.0d;
if (easting.equalsIgnoreCase("W")) {
lonsign = -1.0d;
}
lat = (Math.abs(latpart[0].doubleValue()) + latpart[1].doubleValue() / 60.0d + latpart[2].doubleValue() / 3600.0d) * latsign;
lon = (Math.abs(lonpart[0].doubleValue()) + lonpart[1].doubleValue() / 60.0d + lonpart[2].doubleValue() / 3600.0d) * lonsign;
if (Double.isNaN(lat) || Double.isNaN(lon)) {
error = true;
}
} catch (Exception ex) {
error = true;
}
System.out.println(filename + ": (" + lat + ", " + lon + ")");
}
// public static void main(String[] args) {
// ImageGeo imageGeo = new ImageGeo(ImageGeo.class.getResource("IMAG0068.jpg").getFile());
// System.out.println(imageGeo.lon + "," + imageGeo.lat);
// }
}
package com.jeesite.common.image;
import com.jeesite.common.collect.MapUtils;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Map;
/**
* @Description: 图片工具类
* @Author: tanhonghang
* @CreateDate: 2018/6/13 11:51
*
*/
public class ImageUtils {
/**
* 根据图片获取横竖像素比例
* @return
*/
public static Map<String, Object> getImagePixel(File file){
FileChannel fc = null;
if(file.exists() && file.isFile()){
try {
FileInputStream fs = new FileInputStream(file);
fc = fs.getChannel();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
int width = bi.getWidth();
int height = bi.getHeight();
Map<String, Object> map = MapUtils.newHashMap();
map.put("width",width);
map.put("height",height);
return map;
// return width/(height*1.0);
}
}
package com.jeesite.common.image;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;
import java.util.UUID;
public class QrCodeUtils {
private static final String CHARSET = "utf-8";
private static final String FORMAT = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int LOGO_WIDTH = 60;
// LOGO高度
private static final int LOGO_HEIGHT = 60;
private static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (logoPath == null || "".equals(logoPath)) {
return image;
}
// 插入图片
QrCodeUtils.insertImage(image, logoPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source 二维码图片
* @param logoPath LOGO图片地址
* @param needCompress 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
File file = new File(logoPath);
if (!file.exists()) {
throw new Exception("logo file not found.");
}
Image src = ImageIO.read(new File(logoPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > LOGO_WIDTH) {
width = LOGO_WIDTH;
}
if (height > LOGO_HEIGHT) {
height = LOGO_HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 生成二维码(内嵌LOGO)
* 二维码文件名随机,文件名可能会有重复
*
* @param content 内容
* @param logoPath LOGO地址
* @param destPath 存放目录
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static File encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
mkdirs(destPath);
String fileName = UUID.randomUUID() + "." + FORMAT.toLowerCase();
File file = new File(destPath + "/" + fileName);
ImageIO.write(image, FORMAT, file);
return file;
}
/**
* 生成二维码(内嵌LOGO)
* 调用者指定二维码文件名
*
* @param content 内容
* @param logoPath LOGO地址
* @param destPath 存放目录
* @param fileName 二维码文件名
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
mkdirs(destPath);
fileName = fileName.substring(0, fileName.indexOf(".") > 0 ? fileName.indexOf(".") : fileName.length())
+ "." + FORMAT.toLowerCase();
ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));
return fileName;
}
/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.
* (mkdir如果父目录不存在则会抛出异常)
*
* @param destPath 存放目录
*/
public static void mkdirs(String destPath) {
File file = new File(destPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content 内容
* @param logoPath LOGO地址
* @param destPath 存储地址
* @throws Exception
*/
public static File encode(String content, String logoPath, String destPath) throws Exception {
return QrCodeUtils.encode(content, logoPath, destPath, false);
}
/**
* 生成二维码
*
* @param content 内容
* @param destPath 存储地址
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static File encode(String content, String destPath, boolean needCompress) throws Exception {
return QrCodeUtils.encode(content, null, destPath, needCompress);
}
/**
* 生成二维码
*
* @param content 内容
* @param destPath 存储地址
* @throws Exception
*/
public static File encode(String content, String destPath) throws Exception {
return QrCodeUtils.encode(content, null, destPath, false);
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content 内容
* @param logoPath LOGO地址
* @param output 输出流
* @param needCompress 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String logoPath, OutputStream output, boolean needCompress)
throws Exception {
BufferedImage image = QrCodeUtils.createImage(content, logoPath, needCompress);
ImageIO.write(image, FORMAT, output);
}
/**
* 生成二维码
*
* @param content 内容
* @param output 输出流
* @throws Exception
*/
public static void encode(String content, OutputStream output) throws Exception {
QrCodeUtils.encode(content, null, output, false);
}
/**
* 解析二维码
*
* @param file 二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
//优化精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//复杂模式,开启PURE_BARCODE模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 解析二维码
*
* @param path 二维码图片地址
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
return QrCodeUtils.decode(new File(path));
}
// public static void main(String[] args) throws Exception {
// String text = "http://mirrordemo.idankee.com/f/sUrl/ZNJRrq";
// //String[] shortUrl = ShortUrlGenerator.getShortUrl(text);
// //不含Logo
// QrCodeUtils.encode(text, null, "D:\\", true);
// //含Logo,不指定二维码图片名
// //QrCodeUtils2.encode(text, "/Users/ianly/Documents/picture/google-icon.jpg", "/Users/ianly/Documents/picture/", true);
// //含Logo,指定二维码图片名
// //QrCodeUtils2.encode(text, "/Users/ianly/Documents/picture/google-icon.jpg", "/Users/ianly/Documents/picture", "qrcode", true);
// }
}
package com.jeesite.common.image;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.security.MessageDigest;
import javax.security.sasl.SaslException;
/**
* 短链接生成器
*
* @author zdz8207
* @version v1.0, 2017-01-11
* @since v1.0
*/
public class ShortUrlGenerator {
/**
* 生成短链接
*
* @param url 长链接
* @return 四个短地址数组,取任意一个即可
*/
private final static Logger logger = LoggerFactory.getLogger(ShortUrlGenerator.class);
public static String[] getShortUrl(String url) {
// 可以自定义生成 MD5 加密字符传前的混合 KEY
String key = "zdz8207";
// 要使用生成 URL 的字符
String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h",
"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "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"
};
// 对传入网址进行 MD5 加密
String sMD5EncryptResult = getMD5(key + url);
String hex = sMD5EncryptResult;
String[] resUrl = new String[4];
//生成4个短地址,8位一组
for (int i = 0; i < 4; i++) {
//避免超过32位长度,出现越界
int m;
if ((m = i * 8 + 8) > hex.length()) {
m = hex.length();
}
// 把加密字符按照 8 位一组 16 进制与 0x3FFFFFFF 进行位与运算
// String sTempSubString = "";
// if(hex.length() == 31)
// sTempSubString = hex.substring(i * 8, i * 8 + 7);
// else
// sTempSubString = hex.substring(i * 8, i * 8 + 8);
String sTempSubString = hex.substring(i * 8, m);
// 这里需要使用 long 型来转换,因为 Inteper.parseInt() 只能处理 31 位 , 首位为符号位 , 如果不用
// long ,则会越界
long lHexLong = 0x3FFFFFFF & Long.parseLong(sTempSubString, 16);
String outChars = "";
//生成6次-6位短地址
for (int j = 0; j < 6; j++) {
// 把得到的值与 0x0000003D 进行位与运算,取得字符数组 chars 索引
long index = 0x0000003D & lHexLong;
// 把取得的字符相加
outChars += chars[(int) index];
// 每次循环按位右移 5 位
lHexLong = lHexLong >> 5;
}
// 把字符串存入对应索引的输出数组
resUrl[i] = outChars;
}
return resUrl;
}
/**
* 根据短链接获得key值
*
* @param shortUrl 短链接
* @return key值 String
*/
public static String getShortKey(String shortUrl) {
String key = shortUrl.substring(shortUrl.lastIndexOf("/") + 1, shortUrl.length());
return key;
}
/**
* 对字符串md5加密
*
* @param str
* @return
* @throws SaslException
*/
public static String getMD5(String str) {
try {
// 生成一个MD5加密计算摘要
MessageDigest md = MessageDigest.getInstance("MD5");
// 计算md5函数
md.update(str.getBytes());
// digest()最后确定返回md5 hash值,返回值为8为字符串。因为md5 hash值是16位的hex值,实际上就是8位的字符
// BigInteger函数则将8位的字符串转换成16位hex值,用字符串来表示;得到字符串形式的hash值
return new BigInteger(1, md.digest()).toString(16);
} catch (Exception e) {
System.out.println("MD5加密出现错误");
return "";
}
}
//测试函数
public static void main(String[] args) {
// 长连接:http://www.cnblogs.com/zdz8207/
// 解析后的四个短地址数组,取任意一个即可
String sLongUrl = "http://mirror.hoyar.com.cn/f/mobile/getRecordView?recordCode=1133655894260084736";
String[] aResult = getShortUrl(sLongUrl);
// 打印出结果,四个短地址数组,取任意一个即可
for (int i = 0; i < aResult.length; i++) {
System.out.println(aResult[i]);
}
// FjIjqm
// bEjyay
// jaUJFf
// ZNBrEz
//根据短链接获得key值
String key = getShortKey("http://www.cnblogs.com/?a=FjIjqm11111");
System.out.println("key=" + key);//key=FjIjqm
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 条形码和二维码编码解码
* @author ThinkGem
* @version 2014-02-28
*/
public class ZxingUtils {
/**
* 条形码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode(String contents, int width, int height, String imgPath) {
int codeWidth = 3 + // start guard
(7 * 6) + // left bars
5 + // middle guard
(7 * 6) + // right bars
3; // end guard
codeWidth = Math.max(codeWidth, width);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, codeWidth, height, null);
MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 条形码解码
*
* @param imgPath
* @return String
*/
public static String decode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 二维码编码
*
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static void encode2(String contents, int width, int height, String imgPath) {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToPath(bitMatrix, "png", new File(imgPath).toPath());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 二维码解码
*
* @param imgPath
* @return String
*/
public static String decode2(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("the decode image may be not exit.");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "GBK");
result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
//
// // 条形码
// String imgPath = "target\\zxing_EAN13.png";
// String contents = "6923450657713";
// int width = 105, height = 50;
//
// ZxingUtils.encode(contents, width, height, imgPath);
// System.out.println("finished zxing EAN-13 encode.");
//
// String decodeContent = ZxingUtils.decode(imgPath);
// System.out.println("解码内容如下:" + decodeContent);
// System.out.println("finished zxing EAN-13 decode.");
//
// // 二维码
String imgPath2 = "target\\zxing.png";
String contents2 = "Hello Gem, welcome to Zxing!" + "\nBlog [ http://thinkgem.iteye.com ]" + "\nEMail [ thinkgem@163.com ]";
int width2 = 300, height2 = 300;
ZxingUtils.encode2(contents2, width2, height2, imgPath2);
System.out.println("finished zxing encode.");
//
// String decodeContent2 = ZxingUtils.decode2(imgPath2);
// System.out.println("解码内容如下:" + decodeContent2);
// System.out.println("finished zxing decode.");
//
}
}
\ No newline at end of file
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.io;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 数据流工具类
* @author ThinkGem
*/
public class IOUtils extends org.apache.commons.io.IOUtils {
/**
* 根据文件路径创建文件输入流处理 以字节为单位(非 unicode )
* @param path
* @return
*/
public static FileInputStream getFileInputStream(String filepath) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(filepath);
} catch (FileNotFoundException e) {
System.out.println("错误信息:文件不存在");
e.printStackTrace();
}
return fileInputStream;
}
/**
* 根据文件对象创建文件输入流处理 以字节为单位(非 unicode )
* @param path
* @return
*/
public static FileInputStream getFileInputStream(File file) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
System.out.println("错误信息:文件不存在");
e.printStackTrace();
}
return fileInputStream;
}
/**
* 根据文件对象创建文件输出流处理 以字节为单位(非 unicode )
* @param file
* @param append true:文件以追加方式打开,false:则覆盖原文件的内容
* @return
*/
public static FileOutputStream getFileOutputStream(File file, boolean append) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file, append);
} catch (FileNotFoundException e) {
System.out.println("错误信息:文件不存在");
e.printStackTrace();
}
return fileOutputStream;
}
/**
* 根据文件路径创建文件输出流处理 以字节为单位(非 unicode )
* @param path
* @param append true:文件以追加方式打开,false:则覆盖原文件的内容
* @return
*/
public static FileOutputStream getFileOutputStream(String filepath, boolean append) {
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(filepath, append);
} catch (FileNotFoundException e) {
System.out.println("错误信息:文件不存在");
e.printStackTrace();
}
return fileOutputStream;
}
/**
* Closes a <code>Closeable</code> unconditionally.
*/
public static void closeQuietly(final InputStream input) {
closeQuietly((Closeable) input);
}
/**
* Closes a <code>Closeable</code> unconditionally.
*/
public static void closeQuietly(final Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (final IOException ioe) {
// ignore
}
}
}
\ No newline at end of file
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.io;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import com.jeesite.common.collect.SetUtils;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.lang.StringUtils;
/**
* Properties工具类, 可载入多个properties、yml文件,
* 相同的属性在最后载入的文件中的值将会覆盖之前的值,
* 取不到从System.getProperty()获取。
* @author ThinkGem
* @version 2017-12-30
*/
public class PropertiesUtils {
// 默认加载的文件,可通过继承覆盖(若有相同Key,优先加载后面的)
public static final String[] DEFAULT_CONFIG_FILE = new String[]{
"classpath:config/application.yml", "classpath:application.yml"};
private static Logger logger = PropertiesUtils.initLogger();
private final Set<String> configSet = SetUtils.newLinkedHashSet();
private final Properties properties = new Properties();
/**
* 当前类的实例持有者(静态内部类,延迟加载,懒汉式,线程安全的单例模式)
*/
private static final class PropertiesLoaderHolder {
private static PropertiesUtils INSTANCE;
static {
releadInstance();
}
public static void releadInstance(){
// 获取平台及模块相关的配置文件
Set<String> configSet = SetUtils.newLinkedHashSet();
Resource[] resources = ResourceUtils.getResources("classpath*:/config/jeesite-*.*");
for(Resource resource : resources){
configSet.add("classpath:config/"+resource.getFilename());
}
//configSet.add("classpath:config/jeesite.yml");
// 获取全局设置默认的配置文件(以下是支持环境配置的属性文件)
Set<String> set = SetUtils.newLinkedHashSet();
for (String configFile : DEFAULT_CONFIG_FILE){
set.add(configFile);
}
// 获取 spring.config.location 外部自定义的配置文件
String customConfigs = System.getProperty("spring.config.location");
if (StringUtils.isNotBlank(customConfigs)){
for (String customConfig : StringUtils.split(customConfigs, ",")){
if (!customConfig.contains("$")){
customConfig = org.springframework.util.StringUtils.cleanPath(customConfig);
if (!ResourceUtils.isUrl(customConfig)){
customConfig = ResourceUtils.FILE_URL_PREFIX + customConfig;
}
}
set.add(customConfig);
}
}
// 获取 spring.profiles.active 活动环境名称的配置文件
String[] configFiles = set.toArray(new String[set.size()]);
String profiles = System.getProperty("spring.profiles.active");
if (StringUtils.isBlank(profiles)){
PropertiesUtils propsTemp = new PropertiesUtils(configFiles);
profiles = propsTemp.getProperty("spring.profiles.active");
}
for (String location : configFiles){
configSet.add(location);
if (StringUtils.isNotBlank(profiles)){
if (location.endsWith(".properties")){
configSet.add(StringUtils.substringBeforeLast(location, ".properties")
+ "-" + profiles + ".properties");
}else if (location.endsWith(".yml")){
configSet.add(StringUtils.substringBeforeLast(location, ".yml")
+ "-" + profiles + ".yml");
}
}
}
configFiles = configSet.toArray(new String[configSet.size()]);
logger.debug("Loading jeesite config: {}", (Object)configFiles);
INSTANCE = new PropertiesUtils(configFiles);
}
}
/**
* 载入多个文件,路径使用Spring Resource格式,相同的属性在最后载入的文件中的值将会覆盖之前的值。
*/
public PropertiesUtils(String... configFiles) {
for (String location : configFiles) {
try {
Resource resource = ResourceUtils.getResource(location);
if (resource.exists()){
if (location.endsWith(".properties")){
try (InputStreamReader is = new InputStreamReader(resource.getInputStream(), "UTF-8")){
properties.load(is);
configSet.add(location);
} catch (IOException ex) {
logger.error("Load " + location + " failure. ", ex);
}
}
else if (location.endsWith(".yml")){
YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
bean.setResources(resource);
for (Map.Entry<Object,Object> entry : bean.getObject().entrySet()){
properties.put(ObjectUtils.toString(entry.getKey()),
ObjectUtils.toString(entry.getValue()));
}
configSet.add(location);
}
}
} catch (Exception e) {
logger.error("Load " + location + " failure. ", e);
}
}
}
/**
* 获取当前加载的属性文件
*/
public Set<String> getConfigSet() {
return configSet;
}
/**
* 获取当前加载的属性数据
*/
public Properties getProperties() {
return properties;
}
/**
* 当前类实例
*/
public static PropertiesUtils getInstance(){
return PropertiesLoaderHolder.INSTANCE;
}
/**
* 重新加载实例(重新实例化,以重新加载属性文件数据)
*/
public static void releadInstance(){
PropertiesLoaderHolder.releadInstance();
}
// 正则表达式预编译
private static Pattern p1 = Pattern.compile("\\$\\{.*?\\}");
/**
* 获取属性值,取不到从System.getProperty()获取,都取不到返回null
*/
public String getProperty(String key) {
String value = properties.getProperty(key);
if (value != null){
// 支持嵌套取值的问题 key=${xx}/yy
Matcher m = p1.matcher(value);
while(m.find()) {
String g = m.group();
String keyChild = g.replaceAll("\\$\\{", "").replaceAll("\\}", "");
value = StringUtils.replace(value, g, getProperty(keyChild));
}
return value;
}else{
String systemProperty = System.getProperty(key);
if (systemProperty != null) {
return systemProperty;
}
}
return null;
}
/**
* 取出String类型的Property,但以System的Property优先,如果都为null则返回defaultValue值
*/
public String getProperty(String key, String defaultValue) {
String value = getProperty(key);
return value != null ? value : defaultValue;
}
/**
* 初始化日志路径
*/
private static Logger initLogger(){
String logPath = null;
try {
// 获取当前classes目录
logPath = new DefaultResourceLoader().getResource("/").getFile().getPath();
} catch (Exception e) {
// 取不到,取当前工作路径
logPath = System.getProperty("user.dir");
}
// 取当前日志路径下有classes目录,则使用classes目录
String classesLogPath = FileUtils.path(logPath + "/WEB-INF/classes");
if (new File(classesLogPath).exists()){
logPath = classesLogPath;
}
System.setProperty("logPath", FileUtils.path(logPath));
return LoggerFactory.getLogger(PropertiesUtils.class);
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.io;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.springframework.boot.env.OriginTrackedMapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
/**
* 配置文件加载(Boot)
* @author ThinkGem
* @version 2018-10-16
*/
public class PropertyLoader implements org.springframework.boot.env.PropertySourceLoader{
private static boolean isLoadPropertySource = false;
@Override
public String[] getFileExtensions() {
return new String[] { "properties", "yml" };
}
@Override
public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
if (!isLoadPropertySource){
isLoadPropertySource = true;
Properties properties = PropertiesUtils.getInstance().getProperties();
return Collections.singletonList(new OriginTrackedMapPropertySource("jeesite", properties));
}
return Collections.emptyList();
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.io;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.jeesite.common.lang.ExceptionUtils;
/**
* 资源供给类
* @author ThinkGem
* @version 2016-9-16
*/
public class ResourceUtils extends org.springframework.util.ResourceUtils {
private static ResourceLoader resourceLoader;
private static ResourcePatternResolver resourceResolver;
static{
resourceLoader = new DefaultResourceLoader();
resourceResolver = new PathMatchingResourcePatternResolver(resourceLoader);
}
/**
* 获取资源加载器(可读取jar内的文件)
* @author ThinkGem
*/
public static ResourceLoader getResourceLoader() {
return resourceLoader;
}
/**
* 获取ClassLoader
*/
public static ClassLoader getClassLoader() {
return resourceLoader.getClassLoader();
}
/**
* 获取资源加载器(可读取jar内的文件)
*/
public static Resource getResource(String location) {
return resourceLoader.getResource(location);
}
/**
* 获取资源文件流(用后记得关闭)
* @param location
* @author ThinkGem
* @throws IOException
*/
public static InputStream getResourceFileStream(String location) throws IOException{
Resource resource = resourceLoader.getResource(location);
return resource.getInputStream();
}
/**
* 获取资源文件内容
* @param location
* @author ThinkGem
*/
public static String getResourceFileContent(String location){
try(InputStream is = ResourceUtils.getResourceFileStream(location)){
return IOUtils.toString(is, "UTF-8");
}catch (IOException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* Spring 搜索资源文件
* @param locationPattern
* @author ThinkGem
*/
public static Resource[] getResources(String locationPattern){
try {
Resource[] resources = resourceResolver.getResources(locationPattern);
return resources;
} catch (IOException e) {
throw ExceptionUtils.unchecked(e);
}
}
}
///*package com.jeesite.common.jms;
//
//
//
//import org.apache.activemq.ActiveMQConnectionFactory;
//import org.apache.activemq.command.ActiveMQQueue;
//import org.apache.activemq.command.ActiveMQTopic;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.boot.autoconfigure.jms.DefaultJmsListenerContainerFactoryConfigurer;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.jms.annotation.EnableJms;
//import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
//import org.springframework.jms.config.JmsListenerContainerFactory;
//import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
//import org.springframework.jms.support.converter.MessageConverter;
//import org.springframework.jms.support.converter.MessageType;
//
//
//import javax.jms.ConnectionFactory;
//import javax.jms.Queue;
//import javax.jms.Topic;
//
//
//@EnableJms//启用jms功能
//@Configuration
//public class ActiveMqConfig {
//
// @Value("${queueName}")
// private String queueName;
//
// @Value("${topicName}")
// private String topicName;
//
// @Value("${spring.activemq.user}")
// private String userName;
//
// @Value("${spring.activemq.password}")
// private String password;
//
// @Value("${spring.activemq.broker-url}")
// private String brokerUrl;
//
// @Bean
// public Queue queue(){
// return new ActiveMQQueue(queueName);
// }
//
// @Bean
// public Topic topic(){
// return new ActiveMQTopic(topicName);
// }
//
// @Bean
// public ActiveMQConnectionFactory connectionFactory() {
// return new ActiveMQConnectionFactory(userName, password, brokerUrl);
// }
//
// @Bean
// public JmsListenerContainerFactory<?> jmsListenerContainerQueue(ActiveMQConnectionFactory connectionFactory){
// DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
// bean.setConnectionFactory(connectionFactory);
// return bean;
// }
//
// @Bean
// public JmsListenerContainerFactory<?> jmsListenerContainerTopic(ActiveMQConnectionFactory connectionFactory){
// DefaultJmsListenerContainerFactory bean = new DefaultJmsListenerContainerFactory();
// //设置为发布订阅方式, 默认情况下使用的生产消费者方式
// bean.setPubSubDomain(true);
// bean.setConnectionFactory(connectionFactory);
// return bean;
// }
//
//}*/
//package com.jeesite.common.jms;
//
//
//import org.apache.activemq.util.TransactionTemplate;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.jms.annotation.JmsListener;
//import org.springframework.jms.core.JmsMessagingTemplate;
//import org.springframework.stereotype.Component;
//
//import javax.jms.Destination;
//import javax.jms.Queue;
//
//
///****
// * 消息生产者 producer
// */
//@Component
//public class ActiveMqProducer {
//
// private final static Logger logger = LoggerFactory.getLogger(ActiveMqProducer.class);
//
// @Autowired
// private JmsMessagingTemplate jmsTemplate;
//
// @Autowired
// private Queue queue;
//
// //
////
// public void sendMsg(String msg) {
// logger.info("MQ发送消息:" + msg);
// jmsTemplate.convertAndSend(queue, msg);
//
// }
//
// //生产者监听消费者的应答
// @JmsListener(destination = "out.queue")
// public void consumerMessage(String text) {
// System.out.println("从activeMq 收到报文" + text);
// }
//}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.lang;
/**
* 字节转换工具
* @author ThinkGem
* @version 2015-6-20
*/
public class ByteUtils {
private static final int UNIT = 1024;
/**
* @param byteSize 字节
* @return
*/
public static String formatByteSize(long byteSize) {
if (byteSize <= -1){
return String.valueOf(byteSize);
}
double size = 1.0 * byteSize;
String type = "B";
if((int)Math.floor(size / UNIT) <= 0) { //不足1KB
type = "B";
return format(size, type);
}
size = size / UNIT;
if((int)Math.floor(size / UNIT) <= 0) { //不足1MB
type = "KB";
return format(size, type);
}
size = size / UNIT;
if((int)Math.floor(size / UNIT) <= 0) { //不足1GB
type = "MB";
return format(size, type);
}
size = size / UNIT;
if((int)Math.floor(size / UNIT) <= 0) { //不足1TB
type = "GB";
return format(size, type);
}
size = size / UNIT;
if((int)Math.floor(size / UNIT) <= 0) { //不足1PB
type = "TB";
return format(size, type);
}
size = size / UNIT;
if((int)Math.floor(size / UNIT) <= 0) {
type = "PB";
return format(size, type);
}
return ">PB";
}
private static String format(double size, String type) {
int precision = 0;
if(size * 1000 % 10 > 0) {
precision = 3;
} else if(size * 100 % 10 > 0) {
precision = 2;
} else if(size * 10 % 10 > 0) {
precision = 1;
} else {
precision = 0;
}
String formatStr = "%." + precision + "f";
if("KB".equals(type)) {
return String.format(formatStr, (size)) + "KB";
} else if("MB".equals(type)) {
return String.format(formatStr, (size)) + "MB";
} else if("GB".equals(type)) {
return String.format(formatStr, (size)) + "GB";
} else if("TB".equals(type)) {
return String.format(formatStr, (size)) + "TB";
} else if("PB".equals(type)) {
return String.format(formatStr, (size)) + "PB";
}
return String.format(formatStr, (size)) + "B";
}
// public static void main(String[] args) {
// System.out.println(ByteUtils.formatByteSize(1023));
// System.out.println(ByteUtils.formatByteSize(1L * UNIT));
// System.out.println(ByteUtils.formatByteSize(1L * UNIT * UNIT));
// System.out.println(ByteUtils.formatByteSize(1L * UNIT * 1023));
// System.out.println(ByteUtils.formatByteSize(1L * 1023 * 1023 * 1023));
// System.out.println(ByteUtils.formatByteSize(1L * UNIT * UNIT * UNIT));
// System.out.println(ByteUtils.formatByteSize(1L * UNIT * UNIT * UNIT * UNIT));
// System.out.println(ByteUtils.formatByteSize(1L * UNIT * UNIT * UNIT * UNIT * UNIT));
// System.out.println(ByteUtils.formatByteSize(1L * UNIT * UNIT * UNIT * UNIT * UNIT * UNIT));
// }
}
/**
* Copyright (c) 2005-2012 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jeesite.common.lang;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
/**
* 关于异常的工具类.
* @author calvin
* @version 2014-8-19
*/
public class ExceptionUtils {
/**
* 在request中获取异常类
* @param request
* @return
*/
public static Throwable getThrowable(HttpServletRequest request){
Throwable ex = null;
if (request.getAttribute("exception") != null) {
ex = (Throwable) request.getAttribute("exception");
} else if (request.getAttribute("javax.servlet.error.exception") != null) {
ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
}
return ex;
}
/**
* 将ErrorStack转化为String.
*/
public static String getStackTraceAsString(Throwable e) {
if (e == null){
return "";
}
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
/**
* 判断异常是否由某些底层的异常引起.
*/
@SuppressWarnings("unchecked")
public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
Throwable cause = ex.getCause();
while (cause != null) {
for (Class<? extends Exception> causeClass : causeExceptionClasses) {
if (causeClass.isInstance(cause)) {
return true;
}
}
cause = cause.getCause();
}
return false;
}
/**
* 将CheckedException转换为UncheckedException.
*/
public static RuntimeException unchecked(Exception e) {
if (e instanceof RuntimeException) {
return (RuntimeException) e;
} else {
return new RuntimeException(e);
}
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.lang;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
/**
* BigDecimal工具类
* @author ThinkGem
* @version 2016年6月11日
*/
public class NumberUtils extends org.apache.commons.lang3.math.NumberUtils {
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1, double v2) {
return div(v1, v2, 10);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
/**
* 格式化双精度,保留两个小数
* @return
*/
public static String formatDouble(Double b) {
BigDecimal bg = new BigDecimal(b);
return bg.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 百分比计算
* @return
*/
public static String formatScale(double one, long total) {
BigDecimal bg = new BigDecimal(one * 100 / total);
return bg.setScale(0, BigDecimal.ROUND_HALF_UP).toString();
}
/**
* 格式化数值类型
* @param data
* @param pattern
*/
public static String formatNumber(Object data, String pattern) {
DecimalFormat df = null;
if (pattern == null) {
df = new DecimalFormat();
} else {
df = new DecimalFormat(pattern);
}
return df.format(data);
}
/**
* 格式化数值类型
* @param
* @param
*/
public static String MathUUID(){
String orderNo = "" ;
String trandNo = String.valueOf((int)((Math.random() * 9 + 1) * 1000000));
String sdf = new SimpleDateFormat("yyyyMMddHHMMSS").format(new Date());
orderNo = sdf + trandNo;
return orderNo;
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.lang;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.nustaq.serialization.FSTConfiguration;
import org.springframework.beans.BeanUtils;
import org.springframework.core.NamedThreadLocal;
/**
* 对象操作工具类, 继承org.apache.commons.lang3.ObjectUtils类
* @author ThinkGem
* @version 2018-08-11
*/
public class ObjectUtils extends org.apache.commons.lang3.ObjectUtils {
/**
* 转换为Double类型
*/
public static Double toDouble(final Object val) {
if (val == null) {
return 0D;
}
try {
return NumberUtils.toDouble(StringUtils.trim(val.toString()));
} catch (Exception e) {
return 0D;
}
}
/**
* 转换为Float类型
*/
public static Float toFloat(final Object val) {
return toDouble(val).floatValue();
}
/**
* 转换为Long类型
*/
public static Long toLong(final Object val) {
return toDouble(val).longValue();
}
/**
* 转换为Integer类型
*/
public static Integer toInteger(final Object val) {
return toLong(val).intValue();
}
/**
* 转换为Boolean类型 'true', 'on', 'y', 't', 'yes' or '1' (case insensitive) will return true. Otherwise, false is returned.
*/
public static Boolean toBoolean(final Object val) {
if (val == null) {
return false;
}
return BooleanUtils.toBoolean(val.toString()) || "1".equals(val.toString());
}
/**
* 转换为字符串
* @param obj
* @return
*/
public static String toString(final Object obj) {
return toString(obj, StringUtils.EMPTY);
}
/**
* 如果对象为空,则使用defaultVal值
* @param obj
* @param defaultVal
* @return
*/
public static String toString(final Object obj, final String defaultVal) {
return obj == null ? defaultVal : obj.toString();
}
/**
* 空转空字符串("" to "" ; null to "" ; "null" to "" ; "NULL" to "" ; "Null" to "")
* @param val 需转换的值
* @return 返回转换后的值
*/
public static String toStringIgnoreNull(final Object val) {
return ObjectUtils.toStringIgnoreNull(val, StringUtils.EMPTY);
}
/**
* 空对象转空字符串 ("" to defaultVal ; null to defaultVal ; "null" to defaultVal ; "NULL" to defaultVal ; "Null" to defaultVal)
* @param val 需转换的值
* @param defaultVal 默认值
* @return 返回转换后的值
*/
public static String toStringIgnoreNull(final Object val, String defaultVal) {
String str = ObjectUtils.toString(val);
return !"".equals(str) && !"null".equals(str.trim().toLowerCase()) ? str : defaultVal;
}
/**
* 拷贝一个对象(但是子对象无法拷贝)
* @param source
* @param ignoreProperties
*/
public static Object copyBean(Object source, String... ignoreProperties){
if (source == null){
return null;
}
try {
Object target = source.getClass().newInstance();
BeanUtils.copyProperties(source, target, ignoreProperties);
return target;
} catch (InstantiationException | IllegalAccessException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* 注解到对象复制,只复制能匹配上的方法。 硕正组件用。
* @param annotation
* @param object
*/
public static void annotationToObject(Object annotation, Object object) {
if (annotation != null && object != null) {
Class<?> annotationClass = annotation.getClass();
Class<?> objectClass = object.getClass();
for (Method m : objectClass.getMethods()) {
if (StringUtils.startsWith(m.getName(), "set")) {
try {
String s = StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3));
Object obj = annotationClass.getMethod(s).invoke(annotation);
if (obj != null && !"".equals(obj.toString())) {
// if (object == null){
// object = objectClass.newInstance();
// }
m.invoke(object, obj);
}
} catch (Exception e) {
// 忽略所有设置失败方法
}
}
}
}
}
/**
* 序列化对象
* @param object
* @return
*/
public static byte[] serialize(Object object) {
if (object == null){
return null;
}
long beginTime = System.currentTimeMillis();
byte[] bytes = null;
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);) {
oos.writeObject(object);
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
long totalTime = System.currentTimeMillis() - beginTime;
if (totalTime > 3000){
System.out.println("Serialize time: " + TimeUtils.formatDateAgo(totalTime));
}
return bytes;
}
/**
* 反序列化对象
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes) {
if (bytes == null){
return null;
}
long beginTime = System.currentTimeMillis();
Object object = null;
if (bytes.length > 0) {
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);) {
object = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
}
}
long totalTime = System.currentTimeMillis() - beginTime;
if (totalTime > 3000){
System.out.println("Unserialize time: " + TimeUtils.formatDateAgo(totalTime));
}
return object;
}
// FST序列化配置对象
private static ThreadLocal<FSTConfiguration> fst = new NamedThreadLocal<FSTConfiguration>("FSTConfiguration") {
public FSTConfiguration initialValue() {
return FSTConfiguration.createDefaultConfiguration();
}
};
/**
* FST 序列化对象
* @param object
* @return
*/
public static byte[] serializeFst(Object object) {
if (object == null){
return null;
}
long beginTime = System.currentTimeMillis();
byte[] bytes = fst.get().asByteArray(object);
long totalTime = System.currentTimeMillis() - beginTime;
if (totalTime > 3000){
System.out.println("Fst serialize time: " + TimeUtils.formatDateAgo(totalTime));
}
return bytes;
}
/**
* FST 反序列化对象
* @param bytes
* @return
*/
public static Object unserializeFst(byte[] bytes) {
if (bytes == null){
return null;
}
long beginTime = System.currentTimeMillis();
Object object = fst.get().asObject(bytes);
long totalTime = System.currentTimeMillis() - beginTime;
if (totalTime > 3000){
System.out.println("Fst unserialize time: " + TimeUtils.formatDateAgo(totalTime));
}
return object;
}
/**
* 克隆一个对象(完全拷贝)
* @param source
*/
public static Object cloneBean(Object source){
if (source == null){
return null;
}
byte[] bytes = ObjectUtils.serializeFst(source);
Object target = ObjectUtils.unserializeFst(bytes);
return target;
}
}
package com.jeesite.common.lang;
import java.util.Calendar;
/**
* 工作日计算工具类
* @author ThinkGem
*/
public class WorkDayUtils {
/**
* 获取日期之间的天数
* @param d1
* @param d2
* @return
*/
public int getDaysBetween(java.util.Calendar d1, java.util.Calendar d2) {
if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
java.util.Calendar swap = d1;
d1 = d2;
d2 = swap;
}
int days = d2.get(java.util.Calendar.DAY_OF_YEAR)
- d1.get(java.util.Calendar.DAY_OF_YEAR);
int y2 = d2.get(java.util.Calendar.YEAR);
if (d1.get(java.util.Calendar.YEAR) != y2) {
d1 = (java.util.Calendar) d1.clone();
do {
days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
d1.add(java.util.Calendar.YEAR, 1);
} while (d1.get(java.util.Calendar.YEAR) != y2);
}
return days;
}
/**
* 获取工作日
* @param d1
* @param d2
* @return
*/
public int getWorkingDay(java.util.Calendar d1, java.util.Calendar d2) {
int result = -1;
if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
java.util.Calendar swap = d1;
d1 = d2;
d2 = swap;
}
// int betweendays = getDaysBetween(d1, d2);
// int charge_date = 0;
int charge_start_date = 0;// 开始日期的日期偏移量
int charge_end_date = 0;// 结束日期的日期偏移量
// 日期不在同一个日期内
int stmp;
int etmp;
stmp = 7 - d1.get(Calendar.DAY_OF_WEEK);
etmp = 7 - d2.get(Calendar.DAY_OF_WEEK);
if (stmp != 0 && stmp != 6) {// 开始日期为星期六和星期日时偏移量为0
charge_start_date = stmp - 1;
}
if (etmp != 0 && etmp != 6) {// 结束日期为星期六和星期日时偏移量为0
charge_end_date = etmp - 1;
}
// }
result = (getDaysBetween(this.getNextMonday(d1), this.getNextMonday(d2)) / 7)
* 5 + charge_start_date - charge_end_date;
// System.out.println("charge_start_date>" + charge_start_date);
// System.out.println("charge_end_date>" + charge_end_date);
// System.out.println("between day is-->" + betweendays);
return result;
}
/**
* 获取中文日期
* @param date
* @return
*/
public String getChineseWeek(Calendar date) {
final String dayNames[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
// System.out.println(dayNames[dayOfWeek - 1]);
return dayNames[dayOfWeek - 1];
}
/**
* 获得日期的下一个星期一的日期
* @param date
* @return
*/
public Calendar getNextMonday(Calendar date) {
Calendar result = null;
result = date;
do {
result = (Calendar) result.clone();
result.add(Calendar.DATE, 1);
} while (result.get(Calendar.DAY_OF_WEEK) != 2);
return result;
}
/**
* 获取休息日
* @param d1
* @param d2
* @return
*/
public int getHolidays(Calendar d1, Calendar d2) {
return this.getDaysBetween(d1, d2) - this.getWorkingDay(d1, d2);
}
// public static void main(String[] args) {
// try {
// String strDateStart = "2013-08-01";
// String strDateEnd = "2014-08-31";
//
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// Date date_start = sdf.parse(strDateStart);
// Date date_end = sdf.parse(strDateEnd);
// WorkDayUtils app = new WorkDayUtils();
// Calendar cal_start = Calendar.getInstance();
// Calendar cal_end = Calendar.getInstance();
// cal_start.setTime(date_start);
// cal_end.setTime(date_end);
// System.out.println("开始日:" + cal_start.get(Calendar.YEAR) + "-" + (cal_start.get(Calendar.MONTH) + 1)
// + "-" + cal_start.get(Calendar.DAY_OF_MONTH) + " " + app.getChineseWeek(cal_start));
// System.out.println("结束日:" + cal_end.get(Calendar.YEAR) + "-" + (cal_end.get(Calendar.MONTH) + 1)
// + "-" + cal_end.get(Calendar.DAY_OF_MONTH) + " " + app.getChineseWeek(cal_end));
// System.out.println("工作日:" + app.getWorkingDay(cal_start, cal_end));
// System.out.println("休息日:" + app.getHolidays(cal_start, cal_end));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
}
/**
* Copyright (c) 2005-2012 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.jeesite.common.mapper;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;
import com.jeesite.common.lang.ExceptionUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.reflect.ReflectUtils;
/**
* 使用Jaxb2.0实现XML<->Java Object的Mapper.
*
* 在创建时需要设定所有需要序列化的Root对象的Class.
* 特别支持Root对象是Collection的情形.
*
* @author calvin
* @version 2013-01-15
*/
@SuppressWarnings("rawtypes")
public class JaxbMapper {
private static ConcurrentMap<Class, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class, JAXBContext>();
/**
* Java Object->Xml without encoding.
*/
public static String toXml(Object root) {
Class clazz = ReflectUtils.getUserClass(root);
return toXml(root, clazz, null);
}
/**
* Java Object->Xml with encoding.
*/
public static String toXml(Object root, String encoding) {
Class clazz = ReflectUtils.getUserClass(root);
return toXml(root, clazz, encoding);
}
/**
* Java Object->Xml with encoding.
*/
public static String toXml(Object root, Class clazz, String encoding) {
try {
StringWriter writer = new StringWriter();
createMarshaller(clazz, encoding).marshal(root, writer);
return writer.toString();
} catch (JAXBException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
*/
public static String toXml(Collection<?> root, String rootName, Class clazz) {
return toXml(root, rootName, clazz, null);
}
/**
* Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
*/
public static String toXml(Collection<?> root, String rootName, Class clazz, String encoding) {
try {
CollectionWrapper wrapper = new CollectionWrapper();
wrapper.collection = root;
JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
CollectionWrapper.class, wrapper);
StringWriter writer = new StringWriter();
createMarshaller(clazz, encoding).marshal(wrapperElement, writer);
return writer.toString();
} catch (JAXBException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* Xml->Java Object.
*/
@SuppressWarnings("unchecked")
public static <T> T fromXml(String xml, Class<T> clazz) {
try {
StringReader reader = new StringReader(xml);
return (T) createUnmarshaller(clazz).unmarshal(reader);
} catch (JAXBException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* 创建Marshaller并设定encoding(可为null).
* 线程不安全,需要每次创建或pooling。
*/
public static Marshaller createMarshaller(Class clazz, String encoding) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (StringUtils.isNotBlank(encoding)) {
marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
}
return marshaller;
} catch (JAXBException e) {
throw ExceptionUtils.unchecked(e);
}
}
/**
* 创建UnMarshaller.
* 线程不安全,需要每次创建或pooling。
*/
public static Unmarshaller createUnmarshaller(Class clazz) {
try {
JAXBContext jaxbContext = getJaxbContext(clazz);
return jaxbContext.createUnmarshaller();
} catch (JAXBException e) {
throw ExceptionUtils.unchecked(e);
}
}
protected static JAXBContext getJaxbContext(Class clazz) {
if (clazz == null){
throw new RuntimeException("'clazz' must not be null");
}
JAXBContext jaxbContext = jaxbContexts.get(clazz);
if (jaxbContext == null) {
try {
jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);
jaxbContexts.putIfAbsent(clazz, jaxbContext);
} catch (JAXBException ex) {
// throw new HttpMessageConversionException("Could not instantiate JAXBContext for class [" + clazz
// + "]: " + ex.getMessage(), ex);
throw new RuntimeException("Could not instantiate JAXBContext for class [" + clazz
+ "]: " + ex.getMessage(), ex);
}
}
return jaxbContext;
}
/**
* 封装Root Element 是 Collection的情况.
*/
public static class CollectionWrapper {
@XmlAnyElement
protected Collection<?> collection;
}
}
/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
package com.jeesite.common.mapper;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
import com.jeesite.common.collect.ListUtils;
/**
* 简单封装Jackson,实现JSON String<->Java Object的Mapper.
* 封装不同的输出风格, 使用不同的builder函数创建实例.
* @author ThinkGem
* @version 2016-3-2
*/
public class JsonMapper extends ObjectMapper {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
/**
* 当前类的实例持有者(静态内部类,延迟加载,懒汉式,线程安全的单例模式)
*/
private static final class JsonMapperHolder {
private static final JsonMapper INSTANCE = new JsonMapper();
}
public JsonMapper() {
// Spring ObjectMapper 初始化配置,支持 @JsonView
new Jackson2ObjectMapperBuilder().configure(this);
// 为Null时不序列化
this.setSerializationInclusion(Include.NON_NULL);
// 允许单引号
this.configure(Feature.ALLOW_SINGLE_QUOTES, true);
// 允许不带引号的字段名称
this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// 设置时区
this.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 遇到空值处理为空串
this.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>(){
@Override
public void serialize(Object value, JsonGenerator jgen,
SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeString(StringUtils.EMPTY);
}
});
// // 统一默认Date类型转换格式。如果设置,Bean中的@JsonFormat将失效
// final String dataFormat = Global.getProperty("json.mapper.dataFormat");
// if (StringUtils.isNotBlank(dataFormat)){
// this.registerModule(new SimpleModule().addSerializer(Date.class, new JsonSerializer<Date>(){
// @Override
// public void serialize(Date value, JsonGenerator jgen,
// SerializerProvider provider) throws IOException, JsonProcessingException {
// if (value != null){
// jgen.writeString(DateUtils.formatDate(value, dataFormat));
// }
// }
// }));
// }
// // 进行HTML解码(先注释掉,否则会造成XSS攻击,比如菜单名称里输入<script>alert(123)</script>转josn后就会还原这个编码 ,并在浏览器中运行)。
// this.registerModule(new SimpleModule().addSerializer(String.class, new JsonSerializer<String>(){
// @Override
// public void serialize(String value, JsonGenerator jgen,
// SerializerProvider provider) throws IOException,
// JsonProcessingException {
// if (value != null){
// jgen.writeString(StringEscapeUtils.unescapeHtml4(value));
// }
// }
// }));
}
/**
* Object可以是POJO,也可以是Collection或数组。
* 如果对象为Null, 返回"null".
* 如果集合为空集合, 返回"[]".
*/
public String toJsonString(Object object) {
try {
return this.writeValueAsString(object);
} catch (IOException e) {
logger.warn("write to json string error:" + object, e);
return null;
}
}
/**
* 输出JSONP格式数据.
*/
public String toJsonpString(String functionName, Object object) {
return toJsonString(new JSONPObject(functionName, object));
}
/**
* 反序列化POJO或简单Collection如List<String>.
* 如果JSON字符串为Null或"null"字符串, 返回Null.
* 如果JSON字符串为"[]", 返回空集合.
* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType)
* @see #fromJson(String, JavaType)
*/
public <T> T fromJsonString(String jsonString, Class<T> clazz) {
if (StringUtils.isEmpty(jsonString) || "<CLOB>".equals(jsonString)) {
return null;
}
try {
return this.readValue(jsonString, clazz);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 反序列化复杂Collection如List<Bean>, 先使用函数createCollectionType构造类型,然后调用本函数.
* @see #createCollectionType(Class, Class...)
*/
@SuppressWarnings("unchecked")
public <T> T fromJsonString(String jsonString, JavaType javaType) {
if (StringUtils.isEmpty(jsonString) || "<CLOB>".equals(jsonString)) {
return null;
}
try {
return (T) this.readValue(jsonString, javaType);
} catch (IOException e) {
logger.warn("parse json string error:" + jsonString, e);
return null;
}
}
/**
* 构造泛型的Collection Type如:
* ArrayList<MyBean>, 则调用constructCollectionType(ArrayList.class,MyBean.class)
* HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class)
*/
public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
return this.getTypeFactory().constructParametricType(collectionClass, elementClasses);
}
/**
* 当JSON里只含有Bean的部分属性時,更新一个已存在Bean,只覆盖该部分的属性.
*/
@SuppressWarnings("unchecked")
public <T> T update(String jsonString, T object) {
try {
return (T) this.readerForUpdating(object).readValue(jsonString);
} catch (JsonProcessingException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
} catch (IOException e) {
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
}
return null;
}
/**
* 设定是否使用Enum的toString函数来读写Enum,
* 为False实时使用Enum的name()函数来读写Enum, 默认为False.
* 注意本函数一定要在Mapper创建后, 所有的读写动作之前调用.
*/
public JsonMapper enableEnumUseToString() {
this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
return this;
}
/**
* 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
* 默认会先查找jaxb的annotation,如果找不到再找jackson的。
*/
public JsonMapper enableJaxbAnnotation() {
JaxbAnnotationModule module = new JaxbAnnotationModule();
this.registerModule(module);
return this;
}
/**
* 取出Mapper做进一步的设置或使用其他序列化API.
*/
public ObjectMapper getMapper() {
return this;
}
/**
* 获取当前实例
*/
public static JsonMapper getInstance() {
return JsonMapperHolder.INSTANCE;
}
/**
* 对象转换为JSON字符串
*/
public static String toJson(Object object){
return JsonMapper.getInstance().toJsonString(object);
}
/**
* 对象转换为JSONP字符串
*/
public static String toJsonp(String functionName, Object object){
return JsonMapper.getInstance().toJsonpString(functionName, object);
}
/**
* JSON字符串转换为对象
*/
@SuppressWarnings("unchecked")
public static <T> T fromJson(String jsonString, Class<?> clazz){
return (T) JsonMapper.getInstance().fromJsonString(jsonString, clazz);
}
/**
* JSON字符串转换为 List<Map<String, Object>>
*/
public static List<Map<String, Object>> fromJsonForMapList(String jsonString){
List<Map<String, Object>> result = ListUtils.newArrayList();
if (StringUtils.startsWith(jsonString, "{")){
Map<String, Object> map = fromJson(jsonString, Map.class);
if (map != null){
result.add(map);
}
}else if (StringUtils.startsWith(jsonString, "[")){
List<Map<String, Object>> list = fromJson(jsonString, List.class);
if (list != null){
result = list;
}
}
return result;
}
// public static void main(String[] args) {
// List<Map<String, Object>> list = ListUtils.newArrayList();
// Map<String, Object> map = MapUtils.newHashMap();
// map.put("id", 1);
// map.put("pId", -1);
// map.put("name", "根节点");
// list.add(map);
// map = MapUtils.newHashMap();
// map.put("id", 2);
// map.put("pId", 1);
// map.put("name", "你好");
// map.put("open", true);
// list.add(map);
// String json = JsonMapper.toJson(list);
// System.out.println(json);
// List<Map<String, Object>> map2 = JsonMapper.fromJson(json, List.class);
// System.out.println(map2);
// Map<String, Object> map3 = JsonMapper.fromJson("{extendS1:{title:'站牌号',"
// + "sort:1,type:'text',maxlength:0,maxlength:30},extendS2:{title:'规模分类',"
// + "sort:2,type:'dict',dictType:'scope_category'}}", Map.class);
// System.out.println(map3);
// List<String> list2 = fromJson("[1,2]", List.class);
// System.out.println(list2);
// }
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
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