Commit 59fe890c by 汪鑫

旅馆一件事

parents
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>hotel-common-utils</artifactId>
<packaging>jar</packaging>
<version>1.0.0-RELEASE</version>
<name>${project.artifactId}</name>
<parent>
<groupId>com.ihooyah</groupId>
<artifactId>hotel-parent</artifactId>
<version>1.0.0-RELEASE</version>
<relativePath>../hotel-parent/pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk14</artifactId>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.0.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<!-- 读取FTP -->
<groupId>org.apache.camel</groupId>
<artifactId>camel-ftp</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
<encoding>UTF-8</encoding>
<compilerArguments>
<verbose />
<bootclasspath>${java.home}${file.separator}lib${file.separator}rt.jar${path.separator}${java.home}${file.separator}lib${file.separator}jce.jar</bootclasspath>
</compilerArguments>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.ihooyah;
public interface Constants {
/**
* http请求参数
*/
//App版本号 例如:1.2.1
String APP_VERSION = "app-version";
//App打包版本好 例如 : 21
String APP_VERSION_BUILD = "app-version-build";
//mobi 移动端
String APP_PLATFORM = "app-platform";
//操作系统
String APP_OS = "app-os";
//操作系统版本号
String APP_OS_VERSION = "app-os-version";
//设备名例如 HUAWEI MATE 8 , IPHONE 8
String APP_DEVICE_MODEL = "app-device-model";
//警务平台id
String JWPTID = "jwptid";
}
package com.ihooyah.Enum;
/**
* @author ***
* @version V1.0
* @Description
* @Package com.ihooyah.constant
* @date 2022-11-21 17:17
*/
public enum MaterialEnum {
/**
* 通用材料
*/
PUBLIC_MATER("public","通用材料"),
/**
* 特种行业许可
*/
SPECIAL_MATER("special","特种行业许可"),
/**
* 公共场所卫生许可
*/
HEALTH_MATER("health","公共场所卫生许可"),
/**
* 通用材料公众聚集场所投入使用、营业前消防安全检查
*/
CHECK_MATER("check","通用材料公众聚集场所投入使用、营业前消防安全检查"),
/**
* 户外广告设施设置的审批(可选)
*/
OUTDOOR_MATER("outdoor","户外广告设施设置的审批(可选)");
private String type;
private String value;
public static MaterialEnum getByType(String type) {
for (MaterialEnum materialEnum : MaterialEnum.values()) {
if (materialEnum.getType().equals(type)) {
return materialEnum;
}
}
return null;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
MaterialEnum(String type, String value) {
this.type = type;
this.value = value;
}
}
package com.ihooyah.base;
import com.ihooyah.rest.output.RespEnum;
import com.ihooyah.rest.output.RespInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class BaseController {
@Autowired
HttpServletRequest request;
@Autowired
HttpSession httpSession;
public static final String VALIDATE_CODE_KEY = "VALIDATE_CODE_KEY";
/**
* 输入校验
*
* @param bindingResult
* @return
*/
public RespInfo getBindResult(BindingResult bindingResult) {
if (bindingResult.getAllErrors().size() > 0) {
String errorInfo = bindingResult.getAllErrors().get(0).getDefaultMessage();
return RespInfo.mobiError(RespEnum.INVALID_PARAMS, errorInfo);
}
return null;
}
public String getValidateCode() {
return (String) httpSession.getAttribute(VALIDATE_CODE_KEY);
}
public void keepValidateCode(String validateCode) {
httpSession.setAttribute(VALIDATE_CODE_KEY, validateCode);
}
/**
* 验证码校验
*
* @param validateCode
* @return
*/
public boolean isValid(String validateCode) {
if ("666".equals(validateCode)) {
return true;
}
String sessionValidateCode = this.getValidateCode();
if (sessionValidateCode == null) {
return false;
}
boolean valid = sessionValidateCode.equals(validateCode);
if (valid) {
httpSession.removeAttribute(VALIDATE_CODE_KEY);
}
return valid;
}
}
package com.ihooyah.base;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @Author: gedelong
* @Date: 2019/1/17 16:02
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageForm {
private Integer pageNum = 1;
private Integer pageSize = 10;
private Boolean page=false;
}
package com.ihooyah.constants;
/**
* @author ***
* @version V1.0
* @Description
* @Package com.ihooyah.constant
* @date 2022-11-21 17:09
*/
public interface Constant {
/**
* 通用材料
*/
String publicMaterial = "publicMaterial";
String ONETHING_CODE = "32TC00423222";
/**
* 应用标识
*/
String APPMARK = "klgyjs";
/**
* 业务名称
*/
String SERVICE_NAME_TICKET = "ticketValidate";
String APPWORD = "TIvUdpkY5UV4";
/**
* 业务名称 自然人
*/
String SERVICE_NAME_TOKEN = "findUserByToken";
/**
* 业务名称 法人业务
*/
String SERVICE_NAME_LEGAL_TOKEN = "findCorUserByToken";
/**
* 法人
*/
String USER_TYPEA_LEGAL = "1";
/**
* 自然人
*/
String USER_TYPEA = "0";
}
package com.ihooyah.constants;
public interface HeaderConstants {
/**
* http请求参数
*/
//App版本号 例如:1.2.1
String APP_VERSION = "app-version";
//App打包版本好 例如 : 21
String APP_VERSION_BUILD = "app-version-build";
//mobi 移动端
String APP_PLATFORM = "app-platform";
//操作系统
String APP_OS = "app-os";
//操作系统版本号
String APP_OS_VERSION = "app-os-version";
//设备名例如 HUAWEI MATE 8 , IPHONE 8
String APP_DEVICE_MODEL = "app-device-model";
//警务平台id
String JWPTID = "jwptid";
//所属分局ID
String POLICE_AREA_CODE = "policeAreaCode";
//所属分局名称
String POLICE_AREA_NAME = "policeAreaName";
}
package com.ihooyah.rest;
import com.github.pagehelper.PageInfo;
import java.util.ArrayList;
import java.util.List;
/**
* @author 王尧 【wangyao@ihooyah.com】
* @description
* @create 2018-04-17 下午6:43
**/
public class PageResult<T> {
//当前页
private int pageNum;
//当前页条数
private int pageSize;
//总数
private int totalCount;
//
private boolean hasPreviousPage;
private boolean hasNextPage;
//数据
private List<T> data = new ArrayList<>();
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public boolean isHasPreviousPage() {
return hasPreviousPage;
}
public void setHasPreviousPage(boolean hasPreviousPage) {
this.hasPreviousPage = hasPreviousPage;
}
public boolean isHasNextPage() {
return hasNextPage;
}
public void setHasNextPage(boolean hasNextPage) {
this.hasNextPage = hasNextPage;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
if (data == null) {
return;
}
this.data = data;
}
public static <T> PageResult<T> toPageResult(int pageNum, int pageSize, int count, List<T> data) {
PageResult<T> pageResult = new PageResult<>();
pageResult.setPageNum(pageNum);
pageResult.setPageSize(pageSize);
pageResult.setTotalCount(count);
pageResult.setData(data);
return pageResult;
}
public static <T> PageResult<T> toPageResult(PageInfo<T> pageInfo) {
PageResult<T> pageResult = new PageResult<>();
pageResult.setPageNum(pageInfo.getPageNum());
pageResult.setPageSize(pageInfo.getPageSize());
pageResult.setTotalCount(pageInfo.getEndRow());
pageResult.setHasNextPage(pageInfo.isHasNextPage());
pageResult.setHasPreviousPage(pageInfo.isHasPreviousPage());
pageResult.setData(pageInfo.getList());
return pageResult;
}
}
package com.ihooyah.rest.output;
/**
* @author 王尧 【wangyao@ihooyah.com】
* @description
* @create 2018-03-30 下午8:05
**/
public enum RespEnum {
//基础请求
SUCCESS(200, "请求成功"),
ERROR(500, "请求失败"),
INVALID_PARAMS(400, ""),
//授权相关 11000
AUTH_NO_ACCESS(11001, "没有权限访问该资源"),
AUTH_ACCESSTOKEN_EXPIRED(11002, "令牌已失效"),
AUTH_ACCESSTOKEN_INEXISTENCE(11003, "ACCESS_TOKEN不存在"),
//用户相关 12000
USER_NOLOGIN(12001, "用户未登录"),
USER_INVALID_PWD(12002, "用户密码错误"),
USER_INVALID_LOGINNAME(12003, "用户不存在"),
//公安网证相关 13000
AUTHENTICATION_ERROR(13002, "查询失败,请重试"),
SERIAL_NUMBER_ERROR(13003, "当前设备序列号已存在,请至库存中心进行设备返还入库");
private int code;
private String msg;
private RespEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
/**
* 通过code获取对应的内容
*
* @param
* @return
* @author 王尧 【wangyao@ihooyah.com】
* @date 2018/3/30 下午8:15
**/
public static String getMsgByCode(int code) {
for (RespEnum responseEnum : RespEnum.values()) {
if (responseEnum.getCode() == code) {
return responseEnum.msg;
}
}
return null;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.ihooyah.rest.output;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Http请求统一返回结构
*
* @param
* @author 王尧 【wangyao@ihooyah.com】
* @return
* @date 2018/3/30 下午7:59
**/
public class RespInfo<T> {
private Integer code = -1;
private String msg = "";
private T result;
private Object endpoint = "";
public RespInfo(Integer code, String msg, T result) {
this.code = code;
this.msg = msg;
this.result = result;
}
public RespInfo(Integer code, String msg) {
this.code = code;
this.msg = msg;
this.result = result;
}
public RespInfo() {
}
public static RespInfo out(RespEnum respEnum) {
return new RespInfo(respEnum.getCode(), respEnum.getMsg());
}
public static RespInfo out(RespEnum respEnum, Object object) {
RespInfo respInfo = new RespInfo(respEnum.getCode(), respEnum.getMsg(), object);
respInfo.setEndpoint("web");
return respInfo;
}
public static RespInfo mobiSuccess(RespEnum respEnum, Object object) {
RespInfo respInfo = new RespInfo(respEnum.getCode(), respEnum.getMsg(), object);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobiSuccess() {
RespInfo respInfo = new RespInfo(RespEnum.SUCCESS.getCode(), "", "");
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobiSuccess(Object obj) {
RespInfo respInfo = new RespInfo(RespEnum.SUCCESS.getCode(), "", obj);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobiSuccess(String msg, Object obj) {
RespInfo respInfo = new RespInfo(RespEnum.SUCCESS.getCode(), msg, obj);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobiSuccess(String msg) {
RespInfo respInfo = new RespInfo(RespEnum.SUCCESS.getCode(), msg);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobiError() {
RespInfo respInfo = new RespInfo(RespEnum.ERROR.getCode(), RespEnum.ERROR.getMsg());
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobiError(String msg) {
RespInfo respInfo = new RespInfo(RespEnum.ERROR.getCode(), msg);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobiError(String msg, Object object) {
RespInfo respInfo = new RespInfo(RespEnum.ERROR.getCode(), msg, object);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobiError(RespEnum respEnum, String errorMsg) {
RespInfo respInfo = null;
respInfo = new RespInfo(respEnum.getCode(), errorMsg, "");
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobiError(RespEnum respEnum) {
RespInfo respInfo = new RespInfo(respEnum.getCode(), respEnum.getMsg(), "");
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfo mobi(Object obj) {
RespInfo respInfo = new RespInfo(RespEnum.INVALID_PARAMS.getCode(), "",obj);
respInfo.setEndpoint("mobi");
return respInfo;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
public Object getEndpoint() {
return endpoint;
}
public void setEndpoint(Object endpoint) {
this.endpoint = endpoint;
}
public <T> T getResultObject(Class<T> clazz) {
if (RespEnum.SUCCESS.getCode() == this.getCode()) {
if (StringUtils.isBlank(this.getResult().toString())) {
return null;
}
JSONObject jsonObject = (JSONObject) getResult();
return jsonObject.toJavaObject(clazz);
}
return null;
}
public <T> List<T> getResultList(Class<T> clazz) {
if (RespEnum.SUCCESS.getCode() == this.getCode()) {
if (StringUtils.isBlank(this.getResult().toString())) {
return new ArrayList<>();
}
JSONArray jsonArray = (JSONArray) getResult();
return jsonArray.toJavaList(clazz);
}
return new ArrayList<>();
}
}
package com.ihooyah.rest.output;
/**
* Http请求统一返回结构
*
* @param
* @author 王尧 【wangyao@ihooyah.com】
* @return
* @date 2018/3/30 下午7:59
**/
public class RespInfoBak {
private Integer code = -1;
private String msg = "";
private Object result = "";
private Object endpoint = "";
public RespInfoBak(Integer code, String msg, Object result) {
this.code = code;
this.msg = msg;
this.result = result;
}
public RespInfoBak(Integer code, String msg) {
this.code = code;
this.msg = msg;
this.result = result;
}
public RespInfoBak() {
}
public static RespInfoBak out(RespEnum respEnum) {
return new RespInfoBak(respEnum.getCode(), respEnum.getMsg());
}
public static RespInfoBak out(RespEnum respEnum, Object object) {
RespInfoBak respInfo = new RespInfoBak(respEnum.getCode(), respEnum.getMsg(), object);
respInfo.setEndpoint("web");
return respInfo;
}
public static RespInfoBak mobiSuccess(RespEnum respEnum, Object object) {
RespInfoBak respInfo = new RespInfoBak(respEnum.getCode(), respEnum.getMsg(), object);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfoBak mobiSuccess() {
RespInfoBak respInfo = new RespInfoBak(RespEnum.SUCCESS.getCode(), "", "");
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfoBak mobiSuccess(Object obj) {
RespInfoBak respInfo = new RespInfoBak(RespEnum.SUCCESS.getCode(), "", obj);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfoBak mobiSuccess(String msg, Object obj) {
RespInfoBak respInfo = new RespInfoBak(RespEnum.SUCCESS.getCode(), msg, obj);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfoBak mobiSuccess(String msg) {
RespInfoBak respInfo = new RespInfoBak(RespEnum.SUCCESS.getCode(), msg);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfoBak mobi(Object obj) {
RespInfoBak respInfo = new RespInfoBak(RespEnum.INVALID_PARAMS.getCode(), "",obj);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfoBak mobiError() {
RespInfoBak respInfo = new RespInfoBak(RespEnum.ERROR.getCode(), RespEnum.ERROR.getMsg());
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfoBak mobiError(String msg) {
RespInfoBak respInfo = new RespInfoBak(RespEnum.ERROR.getCode(), msg);
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfoBak mobiError(RespEnum respEnum, String errorMsg) {
RespInfoBak respInfo = null;
respInfo = new RespInfoBak(respEnum.getCode(), errorMsg, "");
respInfo.setEndpoint("mobi");
return respInfo;
}
public static RespInfoBak mobiError(RespEnum respEnum) {
RespInfoBak respInfo = new RespInfoBak(respEnum.getCode(), respEnum.getMsg(), "");
respInfo.setEndpoint("mobi");
return respInfo;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public Object getEndpoint() {
return endpoint;
}
public void setEndpoint(Object endpoint) {
this.endpoint = endpoint;
}
}
package com.ihooyah.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
public class AESUtils {
private static final String TAG = "AESCrypt";
//AESCrypt-ObjC uses CBC and PKCS7Padding
private static final String AES_MODE = "AES/CBC/PKCS7Padding";
private static final String CHARSET = "UTF-8";
//AESCrypt-ObjC uses SHA-256 (and so a 256-bit key)
private static final String HASH_ALGORITHM = "SHA-256";
//AESCrypt-ObjC uses blank IV (not the best security, but the aim here is compatibility)
private static final byte[] ivBytes = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//togglable log option (please turn off in live!)
public static boolean DEBUG_LOG_ENABLED = false;
//public static final String KEY = "a708765a20d14fda";
public static final String KEY = "hq71urgfdq12mn98";
public static void main(String[] args) throws GeneralSecurityException {
String encryptStr = encrypt("{\"account\":\"18512519107\",\"password\":\"123456\"}", AESUtils.KEY);
//String encryptStr = encrypt("{\"account\":\"18512519107\",\"type\":\"device\"}", AESUtils.KEY);
//String encryptStr = encrypt("{\"newPwd\":\"123456\",\"confirmPwd\":\"123456\"}", AESUtils.KEY);
//String encrySearchFeedbackFormptStr = encrypt("{\"name\":\"222222\",\"dept\":\"222222\", \"phone\": \"88888888\", \"email\": \"111@qq.com\"}", AESUtils.KEY);
//String encryptStr = encrypt("{\"fbContent\":\"测试反馈11\",\"fbPhone\":\"18055555555\", \"fbEmail\": \"44@.com\", \"fbFiles\": \"/1111.jpg\"}", AESUtils.KEY);
//String encryptStr = encrypt("{\"pageSize\":\"5\",\"pageNum\":\"1\"}", AESUtils.KEY);
//String encryptStr = encrypt("{\"specialId\":\"201\"}", AESUtils.KEY);
//String encryptStr = encrypt("{\"specialIds\":\"200,202\"}", AESUtils.KEY);
//String encryptStr = encrypt("{\"fbId\":\"13\"}", AESUtils.KEY);
//String encryptStr = encrypt("{\"platform\":\"ANDROID\"}", AESUtils.KEY);
//String encryptStr = encrypt("{\"layerId\":\"10\",\"gatherId\":\"999\"}", AESUtils.KEY);
System.out.println(encryptStr);
String orgStr = "ZPd1m8JbzqkIn3E+saOdXdQIamyxFEltpXYUFUxER164iNoLMIKQr3+v14+XCV6jSjiicA8FL4OHPRgKOdzAhY/6nBf4ZS/Z36r/Usp7MWM=";
String decryptStr = decrypt(orgStr, AESUtils.KEY);
System.out.println(decryptStr);
}
/**
* Generates SHA256 hash of the password which is used as key
*
* @param password used to generated key
* @return SHA256 of the password
*/
private static SecretKeySpec generateKey(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
final MessageDigest digest = MessageDigest.getInstance(HASH_ALGORITHM);
byte[] bytes = password.getBytes("UTF-8");
digest.update(bytes, 0, bytes.length);
byte[] key = digest.digest();
log("SHA-256 key ", key);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
return secretKeySpec;
}
/**
* Encrypt and encode message using 256-bit AES with key generated from password.
*
* @param message the thing you want to encrypt assumed String UTF-8
* @return Base64 encoded CipherText
* @throws GeneralSecurityException if problems occur during encryption
*/
public static String encrypt(String message, String passKey)
throws GeneralSecurityException {
try {
final SecretKeySpec key = generateKey(passKey);
log("message", message);
byte[] cipherText = encrypt(key, ivBytes, message.getBytes(CHARSET));
//NO_WRAP is important as was getting \n at the end
String encoded = Base64.encode(cipherText);
log("Base64.NO_WRAP", encoded);
return encoded;
} catch (UnsupportedEncodingException e) {
throw new GeneralSecurityException(e);
}
}
/**
* More flexible AES encrypt that doesn't encode
*
* @param key AES key typically 128, 192 or 256 bit
* @param iv Initiation Vector
* @param message in bytes (assumed it's already been decoded)
* @return Encrypted cipher text (not encoded)
* @throws GeneralSecurityException if something goes wrong during encryption
*/
public static byte[] encrypt(final SecretKeySpec key, final byte[] iv, final byte[] message)
throws GeneralSecurityException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
final Cipher cipher = Cipher.getInstance(AES_MODE);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] cipherText = cipher.doFinal(message);
log("cipherText", cipherText);
return cipherText;
}
/**
* Decrypt and decode ciphertext using 256-bit AES with key generated from password
*
* @param base64EncodedCipherText the encrpyted message encoded with base64
* @return message in Plain text (String UTF-8)
* @throws GeneralSecurityException if there's an issue decrypting
*/
public static String decrypt(String base64EncodedCipherText, String passKey)
throws GeneralSecurityException {
try {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
final SecretKeySpec key = generateKey(passKey);
log("base64EncodedCipherText", base64EncodedCipherText);
byte[] decodedCipherText = Base64.decode(base64EncodedCipherText);
log("decodedCipherText", decodedCipherText);
byte[] decryptedBytes = decrypt(key, ivBytes, decodedCipherText);
log("decryptedBytes", decryptedBytes);
String message = new String(decryptedBytes, CHARSET);
log("message", message);
return message;
} catch (UnsupportedEncodingException e) {
throw new GeneralSecurityException(e);
}
}
/**
* More flexible AES decrypt that doesn't encode
*
* @param key AES key typically 128, 192 or 256 bit
* @param iv Initiation Vector
* @param decodedCipherText in bytes (assumed it's already been decoded)
* @return Decrypted message cipher text (not encoded)
* @throws GeneralSecurityException if something goes wrong during encryption
*/
public static byte[] decrypt(final SecretKeySpec key, final byte[] iv, final byte[] decodedCipherText)
throws GeneralSecurityException {
final Cipher cipher = Cipher.getInstance(AES_MODE);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] decryptedBytes = cipher.doFinal(decodedCipherText);
log("decryptedBytes", decryptedBytes);
return decryptedBytes;
}
private static void log(String what, byte[] bytes) {
}
private static void log(String what, String value) {
}
/**
* Converts byte array to hexidecimal useful for logging and fault finding
*
* @param bytes
* @return
*/
private static String bytesToHex(byte[] bytes) {
final char[] hexArray = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'A', 'B', 'C', 'D', 'E', 'F'};
char[] hexChars = new char[bytes.length * 2];
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private AESUtils() {
}
}
package com.ihooyah.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
*
* @author shen_feng 加密解密
*/
public class AesUtil {
// static String sKey = "HOPERUN.COM";
/**
* 密钥如超过16位,截至16位,不足16位,补/000至16位
*
* @param key原密钥
* @return 新密钥
*/
public static String secureBytes(String key) {
if (key.length() > 16) {
key = key.substring(0, 16);
} else if (key.length() < 16) {
for (int i = (key.length() - 1); i < 15; i++) {
key += "\000";
}
}
return key;
}
/**
* AES解密 用于数据库储存
*
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String decryptCode(String sSrc, String key) {
String sKey = secureBytes(key);
try {
// 判断Key是否正确
if (sKey == null) {
// LogUtil.d("AesUtil", "Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
// LogUtil.d("AesUtil", "Key长度不是16位");
sKey = secureBytes(sKey);
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = hex2byte(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "GBK");
return originalString;
} catch (Exception e) {
return null;
}
} catch (Exception ex) {
return null;
}
}
/**
* AES解密 用于数据库储存
*
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String decrypt(String sSrc, String key) {
String sKey = secureBytes(key);
try {
// 判断Key是否正确
if (sKey == null) {
// LogUtil.d("AesUtil", "Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
System.out.println("长度不是16");
// LogUtil.d("AesUtil", "Key长度不是16位");
sKey = secureBytes(sKey);
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] encrypted1 = hex2byte(sSrc);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original, "utf-8");
// String originalString = new String(original, "GBK");
return originalString;
} catch (Exception e) {
return null;
}
} catch (Exception ex) {
return null;
}
}
public static String encrypt4Contacts(String sSrc) {
return sSrc;
}
/**
* AES加密
*
* @param sSrc
* @param sKey
* @return
* @throws Exception
*/
public static String encrypt(String sSrc, String key) {
String sKey = secureBytes(key);
try {
if (sSrc == null || sKey == null) {
// LogUtil.d("AesUtil", "Key为空null");
return null;
}
// 判断Key是否为16位
if (sKey.length() != 16) {
// LogUtil.d("AesUtil", "Key长度不是16位");
sKey = secureBytes(sKey);
}
byte[] raw = sKey.getBytes("ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(sSrc.getBytes());
return byte2hex(encrypted).toLowerCase();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* @param strhex
* @return
*/
public static byte[] hex2byte(String strhex) {
if (strhex == null) {
return null;
}
int l = strhex.length();
if (l % 2 == 1) {
return null;
}
byte[] b = new byte[l / 2];
for (int i = 0; i != l / 2; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i * 2, i * 2 + 2),
16);
}
return b;
}
/**
* @param b
* @return
*/
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
}
package com.ihooyah.utils;
import java.io.ByteArrayOutputStream;
public class Base64 {
private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D',
'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,
-1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
-1, -1 };
private Base64() {
}
public static String encode(byte[] data) {
StringBuffer sb = new StringBuffer();
int len = data.length;
int i = 0;
int b1, b2, b3;
while (i < len) {
b1 = data[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
sb.append("==");
break;
}
b2 = data[i++] & 0xff;
if (i == len) {
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4)
| ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
sb.append("=");
break;
}
b3 = data[i++] & 0xff;
sb.append(base64EncodeChars[b1 >>> 2]);
sb.append(base64EncodeChars[((b1 & 0x03) << 4)
| ((b2 & 0xf0) >>> 4)]);
sb.append(base64EncodeChars[((b2 & 0x0f) << 2)
| ((b3 & 0xc0) >>> 6)]);
sb.append(base64EncodeChars[b3 & 0x3f]);
}
return sb.toString();
}
public static byte[] decode(String str) {
byte[] data = str.getBytes();
str = null;
int len = data.length;
ByteArrayOutputStream buf = new ByteArrayOutputStream(len);
int i = 0;
int b1, b2, b3, b4;
while (i < len) {
/* b1 */
do {
b1 = base64DecodeChars[data[i++]];
} while (i < len && b1 == -1);
if (b1 == -1) {
break;
}
/* b2 */
do {
b2 = base64DecodeChars[data[i++]];
} while (i < len && b2 == -1);
if (b2 == -1) {
break;
}
buf.write((int) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
/* b3 */
do {
b3 = data[i++];
if (b3 == 61) {
return buf.toByteArray();
}
b3 = base64DecodeChars[b3];
} while (i < len && b3 == -1);
if (b3 == -1) {
break;
}
buf.write((int) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
/* b4 */
do {
b4 = data[i++];
if (b4 == 61) {
return buf.toByteArray();
}
b4 = base64DecodeChars[b4];
} while (i < len && b4 == -1);
if (b4 == -1) {
break;
}
buf.write((int) (((b3 & 0x03) << 6) | b4));
}
data = null;
return buf.toByteArray();
}
}
\ No newline at end of file
package com.ihooyah.utils;
import lombok.extern.slf4j.Slf4j;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @Author: gedelong
* @Date: 2018/11/8 15:30
*/
@Slf4j
public class DateUtils {
public static final String YYYYMMDD = "yyyyMMdd";
public static final String YYMMDD = "yyMMdd";
public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
/**
* 时间转字符串
*/
public static String dateToString(Date date, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(date);
} catch (Exception e) {
log.error("dateToString方法转换日期失败:" + e.getMessage());
return null;
}
}
/**
* 字符串转时间
*/
public static Date stringToDate(String dateStr, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.parse(dateStr);
} catch (Exception e) {
log.error("stringToDate方法转换日期失败:" + e.getMessage());
return null;
}
}
/**
* 获取N天前的时间
*/
public static Date getDateBeforeDays(Date date, Integer days) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, -days);
return calendar.getTime();
}
/**
* 获取date当天0点时间
*
* @param date
* @return
*/
public static Date getDayBegin(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 获取date当天24点时间
*
* @param date
* @return
*/
public static Date getDayEnd(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return calendar.getTime();
}
/**
* 获取当前时间
*
* @return
*/
public static Date getNowDate() {
return new Date();
}
}
package com.ihooyah.utils;
import java.security.MessageDigest;
/**
* @author ***
* @version V1.0
* @Description
* @Package com.ihooyah.utils
* @date 2022-12-09 17:35
*/
public class MD5Util {
public final static String encodeMd5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4',
'5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
try {
byte[] btInput = s.getBytes();
//获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
//使用指定的字节更新摘要
mdInst.update(btInput);
//获得密文
byte[] md = mdInst.digest();
//把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package com.ihooyah.utils;
import java.util.UUID;
public class UuidCreator {
public static String simpleUUID(){
String uuidStr = UUID.randomUUID().toString();
uuidStr = uuidStr.replace("-","");
return uuidStr;
}
}
package com.ihooyah.utils.coodinate;
import java.io.Serializable;
public class HYCoodinates extends Object implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public double latitude;
public double longitude;
public HYCoodinates() {
}
public HYCoodinates(double lat, double lon) {
this.latitude = lat;
this.longitude = lon;
}
public HYCoodinates(HYCoodinates pCoodinates) {
this.latitude = pCoodinates.getLat();
this.longitude = pCoodinates.getLon();
}
public double getLat() {
return latitude;
}
public double getLon() {
return longitude;
}
public void setLat(double lat) {
this.latitude = lat;
}
public void setLon(double lon) {
this.longitude = lon;
}
public HYCoodinates substract(HYCoodinates pCoordinates) {
double lat = this.latitude - pCoordinates.getLat();
double lon = this.longitude - pCoordinates.getLon();
return new HYCoodinates(lat, lon);
}
public HYCoodinates add(HYCoodinates pCoordinates) {
double lat = this.latitude + pCoordinates.getLat();
double lon = this.longitude + pCoordinates.getLon();
return new HYCoodinates(lat, lon);
}
}
package com.ihooyah.utils.coodinate;
/**
* 坐标系转换类,用来转换各种坐标系
*/
public class HYCoordinateTransform {
public static final double SEMI_MAJOR_AXIS = 6378245.0;
public static final double FLATTENING = 0.00335233;
public static final double SEMI_MINOR_AXIS = SEMI_MAJOR_AXIS * (1.0 - FLATTENING);
private static final double a = SEMI_MAJOR_AXIS;
private static final double b = SEMI_MINOR_AXIS;
public static final double EE = (a * a - b * b) / (a * b);
/**
* WGS84 转 火星坐标
*
* @param wgsLat
* @param wgsLon
* @return
*/
public static HYCoodinates wgs84ToGcj02(double wgsLat, double wgsLon) {
if (isOutOfChina(wgsLat, wgsLon)) {
return new HYCoodinates(wgsLat, wgsLon);
}
double dLat = transformLat(wgsLon - 105.0, wgsLat - 35.0);
double dLon = transformLon(wgsLon - 105.0, wgsLat - 35.0);
double radLat = wgsLat / 180.0 * Math.PI;
double magic = Math.sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((SEMI_MAJOR_AXIS * (1 - EE)) / (magic * sqrtMagic) * Math.PI);
dLon = (dLon * 180.0) / (SEMI_MAJOR_AXIS / sqrtMagic * Math.cos(radLat) * Math.PI);
double gcjLat = wgsLat + dLat;
double gcjLon = wgsLon + dLon;
return new HYCoodinates(gcjLat, gcjLon);
}
/**
* 火星坐标转 WGS84 坐标
*
* @param gcjLat
* @param gcjLon
* @return
*/
public static HYCoodinates gcj02ToWgs84(double gcjLat, double gcjLon) {
HYCoodinates g0 = new HYCoodinates(gcjLat, gcjLon);
HYCoodinates w0 = new HYCoodinates(g0);
HYCoodinates g1 = wgs84ToGcj02(w0.getLat(), w0.getLon());
HYCoodinates w1 = w0.substract(g1.substract(g0));
while (maxAbsDiff(w1, w0) >= 1e-6) {
w0 = w1;
g1 = wgs84ToGcj02(w0.getLat(), w0.getLon());
HYCoodinates gpsDiff = g1.substract(g0);
w1 = w0.substract(gpsDiff);
}
return w1;
}
/**
* 火星坐标 转 大地2000(4490)
*
* @param gcjLat
* @param gcjLon
* @return
*/
public static HYCoodinates gcj02ToWgs4490(double gcjLat, double gcjLon) {
HYCoodinates wgs84 = gcj02ToWgs84(gcjLat, gcjLon);
return wgs84To4490(wgs84.getLat(), wgs84.getLon());
}
/**
* 火星坐标 转 百度坐标
*
* @param gcjLat
* @param gcjLon
* @return
*/
public static HYCoodinates gcj02ToBd09(double gcjLat, double gcjLon) {
double x = gcjLon, y = gcjLat;
double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);
double longitude = z * Math.cos(theta) + 0.0065;
double latitude = z * Math.sin(theta) + 0.006;
return new HYCoodinates(latitude, longitude);
}
/**
* 百度坐标 转 火星坐标
*
* @param bdLat
* @param bdLon
* @return
*/
public static HYCoodinates bd09ToGcj02(double bdLat, double bdLon) {
double x = bdLon - 0.0065, y = bdLat - 0.006;
double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);
double longitude = z * Math.cos(theta);
double latitude = z * Math.sin(theta);
return new HYCoodinates(latitude, longitude);
}
/**
* WGS84 转 百度坐标
*
* @param wgsLat
* @param wgsLon
* @return
*/
public static HYCoodinates wgs84ToBd09(double wgsLat, double wgsLon) {
HYCoodinates gcj02 = HYCoordinateTransform.wgs84ToGcj02(wgsLat, wgsLon);
HYCoodinates bd = HYCoordinateTransform.gcj02ToBd09(gcj02.getLat(),
gcj02.getLon());
return bd;
}
/**
* 百度坐标 转 wgs84
*
* @param bdLat
* @param bdLon
* @return
*/
public static HYCoodinates bd09ToWgs84(double bdLat, double bdLon) {
HYCoodinates gcj02 = HYCoordinateTransform.bd09ToGcj02(bdLat, bdLon);
HYCoodinates wgs84 = HYCoordinateTransform.gcj02ToWgs84(gcj02.getLat(), gcj02.getLon());
return wgs84;
}
//天地图4490 转百度坐标
public static HYCoodinates wgs4490ToBd09(double wgs4490Lat, double wgs4490Lon) {
HYCoodinates wgs84 = new HYCoodinates(wgs4490Lat + 0.0002676, wgs4490Lon + 0.000447);
return HYCoordinateTransform.wgs84ToBd09(wgs84.getLat(), wgs84.getLon());
}
//百度坐标 转 天地图4490
public static HYCoodinates bd09To4490(double bdLat, double bdLon) {
HYCoodinates gcj02 = HYCoordinateTransform.bd09ToGcj02(bdLat, bdLon);
HYCoodinates wgs84 = HYCoordinateTransform.gcj02ToWgs84(gcj02.getLat(), gcj02.getLon());
return new HYCoodinates(wgs84.getLat() - 0.0002676, wgs84.getLon() - 0.000447);
}
//wgs 转 天地图4490
public static HYCoodinates wgs84To4490(double wgs84Lat, double wgs84Lon) {
HYCoodinates wgs4490 = new HYCoodinates(wgs84Lat - 0.0002676, wgs84Lon - 0.000447);
return wgs4490;
}
// 天地图4490 wgs84
public static HYCoodinates wgs4490Towgs84(double wgs4490Lat, double wgs4490Lon) {
HYCoodinates wgs84 = new HYCoodinates(wgs4490Lat + 0.0002676, wgs4490Lon + 0.000447);
return wgs84;
}
private static double maxAbsDiff(HYCoodinates w1, HYCoodinates w0) {
HYCoodinates diff = w1.substract(w0);
double absLatDiff = Math.abs(diff.getLat());
double absLonDiff = Math.abs(diff.getLon());
return (absLatDiff > absLonDiff ? absLatDiff : absLonDiff);
}
private static double transformLon(double x, double y) {
double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
ret = ret + (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
ret = ret + (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
ret = ret + (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x * Math.PI / 30.0)) * 2.0 / 3.0;
return ret;
}
private static double transformLat(double x, double y) {
double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
ret = ret + (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
ret = ret + (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
ret = ret + (160.0 * Math.sin(y / 12.0 * Math.PI) + 320.0 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
return ret;
}
private static boolean isOutOfChina(double wgsLat, double wgsLon) {
if (wgsLat < 0.8293 || wgsLat > 55.8271) {
return true;
}
if (wgsLon < 72.004 || wgsLon > 137.8347) {
return true;
}
return false;
}
public static boolean isInNanjing(double lat, double lon) {
if (lon > 118.125 &&
lon < 119.53125 &&
lat > 31.11328125 &&
lat < 32.6953125) {
return true;
}
return false;
}
}
package com.ihooyah.utils.coodinate;
import java.io.Serializable;
public class SimpleBoundingBox implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public HYCoodinates minPoint;
public HYCoodinates maxPoint;
private static double WGS84_a = 6378137.0; // Major semiaxis [m]
private static double WGS84_b = 6356752.3; // Minor semiaxis [m]
public static SimpleBoundingBox getBoundingBox(HYCoodinates center, Double halfSideInMeter){
double earthRadius = 6371.01 * 1000.0; //in meters
// angular distance in radians on a great circle
double radDist = halfSideInMeter/ earthRadius;
double radLat = Deg2rad(center.getLat()) ;
double radLon = Deg2rad(center.getLon()) ;
double minLat = radLat - radDist;
double maxLat = radLat + radDist;
double minLon, maxLon;
if (minLat > -Math.PI/2 && maxLat < Math.PI/2) {
double deltaLon = Math.asin(Math.sin(radDist) / Math.cos(radLat));
minLon = radLon - deltaLon;
if (minLon < -Math.PI) minLon += 2 * Math.PI;
maxLon = radLon + deltaLon;
if (maxLon > Math.PI) maxLon -= 2 * Math.PI;
} else {
// a pole is within the distance
minLat = Math.max(minLat, -Math.PI/2);
maxLat = Math.min(maxLat, Math.PI/2);
minLon = -Math.PI;
maxLon = Math.PI;
}
SimpleBoundingBox box = new SimpleBoundingBox();
box.minPoint = new HYCoodinates(Rad2deg(minLat), Rad2deg(minLon));
box.maxPoint = new HYCoodinates(Rad2deg(maxLat), Rad2deg(maxLon));
return box;
}
// degrees to radians
private static double Deg2rad(double degrees)
{
return Math.PI * degrees / 180.0;
}
// radians to degrees
private static double Rad2deg(double radians)
{
return 180.0 * radians / Math.PI;
}
private static double WGS84EarthRadius(double lat)
{
// http://en.wikipedia.org/wiki/Earth_radius
double An = WGS84_a * WGS84_a * Math.cos(lat);
double Bn = WGS84_b * WGS84_b * Math.sin(lat);
double Ad = WGS84_a * Math.cos(lat);
double Bd = WGS84_b * Math.sin(lat);
return Math.sqrt((An*An + Bn*Bn) / (Ad*Ad + Bd*Bd));
}
}
package com.ihooyah.utils.des;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.SecureRandom;
public class DesUtil {
private final static String DES = "DES";
public static void main(String[] args) throws Exception {
String data = "123 456";
String key = "wow!@#$%";
System.err.println(encrypt(data, key));
System.err.println(decrypt(encrypt(data, key), key));
}
/**
* Description 根据键值进行加密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
public static String encrypt(String data, String key) throws Exception {
byte[] bt = encrypt(data.getBytes(), key.getBytes());
String strs = new BASE64Encoder().encode(bt);
return strs;
}
/**
* Description 根据键值进行解密
* @param data
* @param key 加密键byte数组
* @return
* @throws IOException
* @throws Exception
*/
public static String decrypt(String data, String key) throws IOException,
Exception {
if (data == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(buf,key.getBytes());
return new String(bt);
}
/**
* Description 根据键值进行加密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
/**
* Description 根据键值进行解密
* @param data
* @param key 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
}
\ No newline at end of file
package com.ihooyah.utils.gis.coodinate;
public class EvilTransform {
public static final double SEMI_MAJOR_AXIS = 6378245.0;
public static final double FLATTENING = 0.00335233;
public static final double SEMI_MINOR_AXIS = SEMI_MAJOR_AXIS * (1.0 - FLATTENING);
private static final double a = SEMI_MAJOR_AXIS;
private static final double b = SEMI_MINOR_AXIS;
public static final double EE = (a * a - b * b) / (a * b);
// wgs84 转火星坐标
public static SimpleCoodinates wgs84ToGcj02(double wgsLat, double wgsLon) {
if (isOutOfChina(wgsLat, wgsLon)) {
return new SimpleCoodinates(wgsLat, wgsLon);
}
double dLat = transformLat(wgsLon - 105.0, wgsLat - 35.0);
double dLon = transformLon(wgsLon - 105.0, wgsLat - 35.0);
double radLat = wgsLat / 180.0 * Math.PI;
double magic = Math.sin(radLat);
magic = 1 - EE * magic * magic;
double sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / ((SEMI_MAJOR_AXIS * (1 - EE)) / (magic * sqrtMagic) * Math.PI);
dLon = (dLon * 180.0) / (SEMI_MAJOR_AXIS / sqrtMagic * Math.cos(radLat) * Math.PI);
double gcjLat = wgsLat + dLat;
double gcjLon = wgsLon + dLon;
return new SimpleCoodinates(gcjLat, gcjLon);
}
public static SimpleCoodinates gcj02ToWgs4490(double gcjLat, double gcjLon) {
SimpleCoodinates g0 = new SimpleCoodinates(gcjLat, gcjLon);
SimpleCoodinates w0 = new SimpleCoodinates(g0);
SimpleCoodinates g1 = wgs84ToGcj02(w0.getLat(), w0.getLon());
SimpleCoodinates w1 = w0.substract(g1.substract(g0));
while (maxAbsDiff(w1, w0) >= 1e-6) {
w0 = w1;
g1 = wgs84ToGcj02(w0.getLat(), w0.getLon());
SimpleCoodinates gpsDiff = g1.substract(g0);
w1 = w0.substract(gpsDiff);
}
return wgs84To4490(w1.getLat(), w1.getLon());
}
/**
* gcj2wgs <- function(gcjLat, gcjLon){ g0 <- c(gcjLat, gcjLon) w0 <- g0 g1
* <- wgs2gcj(w0[1], w0[2]) w1 <- w0 - (g1 - g0) while(max(abs(w1 - w0)) >=
* 1e-6){ w0 <- w1 g1 <- wgs2gcj(w0[1], w0[2]) w1 <- w0 - (g1 - g0) }
* return(data.frame(lat = w1[1], lng = w1[2]))
*
* @param gcjLat
* @param gcjLon
* @return
*/
// 火星坐标转wgs84坐标
public static SimpleCoodinates gcj02ToWgs84(double gcjLat, double gcjLon) {
SimpleCoodinates g0 = new SimpleCoodinates(gcjLat, gcjLon);
SimpleCoodinates w0 = new SimpleCoodinates(g0);
SimpleCoodinates g1 = wgs84ToGcj02(w0.getLat(), w0.getLon());
SimpleCoodinates w1 = w0.substract(g1.substract(g0));
while (maxAbsDiff(w1, w0) >= 1e-6) {
w0 = w1;
g1 = wgs84ToGcj02(w0.getLat(), w0.getLon());
SimpleCoodinates gpsDiff = g1.substract(g0);
w1 = w0.substract(gpsDiff);
}
return w1;
}
public static SimpleCoodinates gcj02To4490(double gcjLat, double gcjLon) {
SimpleCoodinates coodinates84 = gcj02ToWgs84(gcjLat, gcjLon);
return wgs84To4490(coodinates84.getLat(), coodinates84.getLon());
}
// public static SimpleCoodinates gcj02ToWgs4490(double gcjLat, double gcjLon) {
// SimpleCoodinates wgs84 = gcj02ToWgs84(gcjLat, gcjLon);
// return wgs84To4490(wgs84.getLat(), wgs84.getLon());
// }
// 火星坐标转百度坐标
public static SimpleCoodinates gcj02ToBd09(double gcjLat, double gcjLon) {
double x = gcjLon, y = gcjLat;
double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI);
double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI);
double longitude = z * Math.cos(theta) + 0.0065;
double latitude = z * Math.sin(theta) + 0.006;
return new SimpleCoodinates(latitude, longitude);
}
// 百度坐标转火星坐标
public static SimpleCoodinates bd09ToGcj02(double bdLat, double bdLon) {
double x = bdLon - 0.0065, y = bdLat - 0.006;
double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);
double longitude = z * Math.cos(theta);
double latitude = z * Math.sin(theta);
return new SimpleCoodinates(latitude, longitude);
}
// wgs84 转百度坐标
public static SimpleCoodinates wgs84ToBd09(double wgsLat, double wgsLon) {
SimpleCoodinates gcj02 = EvilTransform.wgs84ToGcj02(wgsLat, wgsLon);
SimpleCoodinates bd = EvilTransform.gcj02ToBd09(gcj02.getLat(), gcj02.getLon());
return bd;
}
// 百度坐标 转 wgs84
public static SimpleCoodinates bd09ToWgs84(double bdLat, double bdLon) {
SimpleCoodinates gcj02 = EvilTransform.bd09ToGcj02(bdLat, bdLon);
SimpleCoodinates wgs84 = EvilTransform.gcj02ToWgs84(gcj02.getLat(), gcj02.getLon());
return wgs84;
}
// 天地图4490 转百度坐标
// public static SimpleCoodinates wgs4490ToBd09(double wgs4490Lat, double wgs4490Lon) {
//
// SimpleCoodinates wgs84 = new SimpleCoodinates(wgs4490Lat + 0.0002676, wgs4490Lon + 0.000447);
// return EvilTransform.wgs84ToBd09(wgs84.getLat(), wgs84.getLon());
//
// }
// 百度坐标 转 天地图4490
public static SimpleCoodinates bd09To4490(double bdLat, double bdLon) {
SimpleCoodinates gcj02 = EvilTransform.bd09ToGcj02(bdLat, bdLon);
SimpleCoodinates wgs84 = EvilTransform.gcj02ToWgs84(gcj02.getLat(), gcj02.getLon());
return new SimpleCoodinates(wgs84.getLat() - 0.0002676, wgs84.getLon() - 0.000447);
// wgs84To4490Request(acitiy, wgs84.getLat(), wgs84.getLon(), listener);
}
// wgs 转 天地图4490
public static SimpleCoodinates wgs84To4490(double wgs84Lat, double wgs84Lon) {
SimpleCoodinates wgs4490 = new SimpleCoodinates(wgs84Lat - 0.0002676, wgs84Lon - 0.000447);
return wgs4490;
}
// 4490 转 天地图 gcj02
public static SimpleCoodinates w4490Togcj02(double w4490Lat, double w4490Lon) {
SimpleCoodinates simpleCoodinates = wgs4490Towgs84(w4490Lat, w4490Lon);
SimpleCoodinates simpleCoodinates1 = wgs84ToGcj02(simpleCoodinates.latitude, simpleCoodinates.longitude);
return simpleCoodinates1;
}
// 天地图4490 wgs84
public static SimpleCoodinates wgs4490Towgs84(double wgs4490Lat, double wgs4490Lon) {
SimpleCoodinates wgs84 = new SimpleCoodinates(wgs4490Lat + 0.0002676, wgs4490Lon + 0.000447);
return wgs84;
}
private static double maxAbsDiff(SimpleCoodinates w1, SimpleCoodinates w0) {
SimpleCoodinates diff = w1.substract(w0);
double absLatDiff = Math.abs(diff.getLat());
double absLonDiff = Math.abs(diff.getLon());
return (absLatDiff > absLonDiff ? absLatDiff : absLonDiff);
}
private static double EARTH_RADIUS = 6378.137;
private static double rad(double d) {
return d * Math.PI / 180.0;
}
public static double getDistance(double lat1, double lng1, double lat2,
double lng2) {
double radLat1 = rad(lat1);
double radLat2 = rad(lat2);
double a = radLat1 - radLat2;
double b = rad(lng1) - rad(lng2);
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
+ Math.cos(radLat1) * Math.cos(radLat2)
* Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = Math.round(s * 10000) / 10;
return s;
}
private static double transformLon(double x, double y) {
double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
ret = ret + (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
ret = ret + (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
ret = ret + (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x * Math.PI / 30.0)) * 2.0 / 3.0;
return ret;
}
private static double transformLat(double x, double y) {
double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
ret = ret + (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
ret = ret + (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
ret = ret + (160.0 * Math.sin(y / 12.0 * Math.PI) + 320.0 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
return ret;
}
private static boolean isOutOfChina(double wgsLat, double wgsLon) {
if (wgsLat < 0.8293 || wgsLat > 55.8271) {
return true;
}
if (wgsLon < 72.004 || wgsLon > 137.8347) {
return true;
}
return false;
}
public static boolean isInNanjing(double lat, double lon) {
if (lon > 118.125 && lon < 119.53125 && lat > 31.11328125 && lat < 32.6953125) {
return true;
}
return false;
}
public static void main(String[] args) {
//118.678454384295,31.9451261290794
SimpleCoodinates simpleCoodinates=wgs84To4490(32.0825467547779,118.89079179042);
SimpleCoodinates simpleCoodinates1=wgs4490Towgs84(32.0822032351443,118.890437668687 );
System.out.println(simpleCoodinates.getLat()+","+simpleCoodinates.getLon());
System.out.println(simpleCoodinates1.getLat()+","+simpleCoodinates1.getLon());
}
}
package com.ihooyah.utils.gis.coodinate;
import java.io.Serializable;
public class HYCoodinates extends Object implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public double latitude;
public double longitude;
public HYCoodinates() {
}
public HYCoodinates(double lat, double lon) {
this.latitude = lat;
this.longitude = lon;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
}
package com.ihooyah.utils.gis.coodinate;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
/**
* @Description 虎牙科技坐标转换服务工具类
* @Author: 王尧 / wangyao@ihooyah.com
* @CreateDate: 2020-03-07 21:57:41
* @Version: [V-1.0]
**/
public class HYCoordinateTransform {
// private static final String coordinateTransFromUrl = "https://open.ihooyah.com/api/gis/coordinate-transfrom";
private static final String coordinateTransFromUrl = "https://spgj.njga.gov.cn:8443/gis/coordinate-transfrom";
private static final String appKey = "sjJSGEpIM8vTxmKG";
private static final String appSecret = "a6c22c749ea74a7a1abbe19c7862f70a2a35dca0";
/**
* 初始化网络请求 RestTemplate
*
* @author: 王尧 / wangyao@ihooyah.com
* @createDate: 22:05
*/
static RestTemplate initRestTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setConnectTimeout(30000);
return new RestTemplate(requestFactory);
}
/**
* WGS84 转 WGS84P
*
* @author: 王尧 / wangyao@ihooyah.com
* @createDate: 22:01
*/
public static HYCoodinates wgs84ToWgs84P(String lat, String lng) {
try {
return requestSend(lat, lng, "WGS84toWGS84P");
} catch (Exception e) {
e.printStackTrace();
return new HYCoodinates(0.0D, 0.0D);
}
}
public static HYCoodinates wgs84Togaode(String lat, String lng) {
try {
return requestSend(lat, lng, "WGS84toGCJ02");
} catch (Exception e) {
e.printStackTrace();
return new HYCoodinates(0.0D, 0.0D);
}
}
/**
* WGS84P 转 WGS84
*
* @author: 王尧 / wangyao@ihooyah.com
* @createDate: 22:02
*/
public static HYCoodinates wgs84PToWgs84(String lat, String lng) {
try {
return requestSend(lat, lng, "WGS84PtoWGS84");
} catch (Exception e) {
e.printStackTrace();
return new HYCoodinates(0.0D, 0.0D);
}
}
/**
* 发送请求
*
* @author: 王尧 / wangyao@ihooyah.com
* @createDate: 23:21
*/
static HYCoodinates requestSend(String lat, String lng, String transfromType) throws Exception {
//入参
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("locations", lng + "," + lat);
params.add("transfromType", transfromType);
//header
MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
header.add("appKey", appKey);
header.add("appSecret", appSecret);
//初始化网络请求句柄
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, header);
RestTemplate restTemplate = initRestTemplate();
//发送网络请求
JSONObject jsonObject = restTemplate.postForObject(coordinateTransFromUrl, httpEntity, JSONObject.class);
if (jsonObject.getInteger("code") == 200) {
JSONArray jsonArray = jsonObject.getJSONArray("result");
if (jsonArray.size() > 0) {
JSONObject coordinateObject = jsonArray.getJSONObject(0);
//{ "latitude":31.949390704834798, "longitude":118.69000082057063 }
double latV = coordinateObject.getDouble("latitude");
double lntV = coordinateObject.getDouble("longitude");
return new HYCoodinates(latV, lntV);
}
}
return new HYCoodinates(0.0D, 0.0D);
}
public static void main(String[] args) {
//118.678454384295,31.9451261290794
HYCoodinates hyCoodinates = wgs84ToWgs84P("31.9451261290794", "118.678454384295");
System.out.println(hyCoodinates.getLatitude()+","+hyCoodinates.getLongitude());
}
}
package com.ihooyah.utils.gis.coodinate;
public class SimpleCoodinates {
public double latitude;
public double longitude;
public SimpleCoodinates(double lat, double lon) {
this.latitude = lat;
this.longitude = lon;
}
public SimpleCoodinates(SimpleCoodinates pCoodinates) {
this.latitude = pCoodinates.getLat();
this.longitude = pCoodinates.getLon();
}
public double getLat() {
return latitude;
}
public double getLon() {
return longitude;
}
public void setLat(double lat) {
this.latitude = lat;
}
public void setLon(double lon) {
this.longitude = lon;
}
public SimpleCoodinates substract(SimpleCoodinates pCoordinates) {
double lat = this.latitude - pCoordinates.getLat();
double lon = this.longitude - pCoordinates.getLon();
return new SimpleCoodinates(lat, lon);
}
@Override
public String toString() {
return "SimpleCoodinates{" +
"latitude=" + latitude +
", longitude=" + longitude +
'}';
}
}
package com.ihooyah.utils.http;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtils {
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
/**
* 发送post请求
*
* @param url
* @param dataMap
* @return
* @throws Exception
*/
public static String sendPost(String url, Map<String, String> dataMap) {
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> list = new ArrayList<>(dataMap.size());
dataMap.forEach((key, value) -> {
list.add(new BasicNameValuePair(key, value));
});
try {
httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse httpResponse = httpClient.execute(httpPost);
return EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (Exception e) {
log.error("请求发送失败: ", e);
}
return null;
}
}
package com.ihooyah.utils.http;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.lang.reflect.Field;
import java.util.Map;
/**
* @Author: gedelong
* @Date: 2018/11/26 18:37
*/
@Slf4j
public class HttpUtils {
/**
* 上传josn
* @return
*/
public static <T> T postJson(RestTemplate restTemplate,String url,Object object,Class<T> responseType) {
try {
HttpHeaders headers = new HttpHeaders();
MediaType mediaType = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(mediaType);
String requestJson = JSON.toJSONString(object);
HttpEntity<String> entity = new HttpEntity<>(requestJson,headers);
return restTemplate.postForObject(url, entity, responseType);
}catch (Exception e){
log.info("postJson方法发生异常");
e.printStackTrace();
return null;
}
}
/**
* post请求返回结果泛型
*/
public static <T> T httpPost(RestTemplate restTemplate, String url,Object object,Class<T> responseType){
try {
MultiValueMap<String, Object> param = paramsInit(null,null,object);
return restTemplate.postForObject(url, param,responseType);
}catch (Exception e){
log.info("uploadFile方法异常");
e.printStackTrace();
return null;
}
}
/**
* post请求返回结果String
*/
public static String httpPost(RestTemplate restTemplate, String url,Object object){
try {
MultiValueMap<String, Object> param = paramsInit(null,null,object);
return restTemplate.postForObject(url, param,String.class);
}catch (Exception e){
log.info("uploadFile方法异常");
e.printStackTrace();
return null;
}
}
/**
* post请求返回结果泛型 支持上传文件
* @return
*/
public static <T> T httpPost(RestTemplate restTemplate, String url,
File file,String fileName,Object object,Class<T> responseType){
try {
MultiValueMap<String, Object> param = paramsInit(file,fileName,object);
return restTemplate.postForObject(url, param,responseType);
}catch (Exception e){
log.info("uploadFile方法异常");
e.printStackTrace();
return null;
}
}
/**
* post请求返回结果String 支持上传文件
* @return
*/
public static String httpPost(RestTemplate restTemplate, String url,
File file,String fileName,Object object){
try {
MultiValueMap<String, Object> param = paramsInit(file,fileName,object);
return restTemplate.postForObject(url, param,String.class);
}catch (Exception e){
log.info("uploadFile方法异常");
e.printStackTrace();
return null;
}
}
/**
* post请求返回结果String 单独上传文件
* @return
*/
public static String httpPost(RestTemplate restTemplate, String url,
File file,String fileName){
try {
MultiValueMap<String, Object> param = paramsInit(file,fileName,null);
return restTemplate.postForObject(url, param,String.class);
}catch (Exception e){
log.info("uploadFile方法异常");
e.printStackTrace();
return null;
}
}
public static MultiValueMap<String, Object> paramsInit(File file,String fileName,Object object){
try {
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
if(file!=null){
FileSystemResource resource = new FileSystemResource(file);
param.add(fileName, resource);
}
if(object != null){
if(object instanceof Map){
Map<String,String> params = (Map<String, String>) object;
for(String key : params.keySet()){
param.add(key,params.get(key));
}
}else {
Field[] fields = object.getClass().getDeclaredFields();
for(Field field : fields){
field.setAccessible(true);
if(field.get(object) != null){
param.add(field.getName(),field.get(object));
}
}
}
}
return param;
}catch (Exception e){
log.error("paramsInit方法异常");
e.printStackTrace();
return null;
}
}
}
package com.ihooyah.utils.image;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
*
* 网证Api 3.
* 图片转 base64编码
*
*/
public class ImageBase64Util {
/**
* @Description: 将base64编码字符串转换为图片
* @Author:
* @CreateTime:
* @param imgStr base64编码字符串
* @param path 图片路径-具体到文件
* @return
*/
public static boolean generateImage(String imgStr, String path) {
if (imgStr == null)
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
OutputStream out = new FileOutputStream(path);
out.write(b);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
/**
* @Title: GetImageStrFromUrl
* @Description: TODO(将一张网络图片转化成Base64字符串)
* @param imgURL 网络资源位置
* @return Base64字符串
*/
public static String GetImageStrFromUrl(String imgURL) {
byte[] data = null;
try {
// 创建URL
URL url = new URL(imgURL);
// 创建链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(20 * 1000);
// InputStream inStream = conn.getInputStream();
InputStream inStream = conn.getInputStream();
//得到图片的二进制数据,以二进制封装得到数据,具有通用性
data = readInputStream(inStream);
//data = new byte[inStream.available()];
inStream.read(data);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回Base64编码过的字节数组字符串
return encoder.encode(data);
}
private static byte[] readInputStream(InputStream inStream){
try {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//创建一个Buffer字符串
byte[] buffer = new byte[1024];
//每次读取的字符串长度,如果为-1,代表全部读取完毕
int len = 0;
//使用一个输入流从buffer里把数据读取出来
while( (len=inStream.read(buffer)) != -1 ){
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
//关闭输入流
inStream.close();
//把outStream里的数据写入内存
return outStream.toByteArray();
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
/**
* @Description: 根据图片地址转换为base64编码字符串
* @Author:
* @CreateTime:
* @return
*/
public static String getImageStr(String imgFile) {
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 加密
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
/**
* base64图片转换为BufferdImage
* @param base64String
* @return
*/
public static BufferedImage getImageFromBase64(String base64String) {
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes1 = decoder.decodeBuffer(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
return bi1;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
package com.ihooyah.utils.pattern;
import java.util.regex.Pattern;
/**
* 正则工具类
*
* @author LiuJinLiang
* @date 2018/6/21 10:53
*/
public class PatternUtils {
//8-20位, 必须包含数字和字母
//用户名验证
public static final Pattern DIGIT_AND_LETTER_PATTERN = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$");
//手机号验证
public static final Pattern PHONE_PATTERN = Pattern.compile("^[1][0-9]{10}$");
//数字
public static final Pattern NUMBER_PATTERN = Pattern.compile("^\\d+$");
//字母数字下划线
public static final Pattern NUMBER_LETTER_PATTERN = Pattern.compile("^[0-9a-zA-Z_]{1,40}$");
//字母数字下划线中文
public static final Pattern TAG_LETTER_PATTERN = Pattern.compile("^(?!\\d+$)[A-Za-z0-9\\u4e00-\\u9fa5]+$");
public static boolean matchPhone(String str) {
return PHONE_PATTERN.matcher(str).matches();
}
public static boolean matchNumber(String str) {
return NUMBER_PATTERN.matcher(str).matches();
}
//标签
public static boolean matchTag(String str) {
return TAG_LETTER_PATTERN.matcher(str).matches();
}
//采集图层表名称
public static boolean matchGatherLayerTable(String str) {
return NUMBER_LETTER_PATTERN.matcher(str).matches();
}
}
package com.ihooyah.utils.safety;
import com.alibaba.fastjson.JSON;
import com.ihooyah.utils.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.Security;
import java.util.Map;
/**
* <pre>
* 文件名: DES.java
* 作 者: lijianqiang
* 描 述: DES加密解密
*
* </pre>
*/
public final class DES {
private static String keyString = "267ac2ed67f292ff77c4a0b8";
private static String vec = "12345678";
private static String cString = "DESede/CBC/PKCS7Padding";// "DESede/CBC/PKCS7Padding";
/**
* DES加密
*
* @param encryptString
* @return
* @throws Exception
*/
public static String encryptDES(String encryptString) throws Exception {
Key deskey = new SecretKeySpec(keyString.getBytes(), cString);
Security.addProvider(new BouncyCastleProvider()); // add
Cipher cipher = Cipher.getInstance(cString);
IvParameterSpec ips = new IvParameterSpec(vec.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(encryptString.getBytes());
return Base64.encode(bOut);
}
/**
* DES解密
*
* @param decryptString
* @return
* @throws Exception
*/
public static String decryptDES(String decryptString) throws Exception {
byte[] data = Base64.decode(decryptString);
Security.addProvider(new BouncyCastleProvider()); // add
Key deskey = new SecretKeySpec(keyString.getBytes(), cString);
Cipher cipher = Cipher.getInstance(cString);
IvParameterSpec ips = new IvParameterSpec(vec.getBytes());
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte decryptedData[] = cipher.doFinal(data);
return new String(decryptedData);
}
/**
* DES解密
*
* @param decryptString
* @param cryptKey
* @return
* @throws Exception
*/
public static String decryptDES(String decryptString, String cryptKey) throws Exception {
byte[] data = Base64.decode(decryptString);
Key deskey = new SecretKeySpec(cryptKey.getBytes(), cString);
Cipher cipher = Cipher.getInstance(cString);
IvParameterSpec ips = new IvParameterSpec(vec.getBytes());
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte decryptedData[] = cipher.doFinal(data);
return new String(decryptedData);
}
/**
* 获取URL后端加密字符串
*
* @return
*/
public static String getDesParam(Map<String, Object> map) {
String paramData = null;
try {
String jsonString = JSON.toJSONString(map);
try {
paramData = encryptDES(jsonString);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return paramData;
}
}
/*
* Copyright (C), 2002-2013, 苏宁易购电子商务有限公司
* FileName: DesUtil.java
* Author: 韩志勇
* Date: 2013-12-5 下午08:36:17
* Description: //模块目的、功能描述
* History: //修改记录
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.ihooyah.utils.safety;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.IOException;
import java.security.SecureRandom;
/**
* 加密解密模块<br>
*
* @author 韩志勇
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
@SuppressWarnings("restriction")
public class DesUtil {
private final static String DES = "DES";
private static final String KEY = "523490fjioq9&8*90x98fasdlld0*d^989834JJ)98^%&46#%87941hk(979&*(&(hjo52349(&((yhih2399(7988&*(^^&9rweqe09giq#opd9f03j4jkl4;13pew*";
public static void main(String[] args) throws Exception {
System.out.println(encrypt("20-" + System.currentTimeMillis()));
}
/**
* Description 根据键值进行加密
*
* @param data
* @param key_ali
* 加密键byte数组
* @return
* @throws Exception
*/
public static String encrypt(String data) throws Exception {
byte[] bt = encrypt(data.getBytes(), KEY.getBytes());
String strs = new BASE64Encoder().encode(bt);
return strs;
}
/**
* Description 根据键值进行解密
*
* @param data
* @param key_ali
* 加密键byte数组
* @return
* @throws IOException
* @throws Exception
*/
public static String decrypt(String data) throws IOException, Exception {
if (data == null)
return null;
BASE64Decoder decoder = new BASE64Decoder();
byte[] buf = decoder.decodeBuffer(data);
byte[] bt = decrypt(buf, KEY.getBytes());
return new String(bt);
}
/**
* Description 根据键值进行加密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
/**
* Description 根据键值进行解密
*
* @param data
* @param key
* 加密键byte数组
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
// 生成一个可信任的随机数源
SecureRandom sr = new SecureRandom();
// 从原始密钥数据创建DESKeySpec对象
DESKeySpec dks = new DESKeySpec(key);
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher对象实际完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
return cipher.doFinal(data);
}
}
package com.ihooyah.utils.safety;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 加密工具:md5 sha1
*
* @author
*/
public abstract class EncriptUtil {
/**
* md5 等同于DigestUtils.md5Hex("");
*/
public static final String MD5 = "md5";
/**
* sha1
*/
public static final String SHA1 = "sha-1";
public static final String CHARSET_UTF8 = "UTF8";
public static final String CHARSET_GBK = "GBK";
private static final Log LOG = LogFactory.getLog(EncriptUtil.class);
/**
* 默认加密方式-使用MD5加密
*
* @param painTxt
* @param charset
* @return
*/
public static String encript(String painTxt, String charset) {
return encrypt(painTxt, MD5, charset);
}
/**
* md5或者sha-1加密
*
* @param inputText 要加密的内容
* @param algorithmName 加密算法名称:md5或者sha-1,不区分大小写
* @return
*/
public static String encrypt(String inputText, String algorithmName, String charset) {
if (inputText == null || "".equals(inputText.trim())) {
throw new IllegalArgumentException("请输入要加密的内容");
}
if (algorithmName == null || "".equals(algorithmName.trim())) {
algorithmName = "md5";
}
String encryptText = null;
try {
MessageDigest m = MessageDigest.getInstance(algorithmName);
m.update(inputText.getBytes(charset));
byte[] s = m.digest();
return hex(s);
} catch (NoSuchAlgorithmException e) {
LOG.warn(e.toString());
} catch (UnsupportedEncodingException e) {
LOG.warn(e.toString());
}
return encryptText;
}
/**
* 返回十六进制字符串
*/
private static String hex(byte[] arr) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; ++i) {
sb.append(Integer.toHexString((arr[i] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
}
public static void main(String[] args) {
String password = "111111";
System.out.println(EncriptUtil.encript(password, CHARSET_UTF8));
}
}
/*
* Copyright (C), 2002-2014, 365金融研发中心
* FileName: //文件名
* Author: Administrator
* Date: 2014年12月19日 下午4:00:01
* Description: //模块目的、功能描述
* History: //修改记录
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.ihooyah.utils.safety;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
/**
* 〈一句话功能简述〉 〈功能详细描述〉
*
* @author Administrator
*/
public class LoginRSAUtil {
private static final Log LOG = LogFactory.getLog(LoginRSAUtil.class);
/**
* 获取公私钥对象初始化
*
* @param request
*/
public static void rsaInit(HttpServletRequest request) {
try {
KeyPair kp = RSAUtil.generateKeyPair(); // 获取随机生成的公私钥对象
RSAPublicKey pubKey = (RSAPublicKey) kp.getPublic(); // 获取RSA的公钥
String module = pubKey.getModulus().toString(16);
String exponent = pubKey.getPublicExponent().toString(16);
request.setAttribute("m", module);
request.setAttribute("e", exponent);
HttpSession hs = request.getSession();
RSAPrivateKey privKey = (RSAPrivateKey) kp.getPrivate();
hs.setAttribute("privKey", privKey); // 私钥放入session
hs.setAttribute("p5", EncriptUtil.encript(privKey.getPrivateExponent().toString(16), "UTF-8"));
} catch (Exception e) {
LOG.error("获取公私钥对象异常", e);
}
}
/**
* 解密密码字段
*
* @param request
* @param password
* @return
*/
public static String rsaDecode(HttpServletRequest request, String password) {
HttpSession hs = request.getSession();
String p5 = request.getParameter("p5");
try {
RSAPrivateKey privKey = (RSAPrivateKey) hs.getAttribute("privKey");
// 判断私钥是否失效。init时存入session,同事放入页面,登录时判定两处是否一致。
if (p5.equals(EncriptUtil.encript(privKey.getPrivateExponent().toString(16), "UTF-8"))) {
byte[] en_result = LoginRSAUtil.hexStringToBytes(password);
byte[] de_result = RSAUtil.decrypt(privKey, en_result);
StringBuffer sb = new StringBuffer();
sb.append(new String(de_result));
password = sb.reverse().toString();
return password;
} else {
return null;
}
} catch (Exception e) {
LOG.info("私钥解密失败:" + e.getMessage());
return null;
}
}
/**
* 16进制 To byte[]
*
* @param hexString
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
*
* @param c
* char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}
package com.ihooyah.utils.safety;
import java.security.MessageDigest;
public class MD5Util {
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
return resultSb.toString();
}
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString
.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString
.getBytes(charsetname)));
} catch (Exception exception) {
}
return resultString;
}
public static String MD5Encode(String origin) {
return MD5Encode(origin, "utf-8");
}
private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
}
package com.ihooyah.utils.safety;
import java.util.UUID;
/**
* @author 王尧 【wangyao@ihooyah.com】
* @description
* @create 2017-10-25 下午1:34
**/
public class PasswordUtil {
private static final String SPT = "|";
/**
* 获取用户密码加盐信息
* @return salt
* @author 王尧 【wangyao@ihooyah.com】
* @date 2017/10/25 下午1:42
**/
public static String getSalt(){
String salt = EncriptUtil.encript(UUID.randomUUID().toString(), "UTF-8");
return salt;
}
/**
* 获取用户加密密码
* @param originalPwd 原始密码
* @return
* @author 王尧 【wangyao@ihooyah.com】
* @date 2017/10/25 下午1:37
**/
public static String getCryptoPwd(String originalPwd,String salt) {
String pwdMd5 = EncriptUtil.encript(originalPwd, "UTF-8");
pwdMd5 = pwdMd5 + SPT + salt;
return EncriptUtil.encript(pwdMd5, "UTF-8");
}
}
package com.ihooyah.utils.safety;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
/**
* RSA 工具类。提供加密,解密,生成密钥对等方法。 需要到http://www.bouncycastle.org下载bcprov-jdk14-123.jar。
*
*/
public class RSAUtil {
/**
* * 生成密钥对 *
*
* @return KeyPair *
* @throws EncryptException
*/
public static KeyPair generateKeyPair() throws Exception {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
new org.bouncycastle.jce.provider.BouncyCastleProvider());
final int KEY_SIZE = 1024;// 没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
keyPairGen.initialize(KEY_SIZE, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
return keyPair;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* * 生成公钥 *
*
* @param modulus *
* @param publicExponent *
* @return RSAPublicKey *
* @throws Exception
*/
public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
try {
return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}
/**
* * 生成私钥 *
*
* @param modulus *
* @param privateExponent *
* @return RSAPrivateKey *
* @throws Exception
*/
public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus, byte[] privateExponent) throws Exception {
KeyFactory keyFac = null;
try {
keyFac = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
} catch (NoSuchAlgorithmException ex) {
throw new Exception(ex.getMessage());
}
RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(modulus), new BigInteger(privateExponent));
try {
return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
} catch (InvalidKeySpecException ex) {
throw new Exception(ex.getMessage());
}
}
/**
* * 加密 *
*
* @param key 加密的密钥 *
* @param data 待加密的明文数据 *
* @return 加密后的数据 *
* @throws Exception
*/
public static byte[] encrypt(PublicKey pk, byte[] data) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.ENCRYPT_MODE, pk);
int blockSize = cipher.getBlockSize();// 获得加密块大小,如:加密前数据为128个byte,而key_size=1024
// 加密块大小为127
// byte,加密后为128个byte;因此共有2个加密块,第一个127
// byte第二个为1个byte
int outputSize = cipher.getOutputSize(data.length);// 获得加密块加密后块大小
int leavedSize = data.length % blockSize;
int blocksSize = leavedSize != 0 ? data.length / blockSize + 1 : data.length / blockSize;
byte[] raw = new byte[outputSize * blocksSize];
int i = 0;
while (data.length - i * blockSize > 0) {
if (data.length - i * blockSize > blockSize)
cipher.doFinal(data, i * blockSize, blockSize, raw, i * outputSize);
else
cipher.doFinal(data, i * blockSize, data.length - i * blockSize, raw, i * outputSize);
// 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到
// ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了
// OutputSize所以只好用dofinal方法。
i++;
}
return raw;
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* * 解密 *
*
* @param key 解密的密钥 *
* @param raw 已经加密的数据 *
* @return 解密后的明文 *
* @throws Exception
*/
public static byte[] decrypt(PrivateKey pk, byte[] raw) throws Exception {
try {
Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, pk);
int blockSize = cipher.getBlockSize();
ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
int j = 0;
while (raw.length - j * blockSize > 0) {
bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
j++;
}
return bout.toByteArray();
} catch (Exception e) {
throw new Exception(e.getMessage());
}
}
/**
* * *
*
* @param args *
* @throws Exception
*/
// public static void main(String[] args) throws Exception {
// RSAPublicKey rsap = (RSAPublicKey) RSAUtil.generateKeyPair().getPublic();
// String test = "hello world";
// byte[] en_test = encrypt(getKeyPair().getPublic(), test.getBytes());
// byte[] de_test = decrypt(getKeyPair().getPrivate(), en_test);
// System.out.println(new String(de_test));
// }
}
/*
* Copyright (C), 2002-2015, 苏宁易购电子商务有限公司
* FileName: AuthConstant.java
* Author: Administrator
* Date: 2015年3月8日 上午11:05:26
* Description: //模块目的、功能描述
* History: //修改记录
* <author> <time> <version> <desc>
* 修改人姓名 修改时间 版本号 描述
*/
package com.ihooyah.utils.safety;
/**
* 〈一句话功能简述〉<br>
* 〈功能详细描述〉
*
* @author hzy
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
public class SsoConstant {
/** cookie里session的id */
public static final String SESSION_NAME = "SESSCOOK";
public static final String SPLIT_SIGN = "-";
public static final String ENCODE = "UTF-8";
/** 当前登陆shop存储在request里的Attribute名字 */
public static final String CURRENT_LOGIN_SHOP = "CURRENT_LOGIN_SHOP";
/** 认证机制里存储cookie的域名 */
public static final String DOMAIN_NAME = "auth.domain";
}
package com.ihooyah.utils.security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.codec.binary.Base64;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: gedelong
* @Date: 2018/11/30 15:08
* 加密工具类
*/
public class AesEncryptUtils {
//可配置到Constant中,并读取配置文件注入,16位,自己定义
private static final String KEY = "xxxxxxxxxxxxxxxx";
//参数分别代表 算法名称/加密模式/数据填充方式
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
//
private static final String AES = "AES";
private static final String CHARSET = "UTF-8";
/**
* 加密
* @param content 加密的字符串
* @param encryptKey key值
* @return
* @throws Exception
*/
public static String encrypt(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance(AES);
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), AES));
byte[] b = cipher.doFinal(content.getBytes(CHARSET));
// 采用base64算法进行转码,避免出现中文乱码
return Base64.encodeBase64String(b);
}
/**
* 解密
* @param encryptStr 解密的字符串
* @param decryptKey 解密的key值
* @return
* @throws Exception
*/
public static String decrypt(String encryptStr, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance(AES);
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), AES));
// 采用base64算法进行转码,避免出现中文乱码
byte[] encryptBytes = Base64.decodeBase64(encryptStr);
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
public static String encrypt(String content) throws Exception {
return encrypt(content, KEY);
}
public static String decrypt(String encryptStr) throws Exception {
return decrypt(encryptStr, KEY);
}
public static void main(String[] args) throws Exception {
Map map=new HashMap<String,String>();
map.put("id","11");
String content = JSONObject.toJSONString(map);
System.out.println("加密前:" + content);
String encrypt = encrypt(content, KEY);
System.out.println("加密后:" + encrypt);
String decrypt = decrypt(encrypt, KEY);
System.out.println("解密后:" + decrypt);
}
}
package com.ihooyah.utils.security;
import org.apache.commons.io.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import org.thymeleaf.util.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
/**
* @Author: gedelong
* @Date: 2018/11/30 15:13
* 请求数据解密 可以除去判断注解 实行全部解密
*/
@Slf4j
@ControllerAdvice
public class DecodeRequestBodyAdvice implements RequestBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return body;
}
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
try {
boolean encode = false;
if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {
//获取注解配置的包含和去除字段
SecurityParameter serializedField = methodParameter.getMethodAnnotation(SecurityParameter.class);
//入参是否需要解密
encode = serializedField.inDecode();
}
if (encode) {
log.info("对方法method :【" + methodParameter.getMethod().getName() + "】进行解密");
return new MyHttpInputMessage(inputMessage);
}else{
return inputMessage;
}
} catch (Exception e) {
e.printStackTrace();
log.error("对方法method :【" + methodParameter.getMethod().getName() + "】进行解密出现异常:"+e.getMessage());
return inputMessage;
}
}
@Override
public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
return body;
}
class MyHttpInputMessage implements HttpInputMessage {
private HttpHeaders headers;
private InputStream body;
public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
this.headers = inputMessage.getHeaders();
String requestData = IOUtils.toString(inputMessage.getBody(), "UTF-8");
this.body = IOUtils.toInputStream(AesEncryptUtils.decrypt(requestData), "UTF-8");
}
@Override
public InputStream getBody() throws IOException {
return body;
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
}
}
package com.ihooyah.utils.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* @Author: gedelong
* @Date: 2018/11/30 15:20
* 返回数据加密 可以除去判断注解 实行全部加密
*/
@Slf4j
@ControllerAdvice
public class EncodeResponseBodyAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
boolean encode = false;
if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {
//获取注解配置的包含和去除字段
SecurityParameter serializedField = methodParameter.getMethodAnnotation(SecurityParameter.class);
//出参是否需要加密
encode = serializedField.outEncode();
}
if (encode) {
log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密");
ObjectMapper objectMapper = new ObjectMapper();
try {
String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
return AesEncryptUtils.encrypt(result);
} catch (Exception e) {
e.printStackTrace();
log.error("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常:"+e.getMessage());
}
}
return body;
}
}
package com.ihooyah.utils.security;
import org.springframework.web.bind.annotation.Mapping;
import java.lang.annotation.*;
/**
* @Author: gedelong
* @Date: 2018/11/30 15:12
* 实现注解自动 参数解密 返回数据加密,参数加密需添加@RequestBody使用
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Mapping
@Documented
public @interface SecurityParameter {
/**
* 入参是否解密,默认解密
*/
boolean inDecode() default true;
/**
* 出参是否加密,默认加密
*/
boolean outEncode() default true;
}
package com.ihooyah.utils.validation;
import com.ihooyah.rest.output.RespEnum;
import com.ihooyah.rest.output.RespInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: gedelong
* @Date: 2019/1/18 17:48
*/
public class ValidationUtils {
public static RespInfo paramCheck(BindingResult bindingResult){
List<String> errorInfos = new ArrayList<String>(bindingResult.getAllErrors().size());
for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorInfos.add(fieldError.getDefaultMessage());
}
return RespInfo.mobiError(RespEnum.ERROR, StringUtils.join(errorInfos.toArray(), ','));
}
}
package com.ihooyah;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase {
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest(String testName) {
super(testName);
}
/**
* @return the suite of tests being tested
*/
public static Test suite() {
return new TestSuite(AppTest.class);
}
/**
* Rigourous Test :-)
*/
public void testApp() {
assertTrue(true);
}
}
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>hotel-common-webconfig</artifactId>
<packaging>jar</packaging>
<version>1.0.0-RELEASE</version>
<name>${project.artifactId}</name>
<parent>
<groupId>com.ihooyah</groupId>
<artifactId>hotel-parent</artifactId>
<version>1.0.0-RELEASE</version>
<relativePath>../hotel-parent/pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>com.ihooyah</groupId>
<artifactId>hotel-common-utils</artifactId>
<version>1.0.0-RELEASE</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-metadata</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.ihooyah;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author 王尧 【wangyao@ihooyah.com】
* @description
* @create 2018-04-19 下午11:24
**/
@Component
public class Constant {
@Value("encrypt.mobi")
private String isEncryptMobi;
@Value("encrypt.web")
private String isEncryptWeb;
public String getIsEncryptMobi() {
return isEncryptMobi;
}
public void setIsEncryptMobi(String isEncryptMobi) {
this.isEncryptMobi = isEncryptMobi;
}
public String getIsEncryptWeb() {
return isEncryptWeb;
}
public void setIsEncryptWeb(String isEncryptWeb) {
this.isEncryptWeb = isEncryptWeb;
}
}
//package com.ihooyah.config;
//
//import org.springframework.beans.BeansException;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.ApplicationContextAware;
//import org.springframework.stereotype.Component;
//
///**
// * 获取applicationContext的工具类
// *
// * @author liujinliang
// * @date 2018-04-10
// */
//@Component
//public class ApplicationContextProvider implements ApplicationContextAware {
//
// private ApplicationContext applicationContext;
//
// @Override
// public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// this.applicationContext = applicationContext;
// }
//
// public <T> T getBean(Class<T> var1) throws BeansException {
// return applicationContext.getBean(var1);
// }
//}
package com.ihooyah.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ihooyah.config.support.FastJsonMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
import static com.alibaba.fastjson.serializer.SerializerFeature.*;
/**
* @Author: gedelong
* @Date: 2018/11/8 15:45
*/
public class DefaultMvcConfig implements WebMvcConfigurer {
/**
* 跨域支持
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600 * 24);
}
/**
* 配置消息转换器--这里我用的是alibaba 开源的 fastjson 可以使返回JSON解构美观清晰
*/
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
//1.需要定义一个convert转换消息的对象;
FastJsonMessageConverter fastJsonHttpMessageConverter = new FastJsonMessageConverter();
//2.添加fastJson的配置信息,比如:是否要格式化返回的json数据;
fastJsonHttpMessageConverter.setSerializerFeature(new SerializerFeature[]{
PrettyFormat,
WriteMapNullValue,
WriteNullStringAsEmpty,
WriteNullBooleanAsFalse,
WriteNullNumberAsZero,
QuoteFieldNames,
WriteDateUseDateFormat,
DisableCircularReferenceDetect
});
//3处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//4.在convert中添加配置信息.
fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
//5.将convert添加到converters当中.
return new HttpMessageConverters(fastJsonHttpMessageConverter);
}
/**
* 解决springboot 临时tem临时文件目录被删除问题 ->指定一个基础目录
*/
// @Bean
// MultipartConfigElement multipartConfigElement(){
// MultipartConfigFactory factory = new MultipartConfigFactory();
// factory.setLocation(propertiesUtils.getUploadPath());
// return factory.createMultipartConfig();
// }
// /**
// * 解除redis乱码问题
// * @param redisTemplate
// * @return
// */
// @Bean
// public RedisTemplate redisTemplate(RedisTemplate redisTemplate) {
// StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
// redisTemplate.setKeySerializer(stringRedisSerializer);
// redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);
// redisTemplate.setHashKeySerializer(stringRedisSerializer);
// redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);
// return redisTemplate;
// }
}
package com.ihooyah.config;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* 访问路径 http://localhost:8080/swagger-ui/
*
* @return
*/
@Configuration
@EnableOpenApi
public class SwaggerConfig {
@Bean
public Docket createRestApi(Environment environment) {
boolean enabled = environment.acceptsProfiles(Profiles.of("dev"));
return new Docket(DocumentationType.SWAGGER_2)
// 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息)
.apiInfo(apiInfo())
// 设置哪些接口暴露给Swagger展示
.select()
// 扫描所有有注解的api,用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
// 扫描指定包中的swagger注解
// .apis(RequestHandlerSelectors.basePackage("com.ihooyah.controller"))
// 扫描所有 .apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
/**
* 添加摘要信息
*/
private ApiInfo apiInfo() {
// 用ApiInfoBuilder进行定制
return new ApiInfoBuilder()
// 设置标题
.title("接口文档")
.build();
}
}
//package com.ihooyah.config.advice;
//
//import com.ihooyah.utils.response.Helper;
//import org.springframework.core.MethodParameter;
//import org.springframework.core.annotation.Order;
//import org.springframework.http.MediaType;
//import org.springframework.http.server.ServerHttpRequest;
//import org.springframework.http.server.ServerHttpResponse;
//import org.springframework.web.bind.annotation.ControllerAdvice;
//import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
//
//import java.lang.reflect.Field;
//import java.util.ArrayList;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
///**
// * Created by jeff on 15/10/23.
// */
//@Order(1)
//@ControllerAdvice
//public class MyResponseBodyAdvice implements ResponseBodyAdvice {
// //包含项
// private String[] includes = {};
// //排除项
// private String[] excludes = {};
// //是否加密
// private boolean encode = true;
//
// @Override
// public boolean supports(MethodParameter methodParameter, Class aClass) {
// //这里可以根据自己的需求
// return true;
// }
//
// @Override
// public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
// return o;
// }
//
// /**
// * 处理返回值是单个enity对象
// *
// * @param o
// * @return
// */
// private Object handleSingleObject(Object o) {
// Map<String, Object> map = new HashMap<String, Object>();
//
// Field[] fields = o.getClass().getDeclaredFields();
// for (Field field : fields) {
// //如果未配置表示全部的都返回
// if (includes.length == 0 && excludes.length == 0) {
// String newVal = getNewVal(o, field);
// map.put(field.getName(), newVal);
// } else if (includes.length > 0) {
// //有限考虑包含字段
// if (Helper.isStringInArray(field.getName(), includes)) {
// String newVal = getNewVal(o, field);
// map.put(field.getName(), newVal);
// }
// } else {
// //去除字段
// if (excludes.length > 0) {
// if (!Helper.isStringInArray(field.getName(), excludes)) {
// String newVal = getNewVal(o, field);
// map.put(field.getName(), newVal);
// }
// }
// }
//
// }
// return map;
// }
//
// /**
// * 处理返回值是列表
// *
// * @param list
// * @return
// */
// private List handleList(List list) {
// List retList = new ArrayList();
// for (Object o : list) {
// Map map = (Map) handleSingleObject(o);
// retList.add(map);
// }
// return retList;
// }
//
// /**
// * 获取加密后的新值
// *
// * @param o
// * @param field
// * @return
// */
// private String getNewVal(Object o, Field field) {
// String newVal = "";
// try {
// field.setAccessible(true);
// Object val = field.get(o);
//
// if (val != null) {
// if (encode) {
// newVal = Helper.encode(val.toString());
// } else {
// newVal = val.toString();
// }
// }
// } catch (IllegalAccessException e) {
// e.printStackTrace();
// }
//
// return newVal;
// }
//}
package com.ihooyah.config.exception;
import com.ihooyah.rest.output.RespEnum;
import com.ihooyah.rest.output.RespInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author liujinliang
* @date 2018-04-04
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public RespInfo exceptionHandler(Exception exception) {
log.error("服务器出现错误: ", exception);
if (exception instanceof java.lang.NullPointerException){
}
return RespInfo.out(RespEnum.ERROR, exception.getMessage());
}
}
package com.ihooyah.config.filter;
import javax.servlet.*;
import java.io.IOException;
/**
* @author 王尧 【wangyao@ihooyah.com】
* @description
* @create 2018-04-19 下午7:46
**/
public class DefaultFilter implements Filter {
@Override
public void destroy() {
System.out.println("基础过滤器消费");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("基础过滤器执行");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
System.out.println("基础过滤器初始化");
}
}
//package com.ihooyah.config.interceptor;
//
//import com.ihooyah.Constants;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.stereotype.Component;
//import org.springframework.web.servlet.HandlerInterceptor;
//import org.springframework.web.servlet.ModelAndView;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
///**
// * @author 王尧 【wangyao@ihooyah.com】
// * @description
// * @create 2018-04-23 下午4:01
// **/
//public class MobiParamsInterceptor implements HandlerInterceptor {
// private static final String ERROR_TAG = "error";
// private Logger logger = LoggerFactory.getLogger("MobiParamsInterceptor");
//
// @Override
// public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
// String appVersion = httpServletRequest.getParameter(Constants.APP_VERSION);
// String appVersionBuild = httpServletRequest.getParameter(Constants.APP_VERSION_BUILD);
// String appPlatform = httpServletRequest.getParameter(Constants.APP_PLATFORM);
// String appOs = httpServletRequest.getHeader(Constants.APP_OS);
// String appOsVersion = httpServletRequest.getHeader(Constants.APP_OS_VERSION);
// String appDeviceModel = httpServletRequest.getHeader(Constants.APP_DEVICE_MODEL);
// String jwptid = httpServletRequest.getHeader(Constants.JWPTID);
// //如果 true 正常执行 postHandle
// return false;
// }
//
// //请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
// @Override
// public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
// logger.info("postHandle被调用");
// }
//
// //在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行(主要是用于进行资源清理工作)
// @Override
// public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
// logger.info("afterCompletion被调用");
// }
//}
package com.ihooyah.config.support;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**
* @author 王尧 【wangyao@ihooyah.com】
* @description 自定义消息转换器,灵活这顶最终消息的输出格式
* @create 2018-04-19 下午9:41
**/
@Component
@Slf4j
public class FastJsonMessageConverter extends AbstractHttpMessageConverter<Object> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
// fastjson特性参数
private SerializerFeature[] serializerFeature;
public SerializerFeature[] getSerializerFeature() {
return serializerFeature;
}
public void setSerializerFeature(SerializerFeature[] serializerFeature) {
this.serializerFeature = serializerFeature;
}
public FastJsonMessageConverter() {
super(new MediaType("application", "json", DEFAULT_CHARSET));
}
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return true;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return true;
}
@Override
protected boolean supports(Class<?> clazz) {
throw new UnsupportedOperationException();
}
@Override
protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage)
throws IOException, HttpMessageNotReadableException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i;
while ((i = inputMessage.getBody().read()) != -1) {
baos.write(i);
}
System.out.println("fastJson接收:" + baos.toString());
return JSON.parseObject(baos.toString(), clazz);
}
@Override
protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
String jsonString = JSON.toJSONString(o, this.serializerFeature);
// try {
// jsonString = DES.encryptDES(jsonString);
// } catch (Exception e) {
// e.printStackTrace();
// }
//System.out.println("fastJson返回:"+jsonString);
OutputStream out = outputMessage.getBody();
out.write(jsonString.getBytes(DEFAULT_CHARSET));
out.flush();
}
}
package com.ihooyah.config.support;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* @Author: gedelong
* @Date: 2018/11/28 14:57
* 返回值输出代理类:这个类主要是为了吧Response里面的返回值获取到,
* 因为直接Response没有提供直接拿到返回值的方法。所以要通过代理来取得返回值
*/
public class ResponseWrapper extends HttpServletResponseWrapper {
private ByteArrayOutputStream buffer;
private ServletOutputStream out;
public ResponseWrapper(HttpServletResponse httpServletResponse) {
super(httpServletResponse);
buffer = new ByteArrayOutputStream();
out = new WrapperOutputStream(buffer);
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return out;
}
@Override
public void flushBuffer() throws IOException {
if (out != null) {
out.flush();
}
}
public byte[] getContent() throws IOException {
flushBuffer();
return buffer.toByteArray();
}
class WrapperOutputStream extends ServletOutputStream {
private ByteArrayOutputStream bos;
public WrapperOutputStream(ByteArrayOutputStream bos) {
this.bos = bos;
}
@Override
public void write(int b) throws IOException {
bos.write(b);
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setWriteListener(WriteListener arg0) {
}
}
}
package com.ihooyah.config.support;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
/**
* @author 王尧 【wangyao@ihooyah.com】
* @description
* @create 2018-04-20 上午10:35
**/
public class SpringUtil {
private static ApplicationContext applicationContext = null;
public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
/**
* 获取布尔值
*
* @return
* @author 王尧 【wangyao@ihooyah.com】
* @date 2018/4/20 上午10:37
**/
public static boolean getBooleanValue(String properties) {
String value = getApplicationContext().getEnvironment().getProperty(properties);
if (StringUtils.isEmpty(value)) {
return false;
}
boolean result = Boolean.valueOf(value);
return result;
}
/**
* 获取Int值
*
* @return
* @author 王尧 【wangyao@ihooyah.com】
* @date 2018/4/20 上午10:40
**/
public static int getIntegerValue(String properties) {
String value = getApplicationContext().getEnvironment().getProperty(properties);
if (StringUtils.isEmpty(value)) {
return -1;
}
int result = Integer.parseInt(value);
return result;
}
/**
* 获取Long值
*
* @return
* @author 王尧 【wangyao@ihooyah.com】
* @date 2018/4/20 上午10:40
**/
public static Long getLongValue(String properties) {
String value = getApplicationContext().getEnvironment().getProperty(properties);
if (StringUtils.isEmpty(value)) {
return -1L;
}
Long result = Long.parseLong(value);
return result;
}
/**
* 获取属性值
*
* @return
* @author 王尧 【wangyao@ihooyah.com】
* @date 2018/4/20 上午10:40
**/
public static String getValue(String properties) {
String value = getApplicationContext().getEnvironment().getProperty(properties);
return value;
}
}
package com.ihooyah.dao;
import java.util.List;
public interface BaseDao<T> {
/**
* 根据主键查询相应记录
*
* @param id 主键
* @return
*/
T selectByPrimaryKey(Object id);
/**
* 非空字段查询
*
* @param record 记录
* @return
*/
List<T> select(T record);
/**
* 插入记录
*
* @param record 记录
* @return
*/
int insert(T record);
/**
* 根据主键, 更新非空字段
*
* @param record 记录
* @return
*/
int updateByPrimaryKeySelective(T record);
/**
* 根据主键, 更新全字段
*
* @param record 记录
* @return
*/
int updateByPrimaryKey(T record);
/**
* 根据主键, 删除记录
*
* @param id 主键
* @return
*/
int deleteByPrimaryKey(Object id);
}
package com.ihooyah.exception;
/**
* @author 王尧 【wangyao@ihooyah.com】
* @description 业务异常
* @create 2018-04-18 下午5:04
**/
public class BizException extends Exception{
}
package com.ihooyah.exception;
public class NoneArgumentException extends Exception {
public static final String defaultMessage = "参数不能为空";
public NoneArgumentException() {
super(defaultMessage);
}
public NoneArgumentException(String message) {
super(message);
}
}
package com.ihooyah.service;
import java.util.List;
/**
* @author LiuJinLiang
* @description 描述
* @date 2018/5/8 19:24
*/
public interface BaseService<T> {
/**
* 根据主键查询相应记录
*
* @param id 主键
* @return
*/
T selectByPrimaryKey(Object id) throws Exception;
/**
* 非空字段查询
*
* @param record 记录
* @return
*/
List<T> select(T record) throws Exception;
/**
* 插入记录
*
* @param record 记录
* @return
*/
int insert(T record) throws Exception;
/**
* 根据主键, 更新非空字段
*
* @param record 记录
* @return
*/
int updateByPrimaryKeySelective(T record) throws Exception;
/**
* 根据主键, 更新全字段
*
* @param record 记录
* @return
*/
int updateByPrimaryKey(T record) throws Exception;
/**
* 根据主键, 删除记录
*
* @param id 主键
* @return
*/
int deleteByPrimaryKey(Object id) throws Exception;
}
\ No newline at end of file
package com.ihooyah.service.impl;
import com.ihooyah.dao.BaseDao;
import com.ihooyah.exception.NoneArgumentException;
import com.ihooyah.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import java.util.List;
@CacheConfig
public abstract class BaseServiceImpl<T> implements BaseService<T> {
@Autowired
private BaseDao<T> baseDao;
@Override
public int deleteByPrimaryKey(Object id) throws Exception {
if (id == null) {
throw new NoneArgumentException();
}
return baseDao.deleteByPrimaryKey(id);
}
@Override
public int insert(T record) throws Exception {
if (record == null) {
throw new NoneArgumentException();
}
return baseDao.insert(record);
}
@Override
public T selectByPrimaryKey(Object id) throws Exception {
if (id == null) {
throw new NoneArgumentException();
}
return baseDao.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(T record) throws Exception {
if (record == null) {
throw new NoneArgumentException();
}
return baseDao.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(T record) throws Exception {
if (record == null) {
throw new NoneArgumentException();
}
return baseDao.updateByPrimaryKey(record);
}
@Override
public List<T> select(T record) throws Exception {
if (record == null) {
throw new NoneArgumentException();
}
return baseDao.select(record);
}
}
package com.ihooyah.utils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author ***
* @version V1.0
* @Description
* @Package com.ihooyah.utils
* @date 2022-12-09 18:14
*/
@Data
@Component
@ConfigurationProperties(prefix = "login.url")
public class SignLoginDataUrl {
@ApiModelProperty("获取token")
private String token;
}
package com.ihooyah.utils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author ***
* @version V1.0
* @Description
* @Package com.ihooyah.utils
* @date 2022-11-16 17:25
*/
@Data
@Component
@ConfigurationProperties(prefix = "third.url")
public class ThirdDataUrl {
@ApiModelProperty("获取token")
private String token;
@ApiModelProperty("获取一件事编码")
private String oneThingGuid;
}
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