Commit b81c7945 authored by 曹志's avatar 曹志

公共模块

parent 7f26fb9f
......@@ -6,6 +6,7 @@
<modules>
<module>spacetech-common-util</module>
<module>spacetech-service-interface</module>
<module>spacetech-service-growth</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
......@@ -45,5 +46,32 @@
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>nexus</id>
<name>Team Nexus Repository</name>
<!-- <url>http://weixt.spacetech.com.cn:8081/nexus/content/groups/public</url> -->
<url>http://weixt.spacetech.com.cn:9091/nexus/content/groups/public</url>
</repository>
<repository>
<id>snapshot</id>
<name>公司内部开发用的jar lib</name>
<url>http://weixt.spacetech.com.cn:9091/nexus/content/repositories/snapshots</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>releases1</id>
<name>Team Nexus Repository</name>
<url>http://weixt.spacetech.com.cn:9091/nexus/content/groups/releases/</url>
</repository>
<snapshotRepository>
<id>snapshots</id>
<name>Nexus Snapshot Repository</name>
<url>http://weixt.spacetech.com.cn:9091/nexus/content/repositories/snapshots/</url>
</snapshotRepository>
</distributionManagement>
</project>
......@@ -31,5 +31,155 @@
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--阿里云OSS存储-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.0.6</version>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- 生成二维码 -->
<dependency>
<groupId>com.google</groupId>
<artifactId>zxing-core</artifactId>
<version>1.0.0</version>
</dependency>
<!--JDOM 解析XML依赖包-->
<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>2.0.2</version>
</dependency>
<!--百度AI开放平台-->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.12.0</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--POI 处理Excel文档-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
<scope>compile</scope>
</dependency>
<!--百度云SDK开发包-->
<dependency>
<groupId>com.baidubce</groupId>
<artifactId>bce-java-sdk</artifactId>
<version>0.10.78</version>
</dependency>
<!--异步HTTP客户端开发包-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0.2</version>
</dependency>
<!--SpringData JPA-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--日期时间处理库-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.9.4</version>
</dependency>
<!--图片压缩工具-->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<!--java操作Excel表格工具包-->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<!--汉语拼音工具库-->
<dependency>
<groupId>net.sourceforge.pinyin4j</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.0</version>
</dependency>
<!-- MEMCACHED CLIENT -->
<dependency>
<groupId>com.googlecode.xmemcached</groupId>
<artifactId>xmemcached</artifactId>
<version>2.0.0</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
<!--Memcache 客户端-->
<dependency>
<groupId>net.spy</groupId>
<artifactId>spymemcached</artifactId>
<version>2.11.2</version>
</dependency>
<!--Servlet API-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!--zookeeper 客户端工具包-->
<dependency>
<groupId>com.github.sgroschupf</groupId>
<artifactId>zkclient</artifactId>
<version>0.1</version>
</dependency>
<!--自定义工具包[fastjson,StringUtils]-->
<dependency>
<groupId>ground</groupId>
<artifactId>sdk_release_gs1</artifactId>
<version>1.51.61</version>
</dependency>
<!-- nacos-client -->
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
</dependency>
</dependencies>
</project>
\ No newline at end of file
package com.spacetech.common.entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
* 统一定义id的entity基类.
*
* 基类统一定义id的属性名称、数据类型、列名映射及生成策略.
* Oracle需要每个Entity独立定义id的SEQUCENCE时,不继承于本类而改为实现一个Idable的接口。
*
* @author calvin
*/
// JPA 基类的标识
@MappedSuperclass
public abstract class IdEntity {
protected String id;
@Id
@Column(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
package com.spacetech.common.entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
/**
* 统一定义id的entity基类.
*
* 基类统一定义id的属性名称、数据类型、列名映射及生成策略.
* Oracle需要每个Entity独立定义id的SEQUCENCE时,不继承于本类而改为实现一个Idable的接口。
*
* @author calvin
*/
// JPA 基类的标识
@MappedSuperclass
public abstract class IdLongEntity{
protected Long id;
@Id
@Column(name = "id")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
package com.spacetech.common.exception;
public class ApiException extends RuntimeException {
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public Throwable getErrorCause() {
return errorCause;
}
public void setErrorCause(Throwable errorCause) {
this.errorCause = errorCause;
}
private static final long serialVersionUID = -9171287832448832971L;
protected String errorMsg; // 错误信息(For debug)
protected Throwable errorCause = null; // 错误发生原因(原始Exception)
public ApiException(Throwable e, String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
this.errorCause = e;
}
public ApiException(String errorMsg) {
super(errorMsg);
this.errorMsg = errorMsg;
}
}
package com.spacetech.common.exception;
/**
* 异常处理基类
*
* @author wm
*
*/
public class BaseException extends RuntimeException {
private static final long serialVersionUID = -5154615570448990996L;
protected String errorCode; // 错误代码(属性表文件中定义其message)
protected String errorMsg; // 错误信息(For debug)
protected Object[] parameters; // 参数列表(错误代码对应的message需要的参数列表)
protected Throwable errorCause; // 错误发生原因(原始Exception)
protected String errorDetail; // 错误详细信息
/**
* Constructor
*
* @param errorMsg
* @param errorCode
* @param parameters
* @param e
*/
public BaseException(String errorMsg, String errorDetail, String errorCode,
Object[] parameters) {
super(errorMsg);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
this.errorDetail = errorDetail;
this.parameters = parameters;
}
/**
* Constructor
*
* @param errorMsg
* @param errorCode
* @param parameters
* @param e
*/
public BaseException(String errorMsg, String errorDetail, String errorCode,
Object[] parameters, Throwable e) {
super(errorMsg, e);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
this.errorDetail = errorDetail;
this.errorCause = e;
this.parameters = parameters;
}
public Throwable getErrorCause() {
return errorCause;
}
public void setErrorCause(Throwable errorCause) {
this.errorCause = errorCause;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public Object[] getParameters() {
return parameters;
}
public void setParameters(String[] parameters) {
this.parameters = parameters;
}
public String getErrorDetail() {
return errorDetail;
}
public void setErrorDetail(String errorDetail) {
this.errorDetail = errorDetail;
}
}
package com.spacetech.common.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 业务处理异常类
*
* @author wm
*
*/
public class BusinessException extends BaseException {
private static final long serialVersionUID = 1L;
private static Logger logger = LoggerFactory
.getLogger(BusinessException.class);
/**
* Constructor
*
* @param errorCode
*/
public BusinessException(String errorMsg) {
super(errorMsg, null, null, null);
}
/**
* Constructor
*
* @param errorCode
* @param parameters
*/
public BusinessException(String errorCode, Object[] parameters) {
super(null, null, errorCode, parameters);
}
/**
* Constructor
*
* @param errorCode
* @param e
*/
public BusinessException(String errorMsg, Throwable e) {
super(errorMsg, null, null, null, e);
}
/**
* Constructor
*
* @param errorCode
* @param parameters
* @param e
*/
public BusinessException(String errorCode, Object[] parameters, Throwable e) {
super(null, null, errorCode, parameters, e);
}
/**
* Constructor
*
* @param errorMsg
* @param errorCode
*/
public BusinessException(String errorMsg, String errorCode) {
super(errorMsg, null, errorCode, null);
}
/**
* Constructor
*
* @param errorMsg
* @param errorCode
* @param parameters
*/
public BusinessException(String errorMsg, String errorCode,
Object[] parameters) {
super(errorMsg, null, errorCode, parameters);
}
/**
* Constructor
*
* @param errorMsg
* @param errorCode
* @param parameters
* @param e
*/
public BusinessException(String errorMsg, String errorCode,
Object[] parameters, Throwable e) {
super(errorMsg, null, errorCode, parameters, e);
}
/**
* Constructor
*
* @param errorMsg
* @param errorDetail
* @param errorCode
*/
public BusinessException(String errorMsg, String errorDetail,
String errorCode) {
super(errorMsg, errorDetail, errorCode, null);
}
/**
* Constructor
*
* @param errorMsg
* @param errorDetail
* @param errorCode
* @param e
*/
public BusinessException(String errorMsg, String errorDetail,
String errorCode, Throwable e) {
super(errorMsg, errorDetail, errorCode, null, e);
}
/**
* Constructor
*
* @param errorMsg
* @param errorDetail
* @param errorCode
* @param parameters
*/
public BusinessException(String errorMsg, String errorDetail,
String errorCode, Object[] parameters) {
super(errorMsg, errorDetail, errorCode, parameters, null);
}
/**
* Constructor
*
* @param errorMsg
* @param errorDetail
* @param errorCode
* @param parameters
* @param e
*/
public BusinessException(String errorMsg, String errorDetail,
String errorCode, Object[] parameters, Throwable e) {
super(errorMsg, errorDetail, errorCode, parameters, e);
}
}
package com.spacetech.common.exception;
import java.io.Serializable;
public class ExcelDataCheckException extends RuntimeException implements
Serializable {
private static final long serialVersionUID = 1L;
public ExcelDataCheckException(String errorMsg) {
super(errorMsg);
}
}
package com.spacetech.common.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.spacetech.common.utils.StringUtil;
public class ExceptionUtil {
private static Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);
public boolean extractApiException(java.lang.reflect.InvocationTargetException e) {
String className = e.getTargetException().getClass().getName();
// if(){
//
// }
return false;
}
public static String transformDbException(String msg) {
if (StringUtil.isNullOrEmpty(msg)) {
return "";
}
if (msg.indexOf("exception.SQL") > -1 || msg.indexOf("JDBCException") > -1
|| msg.indexOf("NonUniqueResultException") > -1 || msg.indexOf("QueryException") > -1
|| msg.indexOf("org.hibernate") > -1 || msg.indexOf("InvocationTargetException") > -1) {
return "系统发生错误,请联系管理员稍后重试!";
}
if (msg.indexOf("Forbid consumer") > -1 || msg.indexOf("No provider available") > -1) {
return "平台访问量过大,请稍后重试";
}
return msg;
}
}
package com.spacetech.common.exception;
public class FilePutErrorException extends BusinessException {
public FilePutErrorException(String errorCode) {
super(errorCode);
// TODO Auto-generated constructor stub
}
/**
*
*/
private static final long serialVersionUID = 112311234123423452L;
}
package com.spacetech.common.logger;
import org.apache.log4j.MDC;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.spacetech.common.utils.StringUtil;
public class LoggerUtil {
private static Logger logger = LoggerFactory.getLogger(LoggerUtil.class);
public static String setMdcRequestId(String requestId) {
if (StringUtil.isNullOrEmpty(requestId)) {
requestId = StringUtil.getIdGenerator();
}
MDC.put("requestId", requestId);
return requestId;
}
}
package com.spacetech.common.utils;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.spacetech.common.ConstantVar;
import com.spacetech.common.utils.wechat.AesException;
import com.spacetech.common.utils.wechat.WXBizMsgCrypt;
import com.spacetech.common.utils.wechat.XmlIterator;
import sun.misc.BASE64Encoder;
public class AESUtil {
public static final String AES_KEY = "J90a*&j_~!ks^T4j";
private static final String AES = "AES";
private static Logger logger = LoggerFactory.getLogger(AESUtil.class);
public static String AES_KEY_DATA_SAFE = "J90a*&j_~!ks^T4j";
/**
* 加密
*
* @param encryptStr
* @return
*/
private static byte[] encrypt(byte[] src, String key) throws Exception {
Cipher cipher = Cipher.getInstance(AES);
SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);
cipher.init(Cipher.ENCRYPT_MODE, securekey);// 设置密钥和加密形式
return cipher.doFinal(src);
}
/**
* 解密
*
* @param decryptStr
* @return
* @throws Exception
*/
private static byte[] decrypt(byte[] src, String key) throws Exception {
Cipher cipher = Cipher.getInstance(AES);
SecretKeySpec securekey = new SecretKeySpec(key.getBytes(), AES);// 设置加密Key
cipher.init(Cipher.DECRYPT_MODE, securekey);// 设置密钥和解密形式
return cipher.doFinal(src);
}
/**
* 二行制转十六进制字符串
*
* @param b
* @return
*/
private static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
public static byte[] hex2byte(byte[] b) {
if ((b.length % 2) != 0)
throw new IllegalArgumentException("长度不是偶数");
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += 2) {
String item = new String(b, n, 2);
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
/**
* 系统重要业务数据解密.
*
* @param data
* @return
*/
public final static String decryptForDataSafe(String data, String key) {
return decrypt(data, key);
}
/**
* 系统重要业务数据解密,有长度限制.
*
* @param data
* @return
*/
public final static String decryptLimitForDataSafe(String data, int datalength) {
return decryptLimit(data, AES_KEY_DATA_SAFE, datalength);
}
/**
* 系统重要业务数据加密.
*
* @return
* @throws Exception
*/
public final static String encryptForDataSafe(String data, String key) {
return encrypt(data, key);
}
/**
* 系统重要业务数据加密,限制长度.
*
* @return
* @throws Exception
*/
public final static String encryptLimitForDataSafe(String data, int datalength) {
return encryptLimit(data, AES_KEY_DATA_SAFE, datalength);
}
/**
* 解密
*
* @param data
* @return
* @throws Exception
*/
public final static String decrypt(String data, String key) {
if (StringUtil.isNullOrEmpty(data) || data.length() < 16) {
return data;
}
try {
return new String(decrypt(hex2byte(data.getBytes()), key));
} catch (Exception e) {
logger.warn("数据解密失败:data=" + data + " key=" + key + " 错误原因:" + e.getMessage());
return data;
}
}
public final static String decryptLimit(String data, String key, int datalength) {
try {
if (StringUtil.isNotEmpty(data) && data.length() > datalength) {
return new String(decrypt(hex2byte(data.getBytes()), key));
} else {
return data;
}
} catch (Exception e) {
logger.warn(
"数据解密失败:data=" + data + " key=" + key + " datalength=" + datalength + " 错误原因:" + e.getMessage());
return data;
}
}
/**
* 加密
*
* @param data
* @return
* @throws Exception
*/
public final static String encrypt(String data, String key) {
if (StringUtil.isNullOrEmpty(data)) {
return "";
}
try {
return byte2hex(encrypt(data.getBytes(), key));
} catch (Exception e) {
logger.warn("数据加密失败:data=" + data + " key=" + key + " 错误原因:" + e.getMessage());
return data;
}
}
public final static String encryptLimit(String data, String key, int datalength) {
try {
if (StringUtil.isNotEmpty(data) && data.length() < datalength) {
return byte2hex(encrypt(data.getBytes(), key));
} else {
return data;
}
} catch (Exception e) {
logger.warn(
"数据加密失败:data=" + data + " key=" + key + " datalength=" + datalength + " 错误原因:" + e.getMessage());
return data;
}
}
public final static String encryptWechat(String data, String encodingAesKey, String appId) throws AesException {
SimpleDateFormat sdfDateFormat = new SimpleDateFormat("yymmddhhmm");
String timestamp = sdfDateFormat.format(new Date());
WXBizMsgCrypt pc = new WXBizMsgCrypt(ConstantVar.TOKEN, encodingAesKey, appId);
String result = pc.encryptMsg(data, timestamp, ConstantVar.AES_KEY);
// System.out.println("encryptWechat result="+result);
return result;
}
public final static String decryptWechat(String data, String encodingAesKey, String appId, String msg_signature,
String timestamp, String nonce, String key) throws AesException {
Map<String, String> map = XmlIterator.interatorXML(data);
WXBizMsgCrypt pc = new WXBizMsgCrypt(ConstantVar.TOKEN, encodingAesKey, appId);
String encrypt = map.get("Encrypt");
String toUser = map.get(key);
String format = "<xml><" + key + "><![CDATA[%1$s]]></" + key + "><Encrypt><![CDATA[%2$s]]></Encrypt></xml>";
String fromXML = String.format(format, toUser, encrypt);
//
// 公众平台发送消息给第三方,第三方处理
//
// 第三方收到公众号平台发送的消息
String result = pc.decryptMsg(msg_signature, timestamp, nonce, fromXML);
return result;
}
public static void main(String[] paramArrayOfString) throws Exception {
String a = AESUtil.encryptForDataSafe("3fb6c04eaa3c761e9611a50975228021", "");
System.out.println(a);
String data = "W1koX4Bd6C4/m9QAJ8qyNBBlbIN5Sc611yostscnDRXePWXIbKuxOA74KijquKmK3z3VVM98LHjzVeSA6JyL2YJDNLYigzdKqAWDco2fNeXUZ4X0bohV8lf0gWQtN60xaUrkCyfIBFA8QoC9cw6fK4jEqutYaSZdQMIG7lsbwyAWn3nWZQHg0J8CLk6ILvb3ffRUZO1rfiVwjl9rpU8PVQB90YLBrL6sC4INxNAgRMh7CoCU2NGrdXQCxwe3TefSPxWtX6GmToZw61xhZFhwp2YiKBpXZkLVN/ChpA7H4nGXvj8OG3XRC7FRJjRsP6J9PBQNob7kuISl9f4lOeqRhZVkaGFaI55Pv8TFvqCRexKT1VDfU06cN0wMVBOUrgzOVccP5lBglcC4OZGGkMbJRKznlPIlUbpYrebgLiyi3ag=";
String encodingAesKey = "7vpPNkH02ojRulepw0yyQ2O5TvqwpL2cRXFsSO9Vf14";
String appId = "wxc0b82c673bfaadf9";
String msg_signature = "854703afddd36ea0c0542f3a50af8dd1c3467d59";
String timestamp = "1472181934";
String nonce = "2029305636";
String key = "ToUserName";
decryptWechat(data, encodingAesKey, appId, msg_signature, timestamp, nonce, key);
}
/**
* 系统重要业务数据解密.
*
* @param data
* @return
*/
public final static String decryptForDataSafe(String data) {
return decrypt(data, AES_KEY_DATA_SAFE);
}
/**
* 系统普通数据加密
*
* @param data
* @return
*/
public final static String encrypt(String data) {
return encrypt(data, AES_KEY);
}
/**
* 系统普通数据解密
*
* @param data
* @return
*/
public final static String decrypt(String data) {
return decrypt(data, AES_KEY);
}
/**
* 加密
*
* @param content
* @param encodeRules
* @return
*/
public static String AESEncrypt(String content, String encodeRules) {
try {
// 1.构造密钥生成器,指定为AES算法,不区分大小写
KeyGenerator keygen = KeyGenerator.getInstance(AES);
// 2.根据ecnodeRules规则初始化密钥生成器
// 生成一个128位的随机源,根据传入的字节数组
keygen.init(128, new SecureRandom(encodeRules.getBytes()));
// 3.产生原始对称密钥
SecretKey original_key = keygen.generateKey();
// 4.获得原始对称密钥的字节数组
byte[] raw = original_key.getEncoded();
// 5.根据字节数组生成AES密钥
SecretKey key = new SecretKeySpec(raw, AES);
// 6.根据指定算法AES自成密码器
Cipher cipher = Cipher.getInstance(AES);
// 7.初始化密码器,第一个参数为加密(Encrypt_mode)或者解密解密(Decrypt_mode)操作,第二个参数为使用的KEY
cipher.init(Cipher.ENCRYPT_MODE, key);
// 8.获取加密内容的字节数组(这里要设置为utf-8)不然内容中如果有中文和英文混合中文就会解密为乱码
byte[] byte_encode = content.getBytes("utf-8");
// 9.根据密码器的初始化方式--加密:将数据加密
byte[] byte_AES = cipher.doFinal(byte_encode);
// 10.将加密后的数据转换为字符串
String AES_encode = new String(new BASE64Encoder().encode(byte_AES));
// 11.将字符串返回
return AES_encode;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
package com.spacetech.common.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.spacetech.common.exception.ApiException;
import com.spacetech.common.exception.ExceptionUtil;
public class ApiUtil {
private static Logger logger = LoggerFactory.getLogger(ApiUtil.class);
public final static String SUCCESS = "200";
public final static String ERROR_INTERNAL_SERVER = "500";
public final static String ERROR_INTERNAL_SERVER_300 = "300";
public final static String ERROR_CLASS_NOTEXISTS = "001_001";
public final static String ERROR_METHOD_NOTEXISTS = "001_002";
public final static String MOCK_SERVER_URL = "http://localhost:8080/integtest/mockcall";
public static String formatJsonResult(String api, Object obj, String returnCode, String returnMsg, String version) {
JSONObject result = new JSONObject();
result.put("api", api);
result.put("data", obj);
result.put("v", version);
try {
result.put("ret", formatReturnMsg(returnCode, returnMsg));
return JSON.toJSONString(result, SerializerFeature.WriteMapNullValue,
SerializerFeature.DisableCircularReferenceDetect).replace(" ", " ");
} catch (Exception e) {
// TODO: handle exception
result = new JSONObject();
result.put("api", api);
result.put("v", version);
result.put("ret", formatReturnMsg(returnCode, "系统数据转换发生异常,请联系管理员"));
return JSON.toJSONString(result, SerializerFeature.WriteMapNullValue,
SerializerFeature.DisableCircularReferenceDetect).replace(" ", " ");
}
}
public static void verifyResponse(JSONObject resultJson) {
JSONObject ret = resultJson.getJSONObject("ret");
String code = ret.getString("code");
if (ERROR_INTERNAL_SERVER.equals(code)||ERROR_INTERNAL_SERVER_300.equals(code)) {
String msg = ret.getString("msg");
logger.error("systemerror msg" + JSONObject.toJSONString(resultJson));
throw new ApiException(ExceptionUtil.transformDbException(msg));
}
}
public static JSONObject formatReturnMsg(String code, String msg) {
JSONObject result = new JSONObject();
result.put("code", code);
if (ApiUtil.ERROR_INTERNAL_SERVER.equals(code)) {
msg = ExceptionUtil.transformDbException(msg);
}
result.put("msg", msg);
return result;
}
public static boolean isMockCall(JSONObject params) {
if (params == null) {
return false;
}
if (params.containsKey("mockcall")) {
return params.getBoolean("mockcall");
} else {
return false;
}
}
public static Class[] getJsonArgClass() throws ClassNotFoundException {
Class jsonClass = Class.forName("com.alibaba.fastjson.JSONObject");
Class[] argsClass = new Class[1];
argsClass[0] = jsonClass;
return argsClass;
}
}
package com.spacetech.common.utils;
import java.io.*;
public class Base64Decoder extends FilterInputStream {
private static final char[] chars = {
'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', '+', '/'
};
// A mapping between char values and six-bit integers
private static final int[] ints = new int[128];
static {
for (int i = 0; i < 64; i++) {
ints[chars[i]] = i;
}
}
private int charCount;
private int carryOver;
/***
* Constructs a new Base64 decoder that reads input from the given
* InputStream.
*
* @param in the input stream
*/
public Base64Decoder(InputStream in) {
super(in);
}
/***
* Returns the next decoded character from the stream, or -1 if
* end of stream was reached.
*
* @return the decoded character, or -1 if the end of the
* input stream is reached
* @exception IOException if an I/O error occurs
*/
public int read() throws IOException {
// Read the next non-whitespace character
int x;
do {
x = in.read();
if (x == -1) {
return -1;
}
} while (Character.isWhitespace((char)x));
charCount++;
// The '=' sign is just padding
if (x == '=') {
return -1; // effective end of stream
}
// Convert from raw form to 6-bit form
x = ints[x];
// Calculate which character we're decoding now
int mode = (charCount - 1) % 4;
// First char save all six bits, go for another
if (mode == 0) {
carryOver = x & 63;
return read();
}
// Second char use previous six bits and first two new bits,
// save last four bits
else if (mode == 1) {
int decoded = ((carryOver << 2) + (x >> 4)) & 255;
carryOver = x & 15;
return decoded;
}
// Third char use previous four bits and first four new bits,
// save last two bits
else if (mode == 2) {
int decoded = ((carryOver << 4) + (x >> 2)) & 255;
carryOver = x & 3;
return decoded;
}
// Fourth char use previous two bits and all six new bits
else if (mode == 3) {
int decoded = ((carryOver << 6) + x) & 255;
return decoded;
}
return -1; // can't actually reach this line
}
/***
* Reads decoded data into an array of bytes and returns the actual
* number of bytes read, or -1 if end of stream was reached.
*
* @param buf the buffer into which the data is read
* @param off the start offset of the data
* @param len the maximum number of bytes to read
* @return the actual number of bytes read, or -1 if the end of the
* input stream is reached
* @exception IOException if an I/O error occurs
*/
public int read(byte[] buf, int off, int len) throws IOException {
if (buf.length < (len + off - 1)) {
throw new IOException("The input buffer is too small: " + len +
" bytes requested starting at offset " + off + " while the buffer " +
" is only " + buf.length + " bytes long.");
}
// This could of course be optimized
int i;
for (i = 0; i < len; i++) {
int x = read();
if (x == -1 && i == 0) { // an immediate -1 returns -1
return -1;
}
else if (x == -1) { // a later -1 returns the chars read so far
break;
}
buf[off + i] = (byte) x;
}
return i;
}
/***
* Returns the decoded form of the given encoded string, as a String.
* Note that not all binary data can be represented as a String, so this
* method should only be used for encoded String data. Use decodeToBytes()
* otherwise.
*
* @param encoded the string to decode
* @return the decoded form of the encoded string
*/
public static String decode(String encoded) {
return new String(decodeToBytes(encoded));
}
/***
* Returns the decoded form of the given encoded string, as bytes.
*
* @param encoded the string to decode
* @return the decoded form of the encoded string
*/
public static byte[] decodeToBytes(String encoded) {
byte[] bytes = null;
try {
bytes = encoded.getBytes("UTF-8");
}
catch (UnsupportedEncodingException ignored) { }
Base64Decoder in = new Base64Decoder(
new ByteArrayInputStream(bytes));
ByteArrayOutputStream out =
new ByteArrayOutputStream((int) (bytes.length * 0.67));
try {
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = in.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
out.close();
return out.toByteArray();
}
catch (IOException ignored) { return null; }
}
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java Base64Decoder fileToDecode");
return;
}
Base64Decoder decoder = null;
try {
decoder = new Base64Decoder(
new BufferedInputStream(
new FileInputStream(args[0])));
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = decoder.read(buf)) != -1) {
System.out.write(buf, 0, bytesRead);
}
}
finally {
if (decoder != null) decoder.close();
}
}
}
package com.spacetech.common.utils;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class CDATAdapter extends XmlAdapter<String, String> {
@Override
public String unmarshal(String v) throws Exception {
return v;
}
@Override
public String marshal(String v) throws Exception {
return "<![CDATA[" + v + "]]>";
}
}
package com.spacetech.common.utils;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import com.spacetech.common.exception.ApiException;
public class CalcUtil {
private static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
private static final String CONDITION_UNION_TYPE_AND = "&&";
private static final String CONDITION_UNION_TYPE_OR = "||";
/**
* 判断条件是否满足
*
* @return
*/
public static boolean judgeAtomCondition(String atomCondition) {
// 肯定是数字型
if (atomCondition.indexOf(">=") > -1) {
String[] values = atomCondition.split(">=");
return judgeResult(values, ">=");
} else if (atomCondition.indexOf("<=") > -1) {
String[] values = atomCondition.split("<=");
return judgeResult(values, "<=");
} else if (atomCondition.indexOf(">") > -1) {
String[] values = atomCondition.split(">");
return judgeResult(values, ">");
} else if (atomCondition.indexOf("<") > -1) {
String[] values = atomCondition.split("<");
return judgeResult(values, "<");
} else if (atomCondition.indexOf("!=null") > -1) {
String[] values = atomCondition.split("!=");
// 不为空只有表单条件时候才有,如果表单数据为空,那么表达式不会被替换
if (values[0].equals("null") || values[0].indexOf("form#") > -1 || atomCondition.startsWith("!=")) {
return false;
}
return true;
} else if (atomCondition.indexOf("==") > -1) {
String[] values = atomCondition.split("==");
double value0 = jse(values[0]);
double value1 = jse(values[1]);
// ??? 除了 中文的 0=0无法比较,其他条件应该都可以比较
if (value0 > 0 && value0 == value1) {
return true;
} else {
return values[0].equals(values[1].trim());
}
} else if (atomCondition.indexOf("!=") > -1) {
String[] values = atomCondition.split("!=");
double value0 = jse(values[0]);
double value1 = jse(values[1]);
// ??? 除了 中文的 0=0无法比较,其他条件应该都可以比较
if (value0 > 0 && value0 == value1) {
return false;
} else {
return !values[0].equals(values[1].trim());
}
} else {
throw new RuntimeException("不正确的条件表达式" + atomCondition);
}
}
private static Double jse(String express) {
if (express != null && (express.indexOf("-") > 0 || express.indexOf("+") > 0 || express.indexOf("*") > 0
|| express.indexOf("/") > 0)) {
return eval(express);
} else {
return StringUtil.getDoubleOfObj(express);
}
}
private static boolean judgeResult(String[] values, String operator) {
for (Integer i = 1; i < values.length; i++) {
boolean result = false;
switch (operator) {
case "<=":
result = jse(values[i - 1]) <= jse(values[i]);
break;
case ">=":
result = jse(values[i - 1]) >= jse(values[i]);
break;
case ">":
result = jse(values[i - 1]) > jse(values[i]);
break;
case "<":
result = jse(values[i - 1]) < jse(values[i]);
break;
default:
result = false;
break;
}
if (!result) {
return false;
}
}
return true;
}
public static Double eval(String express) {
try {
return StringUtil.getDoubleOfObj(jse.eval(express));
} catch (ScriptException e) {
return 0d;
}
}
/**
* 表达式expression校验:checkNum<2;2<=checkNum<5;5<=checkNum
*
* @param checkNum
* @param expression
* @return
*/
public static Boolean checkExpression(Float checkNum, String expression) {
try {
if (expression.indexOf("<=") == -1) {
if (checkNum < StringUtil.getNullFloat(expression.split("<=")[2])) {
return true;
}
} else if (expression.split("<").length > 2) {
float min = StringUtil.getNullFloat(expression.split("<=")[0]);
float max = StringUtil.getNullFloat(expression.split("<")[2]);
if (min <= checkNum && checkNum < max) {
return true;
}
} else {
if (StringUtil.getNullFloat(expression.split("<=")[0]) <= checkNum) {
return true;
}
}
} catch (Exception e) {
throw new ApiException("表达式配置不正确");
}
return false;
}
/**
* B,KB,MB,GB 单位换算
*
*/
public static String fileSizeConver(long fileS) {
DecimalFormat df = new DecimalFormat("#.00");
String fileSizeString = "";
String wrongSize = "0B";
if (fileS == 0) {
return wrongSize;
}
if (fileS < 1024) {
fileSizeString = df.format((double) fileS) + "B";
} else if (fileS < 1048576) {
fileSizeString = df.format((double) fileS / 1024) + "KB";
} else if (fileS < 1073741824) {
fileSizeString = df.format((double) fileS / 1048576) + "MB";
} else if (fileS < 1099511627776L) {
fileSizeString = df.format((double) fileS / 1073741824) + "GB";
} else {
fileSizeString = df.format((double) fileS / 1099511627776L) + "TB";
}
return fileSizeString;
}
public static boolean isMatchRule(String expression) {
boolean result = false;
if (StringUtil.isNullOrEmpty(expression)) {
return result;
}
String unionType = CONDITION_UNION_TYPE_AND;
String splitValue = "";
if (expression.indexOf(CONDITION_UNION_TYPE_OR) > -1) {
unionType = CONDITION_UNION_TYPE_OR;
splitValue = "\\|\\|";
} else {
unionType = CONDITION_UNION_TYPE_AND;
splitValue = CONDITION_UNION_TYPE_AND;
}
expression = expression.replaceAll(" ", "");
String[] conditions = expression.split(splitValue);
for (String condition : conditions) {
// String replacedCondition = replaceFormExpressionWithValue(condition,
// dataList);
boolean conditionMeeted = judgeAtomCondition(condition);
if (unionType.equals(CONDITION_UNION_TYPE_AND)) {
if (!conditionMeeted) {
result = false;
break;
} else {
result = true;
}
}
if (unionType.equals(CONDITION_UNION_TYPE_OR) && conditionMeeted) {
result = true;
break;
}
}
return result;
}
/**
* 获取列表的中位数;
*
* @param numList
* @return
*/
public static Float getMedianNum(List<Float> numList){
if(numList.isEmpty()){
return 0.0f;
}
Collections.sort(numList);
int size = numList.size();
if (size % 2 == 1) { // size为奇数个
return numList.get((size - 1) / 2);
} else { //size 为偶数个
return (numList.get((size / 2 - 1)) + numList.get(size / 2)) / 2;
}
}
}
package com.spacetech.common.utils;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import com.spacetech.common.utils.FileUtil;
/**
* @author lc Date: 13-06-04
*/
public class ConfigUtil {
private static Properties props;
public static void loadProperties(String properties) {
props = new Properties();
try {
props.load(Thread.currentThread().getContextClassLoader()
.getResource(properties).openStream());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 得到key的值
*
* @param key
* 取得其值的键
* @return key的值
*/
public static String getValue(String key) {
if (props!=null && props.containsKey(key)) {
return props.getProperty(key);// 得到某一属性的值
} else {
return "";
}
}
/**
* 图片上传路径
*
* @param orgcde
* @return
*/
public static String getFileUploadPath() {
String fileUploadPath = ConfigUtil.getValue("share") + "/";
FileUtil.makeDir(fileUploadPath);
return fileUploadPath;
}
/**
* 改变或添加一个key的值,当key存在于properties文件中时该key的值被value所代替, 当key不存在时,该key的值是value
*
* @param key
* 要存入的键
* @param value
* 要存入的值
*/
public void setValue(String key, String value) {
props.setProperty(key, value);
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed.
This diff is collapsed.
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