Commit de3de82d authored by dingzhiwei's avatar dingzhiwei
Browse files

初始化Jeepay项目

parent 40dcaf4a
package org.xxpay.common.util;
import org.apache.commons.beanutils.Converter;
import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Locale;
/**
* Created by admin on 2016/5/10.
*/
public class DateTimeConverter implements Converter {
private static final String DATE = "yyyy-MM-dd";
private static final String DATETIME = "yyyy-MM-dd HH:mm:ss";
private static final String TIMESTAMP = "yyyy-MM-dd HH:mm:ss.SSS";
@Override
public Object convert(Class type, Object value) {
return toDate(type, value);
}
public static Object toDate(Class type, Object value) {
if (value == null || "".equals(value))
return null;
if (value instanceof String) {
String dateValue = value.toString().trim();
int length = dateValue.length();
if (type.equals(java.util.Date.class)) {
try {
DateFormat formatter = null;
if (length <= 10) {
formatter = new SimpleDateFormat(DATE, new DateFormatSymbols(Locale.CHINA));
return formatter.parse(dateValue);
}
if (length <= 19) {
formatter = new SimpleDateFormat(DATETIME, new DateFormatSymbols(Locale.CHINA));
return formatter.parse(dateValue);
}
if (length <= 23) {
formatter = new SimpleDateFormat(TIMESTAMP, new DateFormatSymbols(Locale.CHINA));
return formatter.parse(dateValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return value;
}
}
package org.xxpay.common.util;
import org.apache.commons.lang3.StringUtils;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @Description: 日期时间工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class DateUtil {
public static final String FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_YYYYMMDDHHMMSSSSS = "yyyyMMddhhmmssSSS";
public static final String FORMAT_YYYYMMDDHHMMSS = "yyyyMMddhhmmss";
public static String getCurrentDate() {
String formatPattern_Short = "yyyyMMddhhmmss";
SimpleDateFormat format = new SimpleDateFormat(formatPattern_Short);
return format.format(new Date());
}
public static String getSeqString() {
SimpleDateFormat fm = new SimpleDateFormat("yyyyMMddHHmmss"); // "yyyyMMdd G
return fm.format(new Date());
}
public static Timestamp getCurrentTimestamp() {
return new Timestamp(System.currentTimeMillis());
}
/**
* 获取当前时间,格式为 yyyyMMddHHmmss
*
* @return
*/
public static String getCurrentTimeStr(String format) {
format = StringUtils.isBlank(format) ? FORMAT_YYYY_MM_DD_HH_MM_SS : format;
Date now = new Date();
return date2Str(now, format);
}
public static String date2Str(Date date) {
return date2Str(date, FORMAT_YYYY_MM_DD_HH_MM_SS);
}
/**
* 时间转换成 Date 类型
*
* @param date
* @param format
* @return
*/
public static String date2Str(Date date, String format) {
if ((format == null) || format.equals("")) {
format = FORMAT_YYYY_MM_DD_HH_MM_SS;
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
if (date != null) {
return sdf.format(date);
}
return "";
}
/**
* 获取批量付款预约时间
* @return
*/
public static String getRevTime() {
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
String dateString = new SimpleDateFormat(DateUtil.FORMAT_YYYYMMDDHHMMSS).format(cal.getTime());
System.out.println(dateString);
return dateString;
}
/**
* 时间比较
* @param date1
* @param date2
* @return DATE1>DATE2返回1,DATE1<DATE2返回-1,等于返回0
*/
public static int compareDate(String date1, String date2, String format) {
DateFormat df = new SimpleDateFormat(format);
try {
Date dt1 = df.parse(date1);
Date dt2 = df.parse(date2);
if (dt1.getTime() > dt2.getTime()) {
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
/**
* 把给定的时间减掉给定的分钟数
* @param date
* @param minute
* @return
*/
public static Date minusDateByMinute(Date date, int minute) {
Date newDate = new Date(date.getTime() - (minute * 60 * 1000));
return newDate;
}
}
package org.xxpay.common.util;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 时间格式化工具
* Created by admin on 2016/5/4.
*/
public class DateUtils {
private static final String DEFAULT_CONVERT_PATTERN = "yyyyMMddHHmmssSSS";
/**
* 获取当前时间字符串(默认格式:yyyyMMddHHmmssSSS)
*
* @return
*/
public static String getCurrentTimeStrDefault() {
return getCurrentTimeStr(DEFAULT_CONVERT_PATTERN);
}
/**
* 获取指定时间字符串(默认格式:yyyyMMddHHmmssSSS)
* @param date
* @return
*/
public static String getTimeStrDefault(Date date) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_CONVERT_PATTERN);
return dateFormat.format(date);
}
/**
* 获取当前时间字符串
*
* @param pattern 转换格式
* @return
*/
public static String getCurrentTimeStr(String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(new Date());
}
/**
* 获取指定时间字符串
* @param date
* @return
*/
public static String getTimeStr(Date date, String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
return dateFormat.format(date);
}
/**
* 判断时间字符串是否为默认格式
* @param dateTimeStr
* @return
*/
public static boolean isValidDefaultFormat(String dateTimeStr) {
SimpleDateFormat dateFormat = new SimpleDateFormat(DEFAULT_CONVERT_PATTERN);
try {
dateFormat.parse(dateTimeStr);
return true;
} catch (Exception e) {
// 如果抛出异常,说明格式不正确
return false;
}
}
}
package org.xxpay.common.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class HttpClient {
private static final String USER_AGENT_VALUE =
"Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)";
private static final String JKS_CA_FILENAME =
"tenpay_cacert.jks";
private static final String JKS_CA_ALIAS = "tenpay";
private static final String JKS_CA_PASSWORD = "";
private static Logger _log = LoggerFactory.getLogger(HttpClient.class);
/**
* ca证书文件
*/
private File caFile;
/**
* 证书文件
*/
private File certFile;
/**
* 证书密码
*/
private String certPasswd;
/**
* 请求内容,无论post和get,都用get方式提供
*/
private String reqContent;
/**
* 应答内容
*/
private String resContent;
/**
* 请求方法
*/
private String method;
/**
* 错误信息
*/
private String errInfo;
/**
* 超时时间,以秒为单位
*/
private int timeOut;
/**
* http应答编码
*/
private int responseCode;
/**
* 字符编码
*/
private String charset;
private InputStream inputStream;
public HttpClient() {
this.caFile = null;
this.certFile = null;
this.certPasswd = "";
this.reqContent = "";
this.resContent = "";
this.method = "POST";
this.errInfo = "";
this.timeOut = 30;//30秒
this.responseCode = 0;
this.charset = "UTF-8";
this.inputStream = null;
}
public HttpClient(String url, String method, int timeOut, String charset) {
this.caFile = null;
this.certFile = null;
this.certPasswd = "";
this.reqContent = url;
this.resContent = "";
this.method = method;
this.errInfo = "";
this.timeOut = timeOut;//30秒
this.responseCode = 0;
this.charset = charset;
this.inputStream = null;
}
/**
* 设置证书信息
*
* @param certFile 证书文件
* @param certPasswd 证书密码
*/
public void setCertInfo(File certFile, String certPasswd) {
this.certFile = certFile;
this.certPasswd = certPasswd;
}
/**
* 设置ca
*
* @param caFile
*/
public void setCaInfo(File caFile) {
this.caFile = caFile;
}
/**
* 设置请求内容
*
* @param reqContent 表求内容
*/
public void setReqContent(String reqContent) {
this.reqContent = reqContent;
}
/**
* 获取结果内容
*
* @return String
* @throws IOException
*/
public String getResContent() {
try {
this.doResponse();
} catch (IOException e) {
_log.error("", e);
this.errInfo = e.getMessage();
//return "";
}
return this.resContent;
}
/**
* 设置请求方法post或者get
*
* @param method 请求方法post/get
*/
public void setMethod(String method) {
this.method = method;
}
/**
* 获取错误信息
*
* @return String
*/
public String getErrInfo() {
return this.errInfo;
}
/**
* 设置超时时间,以秒为单位
*
* @param timeOut 超时时间,以秒为单位
*/
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
/**
* 获取http状态码
*
* @return int
*/
public int getResponseCode() {
return this.responseCode;
}
/**
* 执行http调用。true:成功 false:失败
*
* @return boolean
*/
public boolean call() {
boolean isRet = false;
//http
if (null == this.caFile && null == this.certFile) {
try {
this.callHttp();
isRet = true;
} catch (IOException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (Exception e) {
_log.error("", e);
this.errInfo = e.getMessage();
}
return isRet;
}
//https
return calls();
}
public boolean calls() {
boolean isRet = false;
//https
try {
this.callHttps();
isRet = true;
} catch (UnrecoverableKeyException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (KeyManagementException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (CertificateException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (KeyStoreException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (NoSuchAlgorithmException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (IOException e) {
_log.error("", e);
this.errInfo = e.getMessage();
} catch (Exception e) {
_log.error("", e);
this.errInfo = e.getMessage();
}
return isRet;
}
protected void callHttp() throws IOException {
if ("POST".equals(this.method.toUpperCase())) {
String url = HttpClientUtil.getURL(this.reqContent);
String queryString = HttpClientUtil.getQueryString(this.reqContent);
byte[] postData = queryString.getBytes(this.charset);
this.httpPostMethod(url, postData);
return;
}
this.httpGetMethod(this.reqContent);
}
protected void callHttps() throws IOException, CertificateException,
KeyStoreException, NoSuchAlgorithmException,
UnrecoverableKeyException, KeyManagementException {
// ca目录
/*String caPath = this.caFile.getParent();
File jksCAFile = new File(caPath + "/"
+ HttpClient.JKS_CA_FILENAME);
if (!jksCAFile.isFile()) {
X509Certificate cert = (X509Certificate) HttpClientUtil
.getCertificate(this.caFile);
FileOutputStream out = new FileOutputStream(jksCAFile);
// store jks file
HttpClientUtil.storeCACert(cert, HttpClient.JKS_CA_ALIAS,
HttpClient.JKS_CA_PASSWORD, out);
out.close();
}
FileInputStream trustStream = new FileInputStream(jksCAFile);
FileInputStream keyStream = new FileInputStream(this.certFile);*/
/*SSLContext sslContext = HttpClientUtil.getSSLContext(trustStream,
HttpClient.JKS_CA_PASSWORD, keyStream, this.certPasswd);*/
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new TrustAnyTrustManager()},
new java.security.SecureRandom());
//关闭流
//keyStream.close();
//trustStream.close();
if ("POST".equals(this.method.toUpperCase())) {
String url = HttpClientUtil.getURL(this.reqContent);
String queryString = HttpClientUtil.getQueryString(this.reqContent);
byte[] postData = queryString.getBytes(this.charset);
this.httpsPostMethod(url, postData, sslContext);
return;
}
this.httpsGetMethod(this.reqContent, sslContext);
}
/**
* 以http post方式通信
*
* @param url
* @param postData
* @throws IOException
*/
protected void httpPostMethod(String url, byte[] postData)
throws IOException {
HttpURLConnection conn = HttpClientUtil.getHttpURLConnection(url);
this.doPost(conn, postData);
}
/**
* 以http get方式通信
*
* @param url
* @throws IOException
*/
protected void httpGetMethod(String url) throws IOException {
HttpURLConnection httpConnection =
HttpClientUtil.getHttpURLConnection(url);
this.setHttpRequest(httpConnection);
httpConnection.setRequestMethod("GET");
this.responseCode = httpConnection.getResponseCode();
this.inputStream = httpConnection.getInputStream();
}
/**
* 以https get方式通信
*
* @param url
* @param sslContext
* @throws IOException
*/
protected void httpsGetMethod(String url, SSLContext sslContext)
throws IOException {
SSLSocketFactory sf = sslContext.getSocketFactory();
HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);
conn.setSSLSocketFactory(sf);
this.doGet(conn);
}
protected void httpsPostMethod(String url, byte[] postData,
SSLContext sslContext) throws IOException {
SSLSocketFactory sf = sslContext.getSocketFactory();
HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);
conn.setSSLSocketFactory(sf);
this.doPost(conn, postData);
}
/**
* 设置http请求默认属性
*
* @param httpConnection
*/
protected void setHttpRequest(HttpURLConnection httpConnection) {
//设置连接超时时间
httpConnection.setConnectTimeout(this.timeOut * 1000);
//User-Agent
httpConnection.setRequestProperty("User-Agent",
HttpClient.USER_AGENT_VALUE);
//不使用缓存
httpConnection.setUseCaches(false);
//允许输入输出
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
}
/**
* 处理应答
*
* @throws IOException
*/
protected void doResponse() throws IOException {
if (null == this.inputStream) {
return;
}
//获取应答内容
this.resContent = HttpClientUtil.InputStreamTOString(this.inputStream, this.charset);
//关闭输入流
this.inputStream.close();
}
/**
* post方式处理
*
* @param conn
* @param postData
* @throws IOException
*/
protected void doPost(HttpURLConnection conn, byte[] postData)
throws IOException {
// 以post方式通信
conn.setRequestMethod("POST");
// 设置请求默认属性
this.setHttpRequest(conn);
// Content-Type
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
BufferedOutputStream out = new BufferedOutputStream(conn
.getOutputStream());
final int len = 1024; // 1KB
HttpClientUtil.doOutput(out, postData, len);
/*PrintWriter out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(new String(postData));
// flush输出流的缓冲
out.flush();*/
// 关闭流
out.close();
// 获取响应返回状态码
this.responseCode = conn.getResponseCode();
// 获取应答输入流
this.inputStream = conn.getInputStream();
}
/**
* get方式处理
*
* @param conn
* @throws IOException
*/
protected void doGet(HttpURLConnection conn) throws IOException {
//以GET方式通信
conn.setRequestMethod("GET");
//设置请求默认属性
this.setHttpRequest(conn);
//获取响应返回状态码
this.responseCode = conn.getResponseCode();
//获取应答输入流
this.inputStream = conn.getInputStream();
}
public static String callHttpPost(String url) {
return callHttpPost(url, 60); // 默认超时时间60秒
}
public static String callHttpPost(String url, int connect_timeout) {
return callHttpPost(url, connect_timeout, "UTF-8"); // 默认编码 UTF-8
}
public static String callHttpPost(String url, int connect_timeout, String encode) {
HttpClient client = new HttpClient(url, "POST", connect_timeout, encode);
client.call();
return client.getResContent();
}
public static String callHttpsPost(String url) {
HttpClient client = new HttpClient(url, "POST", 60, "UTF-8");
client.calls();
return client.getResContent();
}
private static class TrustAnyTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
}
package org.xxpay.common.util;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class HttpClientUtil {
public static final String SunX509 = "SunX509";
public static final String JKS = "JKS";
public static final String PKCS12 = "PKCS12";
public static final String TLS = "TLS";
private static final String encoding = "UTF-8";
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* get HttpURLConnection
* @param strUrl url地址
* @return HttpURLConnection
* @throws IOException
*/
public static HttpURLConnection getHttpURLConnection(String strUrl)
throws IOException {
URL url = new URL(strUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
return httpURLConnection;
}
/**
* get HttpsURLConnection
* @param strUrl url地址
* @return HttpsURLConnection
* @throws IOException
*/
public static HttpsURLConnection getHttpsURLConnection(String strUrl)
throws IOException {
URL url = new URL(strUrl);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url
.openConnection();
return httpsURLConnection;
}
/**
* 获取不带查询串的url
* @param strUrl
* @return String
*/
public static String getURL(String strUrl) {
if(null != strUrl) {
int indexOf = strUrl.indexOf("?");
if(-1 != indexOf) {
return strUrl.substring(0, indexOf);
}
return strUrl;
}
return strUrl;
}
/**
* 获取查询串
* @param strUrl
* @return String
*/
public static String getQueryString(String strUrl) {
if(null != strUrl) {
int indexOf = strUrl.indexOf("?");
if(-1 != indexOf) {
return strUrl.substring(indexOf+1, strUrl.length());
}
return "";
}
return strUrl;
}
/**
* 查询字符串转换成Map<br/>
* name1=key1&name2=key2&...
* @param queryString
* @return
*/
public static Map queryString2Map(String queryString) {
if(null == queryString || "".equals(queryString)) {
return null;
}
Map m = new HashMap();
String[] strArray = queryString.split("&");
for(int index = 0; index < strArray.length; index++) {
String pair = strArray[index];
HttpClientUtil.putMapByPair(pair, m);
}
return m;
}
/**
* 把键值添加至Map<br/>
* pair:name=value
* @param pair name=value
* @param m
*/
public static void putMapByPair(String pair, Map m) {
if(null == pair || "".equals(pair)) {
return;
}
int indexOf = pair.indexOf("=");
if(-1 != indexOf) {
String k = pair.substring(0, indexOf);
String v = pair.substring(indexOf+1, pair.length());
if(null != k && !"".equals(k)) {
m.put(k, v);
}
} else {
m.put(pair, "");
}
}
/**
* BufferedReader转换成String<br/>
* 注意:流关闭需要自行处理
* @param reader
* @return String
* @throws IOException
*/
public static String bufferedReader2String(BufferedReader reader) throws IOException {
StringBuffer buf = new StringBuffer();
String line = null;
while( (line = reader.readLine()) != null) {
buf.append(line);
buf.append("\r\n");
}
return buf.toString();
}
/**
* 处理输出<br/>
* 注意:流关闭需要自行处理
* @param out
* @param data
* @param len
* @throws IOException
*/
public static void doOutput(OutputStream out, byte[] data, int len)
throws IOException {
int dataLen = data.length;
int off = 0;
while (off < data.length) {
if (len >= dataLen) {
out.write(data, off, dataLen);
off += dataLen;
} else {
out.write(data, off, len);
off += len;
dataLen -= len;
}
// 刷新缓冲区
out.flush();
}
}
/**
* 获取SSLContext
* @param trustPasswd
* @param keyPasswd
* @return
* @throws NoSuchAlgorithmException
* @throws KeyStoreException
* @throws IOException
* @throws CertificateException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
*/
public static SSLContext getSSLContext(
FileInputStream trustFileInputStream, String trustPasswd,
FileInputStream keyFileInputStream, String keyPasswd)
throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, IOException, UnrecoverableKeyException,
KeyManagementException {
// ca
TrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);
KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);
trustKeyStore.load(trustFileInputStream, HttpClientUtil
.str2CharArray(trustPasswd));
tmf.init(trustKeyStore);
final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);
KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);
ks.load(keyFileInputStream, kp);
kmf.init(ks, kp);
SecureRandom rand = new SecureRandom();
SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);
return ctx;
}
/**
* 获取CA证书信息
* @param cafile CA证书文件
* @return Certificate
* @throws CertificateException
* @throws IOException
*/
public static Certificate getCertificate(File cafile)
throws CertificateException, IOException {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in = new FileInputStream(cafile);
Certificate cert = cf.generateCertificate(in);
in.close();
return cert;
}
/**
* 字符串转换成char数组
* @param str
* @return char[]
*/
public static char[] str2CharArray(String str) {
if(null == str) return null;
return str.toCharArray();
}
/**
* 存储ca证书成JKS格式
* @param cert
* @param alias
* @param password
* @param out
* @throws KeyStoreException
* @throws NoSuchAlgorithmException
* @throws CertificateException
* @throws IOException
*/
public static void storeCACert(Certificate cert, String alias,
String password, OutputStream out) throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
ks.setCertificateEntry(alias, cert);
// store keystore
ks.store(out, HttpClientUtil.str2CharArray(password));
}
public static InputStream String2Inputstream(String str) {
return new ByteArrayInputStream(str.getBytes());
}
/**
* InputStream转换成Byte
* 注意:流关闭需要自行处理
* @param in
* @return byte
* @throws Exception
*/
public static byte[] InputStreamTOByte(InputStream in) throws IOException{
int BUFFER_SIZE = 4096;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1;
while((count = in.read(data,0,BUFFER_SIZE)) != -1)
outStream.write(data, 0, count);
data = null;
byte[] outByte = outStream.toByteArray();
outStream.close();
return outByte;
}
/**
* InputStream转换成String
* 注意:流关闭需要自行处理
* @param in
* @param encoding 编码
* @return String
* @throws Exception
*/
public static String InputStreamTOString(InputStream in,String encoding) throws IOException{
return new String(InputStreamTOByte(in),encoding);
}
}
package org.xxpay.common.util;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* @Description: IP地址工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class IPUtility {
/**
* getLocalhostIp(获取本机ip地址)
* @throws UnknownHostException
* @Exception 异常对象
* @since CodingExample Ver(编码范例查看) 1.1
*/
public static String getLocalhostIp() {
String ip = "";
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (Exception e) {
return null;
}
return ip;
}
public static List<String> getIpAddrs() throws Exception {
List<String> IPs = new ArrayList<String>();
Enumeration<NetworkInterface> allNetInterfaces = null;
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
Enumeration<?> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address && ip.getHostAddress().indexOf(".") != -1) {
IPs.add(ip.getHostAddress());
}
}
}
return IPs;
}
/**
* 兼容Linux系统
* @return
*/
public static String getLocalIP() {
String ip = "";
try {
Enumeration<?> e1 = (Enumeration<?>) NetworkInterface
.getNetworkInterfaces();
while (e1.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e1.nextElement();
Enumeration<?> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ia = (InetAddress) e2.nextElement();
if (ia instanceof Inet6Address)
continue;
if (!ia.isLoopbackAddress()) {
ip = ia.getHostAddress();
break;
}
}
}
} catch (SocketException e) {
e.printStackTrace();
return "";
}
return ip;
}
public static void main(String[] args) throws Exception {
System.out.println(IPUtility.getLocalIP());
}
}
package org.xxpay.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.List;
/**
* Created by admin on 2016/4/13.
*/
public class JsonUtil {
static {
System.setProperty("fastjson.compatibleWithJavaBean", "true");
}
public static String object2Json(Object object) {
if (object == null) {
return null;
}
return JSONObject.toJSONString(object);
}
public static <T> T getObjectFromJson(String json, Class<T> clazz) {
if (json == null) {
return null;
}
return JSON.parseObject(json, clazz);
}
public static <T> List<T> getObjectListFromJson(String json, Class<T> clazz) {
if (json == null) {
return null;
}
return JSON.parseArray(json, clazz);
}
public static JSONObject getJSONObjectFromJson(String json) {
if (json == null) {
return null;
}
return JSONObject.parseObject(json);
}
public static JSONObject getJSONObjectFromObj(Object object) {
if (object == null) {
return null;
}
return (JSONObject) JSONObject.toJSON(object);
}
}
package org.xxpay.common.util;
/**
* @Description: base64编码解码工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class MyBase64 {
public final static String encode(byte[] src, int startIndex, int srclen) {
if (src == null) return null;
if (startIndex+srclen>src.length) srclen = src.length-startIndex;
byte src2[] = new byte[srclen];
System.arraycopy(src, startIndex, src2, 0, srclen);
return encode(src2);
}
public final static String encode(byte[] src, int srclen) {
if (src == null) return null;
if (srclen>src.length) srclen = src.length;
byte data[] = new byte[srclen+2];
System.arraycopy(src, 0, data, 0, srclen);
byte dest[] = new byte[(data.length/3)*4];
// 3-byte to 4-byte conversion
for (int sidx = 0, didx=0; sidx < srclen; sidx += 3, didx += 4) {
dest[didx] = (byte) ((data[sidx] >>> 2) & 077);
dest[didx+1] = (byte) ((data[sidx+1] >>> 4) & 017 | (data[sidx] << 4) & 077);
dest[didx+2] = (byte) ((data[sidx+2] >>> 6) & 003 | (data[sidx+1] << 2) & 077);
dest[didx+3] = (byte) (data[sidx+2] & 077);
}
// 0-63 to ascii printable conversion
for (int idx = 0; idx <dest.length; idx++) {
if (dest[idx] < 26) dest[idx] = (byte)(dest[idx] + 'A');
else if (dest[idx] < 52) dest[idx] = (byte)(dest[idx] + 'a' - 26);
else if (dest[idx] < 62) dest[idx] = (byte)(dest[idx] + '0' - 52);
else if (dest[idx] < 63) dest[idx] = (byte)'+';
else dest[idx] = (byte)'/';
}
// add padding
for (int idx = dest.length-1; idx > (srclen*4)/3; idx--) {
dest[idx] = (byte)'=';
}
return new String(dest);
}
public final static String encode(byte[] d) {
return encode(d, d.length);
}
/** 每64字符后,换行 */
public static String encode_64(byte[] bin) throws Exception {
String b64 = MyBase64.encode(bin);
StringBuffer sb = new StringBuffer();
for(int offset=0; offset < b64.length(); offset+=64) {
int idx_begin = offset;
int idx_end = Math.min(offset+64, b64.length());
String s = b64.substring(idx_begin, idx_end);
sb.append(s).append('\n');
//if (withDebug) debug(idx_begin+"..."+idx_end);
}
b64 = sb.toString();
return b64;
}
public final static byte[] decode(String str) {
if (str == null) return new byte[0];
str = str.trim(); //TODO 去掉结尾空格,但还不彻底,可考虑进一步改善。。。
if (str.length()==0) return new byte[0];
return decode(str.getBytes());
}
private final static byte[] decode(byte[] data) {
int tail = data.length;
while (data[tail-1] == '=') tail--; //去掉结尾的等号
byte dest[] = new byte[tail - data.length/4];
for(int i = 0; i <data.length; i++) {// ascii printable to 0-63 conversion
data[i] = decode_pre_byte(data[i]); //TODO ??是否有用?
}
// 4-byte to 3-byte conversion
int sidx, didx;
for (sidx = 0, didx=0; didx < dest.length-2; sidx += 4, didx += 3) {
dest[didx] = (byte) ( ((data[sidx] << 2) & 255) | ((data[sidx+1] >>> 4) & 3) );
dest[didx+1] = (byte) ( ((data[sidx+1] << 4) & 255) | ((data[sidx+2] >>> 2) & 017) );
dest[didx+2] = (byte) ( ((data[sidx+2] << 6) & 255) | ( data[sidx+3] & 077) );
}
if (didx < dest.length) {
dest[didx] = (byte) ( ((data[sidx] << 2) & 255) | ((data[sidx+1] >>> 4) & 3) );
}
if (++didx < dest.length) {
dest[didx] = (byte) ( ((data[sidx+1] << 4) & 255) | ((data[sidx+2] >>> 2) & 017) );
}
return dest;
}
private final static byte decode_pre_byte(byte b0) { //重构。。。
byte b = 0;
if (b0 >= '0' && b0 <= '9') b = (byte)(b0 - ('0' - 52));
else if (b0 >= 'a' && b0 <= 'z') b = (byte)(b0 - ('a' - 26));
else if (b0 >= 'A' && b0 <= 'Z') b = (byte)(b0 - 'A');
else if (b0 == '=') b = 0;
else if (b0 == '+') b = 62;
else if (b0 == '/') b = 63;
return b;
}
/**
* A simple test.cache that encodes and decodes the first commandline argument.
*/
public final static void main(String args[]) throws Exception {
String s = "xxpay做最好的开源聚合支付系统";
System.out.println(MyBase64.encode(s.getBytes()));
}
}
\ No newline at end of file
package org.xxpay.common.util;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Created by admin on 2016/4/27.
*/
public class MyLog extends MyLogFace {
private static final Map<String,MyLog> _pool = new HashMap<String,MyLog>();
//----------
public static synchronized Set<String> getLoggers() {
return _pool.keySet();
}
public static synchronized void clearLoggers() {
_pool.clear();
}
//----------
public static synchronized MyLog getLog(String clz) {
MyLog log = _pool.get(clz);
if (log==null) {
log = new MyLog();
log.setName(clz);
_pool.put(clz, log);
}
return log;
}
//----------
public static MyLog getLog(Class<?> clz){
return getLog(clz.getName());
}
}
package org.xxpay.common.util;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class MyLogFace implements MyLogInf {
private org.slf4j.Logger _log = null;
public void setName(String clz) { _log = org.slf4j.LoggerFactory.getLogger(clz); }
public boolean isDebugEnabled() { return _log.isDebugEnabled(); }
public boolean isInfoEnabled() { return _log.isInfoEnabled(); }
public boolean isWarnEnabled() { return _log.isWarnEnabled(); }
public boolean isErrorEnabled() { return _log.isErrorEnabled(); }
public boolean isTraceEnabled() { return _log.isTraceEnabled(); }
public void trace(String message, Object... args) {
if (this.isTraceEnabled()) _log.trace(message, args);
}
public void debug(String message, Object... args) {
if (this.isDebugEnabled()) _log.debug(message, args);
}
public void info(String message, Object... args) {
if (this.isInfoEnabled()) _log.info(message, args);
}
public void warn(String message, Object... args) {
if (this.isWarnEnabled()) _log.warn(message, args);
}
public void error(String message, Object... args) {
if (this.isErrorEnabled()) _log.error(message, args);
}
public void error(Throwable e, String message, Object... args) {
if (this.isErrorEnabled()) _log.error(String.format(message, args), e);
}
//------------------
public void error(Throwable e, String message) {//简化版
if (this.isErrorEnabled()) _log.error(message+e.toString(), e);
}
}
package org.xxpay.common.util;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public abstract interface MyLogInf {
public abstract void debug(String paramString, Object[] paramArrayOfObject);
public abstract void info(String paramString, Object[] paramArrayOfObject);
public abstract void warn(String paramString, Object[] paramArrayOfObject);
public abstract void error(Throwable paramThrowable, String paramString, Object[] paramArrayOfObject);
}
package org.xxpay.common.util;
import java.util.Date;
import java.util.HashMap;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* @Description: 属性文件工具类,支持缓存及刷新
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class MyProperties {
private static HashMap<String, MyProperties> configMap = new HashMap<String, MyProperties>();
private Date loadTime = null;
private ResourceBundle rb = null;
private static final String CONFIG_FILE = "properties";
private static final long CONFIG_CACHE_TIME = 60 * 1000; // 缓存1分钟
private MyProperties(String name) {
this.loadTime = new Date();
this.rb = ResourceBundle.getBundle(name);
}
public static synchronized MyProperties getInstance(String name) {
MyProperties conf = configMap.get(name);
if (null == conf) {
conf = new MyProperties(name);
configMap.put(name, conf);
return conf;
}
if (new Date().getTime() - conf.getLoadTime().getTime() > CONFIG_CACHE_TIME) {
conf = new MyProperties(name);
configMap.put(name, conf);
return conf;
}
return conf;
}
public static synchronized MyProperties getInstance() {
return getInstance("config");
}
public Date getLoadTime() {
return loadTime;
}
public String getValue(String key) {
try {
String v = rb.getString(key);
return v;
}catch (MissingResourceException e) {
return "";
}
}
public boolean getBool(String key) {
String v = getValue(key);
if (v.equalsIgnoreCase("true"))
return true;
return false;
}
public int getInt(String key) {
String v = getValue(key);
return Integer.parseInt(v);
}
public long getLong(String key) {
String v = getValue(key);
return Long.parseLong(v);
}
public static void main(String[] args) throws InterruptedException {
for (int i=0; i<10; i++) {
String v = MyProperties.getInstance("common").getValue("jdbc.jndi.name");
Thread.sleep(1000 * 30);
}
}
}
package org.xxpay.common.util;
import java.util.concurrent.atomic.AtomicLong;
/**
* @Description: 生成全局唯一序列号工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class MySeq {
private static AtomicLong pay_seq = new AtomicLong(0L);
private static String pay_seq_prefix = "P";
private static AtomicLong trans_seq = new AtomicLong(0L);
private static String trans_seq_prefix = "T";
private static AtomicLong refund_seq = new AtomicLong(0L);
private static String refund_seq_prefix = "R";
private static String node = "00";
static {
try {
//URL url = Thread.currentThread().getContextClassLoader().getResource("config" + File.separator + "system.properties");
//Properties properties = new Properties();
//properties.load(url.openStream());
//node = properties.getProperty(ConfigEnum.SERVER_NAME.getKey());
}catch (Exception e) {
e.printStackTrace();
}
}
public static String getPay() {
return getSeq(pay_seq_prefix, pay_seq);
}
public static String getTrans() {
return getSeq(trans_seq_prefix, trans_seq);
}
public static String getRefund() {
return getSeq(refund_seq_prefix, refund_seq);
}
private static String getSeq(String prefix, AtomicLong seq) {
prefix += node;
return String.format("%s%s%06d", prefix, DateUtil.getSeqString(), (int) seq.getAndIncrement() % 1000000);
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println("pay=" + getPay());
System.out.println("trans=" + getTrans());
System.out.println("refund=" + getRefund());
}
}
}
\ No newline at end of file
package org.xxpay.common.util;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
/**
* Created by admin on 2016/6/23.
*/
public class ObjectValidUtil {
public static boolean isValid(Object... objs) {
if (objs == null || objs.length < 1) {
return false;
}
for (Object obj : objs) {
if (obj instanceof Short) {
if (isNull(obj)) {
return false;
}
} else if (obj instanceof Integer) {
if (isInvalidInteger((Integer) obj)) {
return false;
}
} else if (obj instanceof Long) {
if (isInvalidLong((Long) obj)) {
return false;
}
} else if (obj instanceof String) {
if (isInvalidString(obj.toString())) {
return false;
}
} else if (obj instanceof List) {
if (CollectionUtils.isEmpty((List) obj)) {
return false;
}
} else if (obj instanceof Map) {
if (isNull(obj) || ((Map) obj).isEmpty()) {
return false;
}
} else {
if (isNull(obj)) {
return false;
}
}
}
return true;
}
public static boolean isInvalid(Object... objs) {
return !isValid(objs);
}
/**
* 判断是否为有效Short值
* @param num
* @return
*/
public static boolean isValidShort(Short num) {
if (num == null || num.compareTo((short) 0) <= 0) {
return false;
}
return true;
}
public static boolean isInvalidShort(Short num) {
return !isValidShort(num);
}
/**
* 判断是否为有效Integer值
* @param num
* @return
*/
public static boolean isValidInteger(Integer num) {
if (num == null || num.compareTo(0) <= 0) {
return false;
}
return true;
}
public static boolean isInvalidInteger(Integer num) {
return !isValidInteger(num);
}
/**
* 判断是否为有效Long值
* @param num
* @return
*/
public static boolean isValidLong(Long num) {
if (num == null || num.compareTo(0L) <= 0) {
return false;
}
return true;
}
public static boolean isInvalidLong(Long num) {
return !isValidLong(num);
}
/**
* 判断是否为有效BigDecimal值
* @param num
* @return
*/
public static boolean isValidBigDecimal(BigDecimal num) {
if (num == null || num.compareTo(BigDecimal.ZERO) <= 0) {
return false;
}
return true;
}
public static boolean isInvalidBigDecimal(BigDecimal num) {
return !isValidBigDecimal(num);
}
/**
* 判断是否为有效String值
* @param str
* @return
*/
public static boolean isValidString(String str) {
return StringUtils.isNotBlank(str);
}
public static boolean isInvalidString(String str) {
return StringUtils.isBlank(str);
}
public static boolean isNull(Object obj) {
if (obj == null) {
return true;
}
return false;
}
public static boolean isNotNull(Object obj) {
return !isNull(obj);
}
public static boolean isValidCurPage(Integer curPage) {
if (curPage == null) {
return false;
}
if (curPage.compareTo(1) < 0) {
return false;
}
return true;
}
public static boolean isValidCurPage(Long curPage) {
if (curPage == null) {
return false;
}
if (curPage.compareTo(1L) < 0) {
return false;
}
return true;
}
public static boolean isInvalidCurPage(Integer curPage) {
return !isValidCurPage(curPage);
}
public static boolean isInvalidCurPage(Long curPage) {
return !isValidCurPage(curPage);
}
public static boolean isValidViewNumber(Integer viewNumber) {
if (viewNumber == null) {
return false;
}
if (viewNumber.compareTo(0) <= 0) {
return false;
}
return true;
}
public static boolean isValidViewNumber(Long viewNumber) {
if (viewNumber == null) {
return false;
}
if (viewNumber.compareTo(0L) <= 0) {
return false;
}
return true;
}
public static boolean isInvalidViewNumber(Integer viewNumber) {
return !isValidViewNumber(viewNumber);
}
public static boolean isInvalidViewNumber(Long viewNumber) {
return !isValidViewNumber(viewNumber);
}
public static boolean isValidLimit(Integer limit) {
if (limit == null) {
return false;
}
if (limit.compareTo(0) <= 0) {
return false;
}
return true;
}
public static boolean isInvalidLimit(Integer limit) {
return !isValidLimit(limit);
}
public static boolean isAllNull(Object... objs) {
if (objs == null || objs.length < 1) {
return true;
}
int nullcount = 0;
for (Object obj : objs) {
if (isNull(obj)) {
nullcount++;
}
}
return objs.length == nullcount;
}
}
package org.xxpay.common.util;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @Description:
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class PayDigestUtil {
private static final MyLog _log = MyLog.getLog(PayDigestUtil.class);
private static String encodingCharset = "UTF-8";
/**
* @param aValue
* @param aKey
* @return
*/
public static String hmacSign(String aValue, String aKey) {
byte k_ipad[] = new byte[64];
byte k_opad[] = new byte[64];
byte keyb[];
byte value[];
try {
keyb = aKey.getBytes(encodingCharset);
value = aValue.getBytes(encodingCharset);
} catch (UnsupportedEncodingException e) {
keyb = aKey.getBytes();
value = aValue.getBytes();
}
Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
for (int i = 0; i < keyb.length; i++) {
k_ipad[i] = (byte) (keyb[i] ^ 0x36);
k_opad[i] = (byte) (keyb[i] ^ 0x5c);
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
md.update(k_ipad);
md.update(value);
byte dg[] = md.digest();
md.reset();
md.update(k_opad);
md.update(dg, 0, 16);
dg = md.digest();
return toHex(dg);
}
public static String toHex(byte input[]) {
if (input == null)
return null;
StringBuffer output = new StringBuffer(input.length * 2);
for (int i = 0; i < input.length; i++) {
int current = input[i] & 0xff;
if (current < 16)
output.append("0");
output.append(Integer.toString(current, 16));
}
return output.toString();
}
/**
*
* @param args
* @param key
* @return
*/
public static String getHmac(String[] args, String key) {
if (args == null || args.length == 0) {
return (null);
}
StringBuffer str = new StringBuffer();
for (int i = 0; i < args.length; i++) {
str.append(args[i]);
}
return (hmacSign(str.toString(), key));
}
/**
* @param aValue
* @return
*/
public static String digest(String aValue) {
aValue = aValue.trim();
byte value[];
try {
value = aValue.getBytes(encodingCharset);
} catch (UnsupportedEncodingException e) {
value = aValue.getBytes();
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
return toHex(md.digest(value));
}
public static String md5(String value, String charset) {
MessageDigest md = null;
try {
byte[] data = value.getBytes(charset);
md = MessageDigest.getInstance("MD5");
byte[] digestData = md.digest(data);
return toHex(digestData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
public static String getSign(Object o, String key) throws IllegalAccessException {
if(o instanceof Map) {
return getSign((Map<String, Object>)o, key);
}
ArrayList<String> list = new ArrayList<String>();
Class cls = o.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
if (f.get(o) != null && !"".equals(f.get(o))) {
list.add(f.getName() + "=" + f.get(o) + "&");
}
}
int size = list.size();
String [] arrayToSort = list.toArray(new String[size]);
Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < size; i ++) {
sb.append(arrayToSort[i]);
}
String result = sb.toString();
result += "key=" + key;
_log.debug("Sign Before MD5:" + result);
result = md5(result, encodingCharset).toUpperCase();
_log.debug("Sign Result:" + result);
return result;
}
public static String getSign(Map<String,Object> map, String key){
ArrayList<String> list = new ArrayList<String>();
for(Map.Entry<String,Object> entry:map.entrySet()){
if(!"".equals(entry.getValue()) && null != entry.getValue()){
list.add(entry.getKey() + "=" + entry.getValue() + "&");
}
}
int size = list.size();
String [] arrayToSort = list.toArray(new String[size]);
Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < size; i ++) {
sb.append(arrayToSort[i]);
}
String result = sb.toString();
result += "key=" + key;
_log.debug("Sign Before MD5:" + result);
result = md5(result, encodingCharset).toUpperCase();
_log.debug("Sign Result:" + result);
return result;
}
/**
*
* @param map
* @param key
* @param notContains 不包含的签名字段
* @return
*/
public static String getSign(Map<String,Object> map, String key, String... notContains){
Map<String,Object> newMap = new HashMap<String,Object>();
for(Map.Entry<String,Object> entry:map.entrySet()){
boolean isContain = false;
for(int i=0; i<notContains.length; i++) {
if(entry.getKey().equals(notContains[i])) {
isContain = true;
break;
}
}
if(!isContain) {
newMap.put(entry.getKey(), entry.getValue());
}
}
return getSign(newMap, key);
}
public static void main(String[] args) {
String key = "8UPp0KE8sq73zVP370vko7C39403rtK1YwX40Td6irH216036H27Eb12792t";
String dataStr = "AnnulCard1000043252120080620160450.0http://localhost/SZXpro/callback.asp这4564868265473632445648682654736324511";
System.out.println(hmacSign(dataStr, key));
System.out.println(md5(dataStr, "UTF-8"));
System.out.println(md5(dataStr, "GBK"));
}
}
package org.xxpay.common.util;
import java.util.ResourceBundle;
/**
* @Description: 属性文件工具类
* @author dingzhiwei jmdhappy@126.com
* @date 2017-07-05
* @version V1.0
* @Copyright: www.xxpay.org
*/
public class PropertiesFileUtil {
private ResourceBundle rb = null;
public PropertiesFileUtil(String bundleFile) {
rb = ResourceBundle.getBundle(bundleFile);
}
public String getValue(String key) {
return rb.getString(key);
}
public static void main(String[] args) {
}
}
package org.xxpay.common.util;
import org.xxpay.common.constant.Constant;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
/**
* 生成随机通讯码工具类
* Created by admin on 2016/5/4.
*/
public class RandomStrUtils {
private static Object lock = new Object();
private static RandomStrUtils instance;
private Map<String, Long> randomStrMap = new ConcurrentHashMap<String, Long>();
private static final String[] BASE_STRING = new String[]{
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z", "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"
};
private static final int RANDOM_STRING_LENGTH = 6;
private RandomStrUtils() {
}
public static RandomStrUtils getInstance() {
synchronized (lock) {
if (instance == null) {
instance = new RandomStrUtils();
}
}
return instance;
}
public String getRandomString() {
Long nowTime = System.currentTimeMillis();
String randomStr = null;
synchronized (lock) {
// 生成随机字符串
randomStr = createRandomString(RANDOM_STRING_LENGTH, nowTime);
// 删除一分钟前的随机字符串
Iterator<Map.Entry<String, Long>> it = randomStrMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Long> entry = it.next();
Long value = entry.getValue();
if (nowTime - value > Constant.RPC_SEQ_NO_NOT_REPEAT_INTERVAL) {
it.remove();
}
}
}
return randomStr;
}
private String createRandomString(int len, Long nowTime) {
Random random = new Random();
int length = BASE_STRING.length;
String randomString = "";
for (int i = 0; i < length; i++) {
randomString += BASE_STRING[random.nextInt(length)];
}
random = new Random(System.currentTimeMillis());
String resultStr = "";
for (int i = 0; i < len; i++) {
resultStr += randomString.charAt(random.nextInt(randomString.length() - 1));
}
// 判断一分钟内是否重复
Long randomStrCreateTime = randomStrMap.get(resultStr);
if (randomStrCreateTime != null &&
nowTime - randomStrCreateTime < Constant.RPC_SEQ_NO_NOT_REPEAT_INTERVAL) {
resultStr = createRandomString(len, nowTime);
}
randomStrMap.put(resultStr, nowTime);
return resultStr;
}
}
package org.xxpay.common.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* RPC通讯层签名工具类
* Created by admin on 2016/5/3.
*/
public class RpcSignUtils {
public static String sha1(String decript) {
try {
MessageDigest digest = MessageDigest
.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// 字节数组转换为 十六进制 数
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
package org.xxpay.common.util;
import org.xxpay.common.constant.Constant;
import org.xxpay.common.domain.BaseParam;
import org.xxpay.common.domain.RpcBaseParam;
import org.xxpay.common.enumm.RetEnum;
import java.util.HashMap;
import java.util.Map;
/**
* @author: dingzhiwei
* @date: 17/9/9
* @description:
*/
public class RpcUtil {
public static BaseParam getBaseParam(Map<String, Object> paramMap) {
if (paramMap == null || paramMap.isEmpty()) {
return null;
}
BaseParam baseParam = BeanConvertUtils.map2Bean(paramMap, BaseParam.class);
paramMap.remove("rpcSrcSysId");
paramMap.remove("rpcDateTime");
paramMap.remove("rpcSeqNo");
paramMap.remove("rpcSignType");
paramMap.remove("rpcSign");
paramMap.remove("bizSeqNo");
paramMap.remove("bizSign");
baseParam.setBizParamMap(paramMap);
return baseParam;
}
/**
* 构建成功返回结果
* @param baseParam
* @param obj
* @return
*/
public static Map<String, Object> createBizResult(RpcBaseParam baseParam, Object obj) {
Map<String, Object> resultMap = createResultMap(baseParam, RetEnum.RET_SUCCESS);
resultMap.put(Constant.BIZ_RESULT_KEY, obj);
return resultMap;
}
public static Map<String, Object> createBizResultWithDBError(RpcBaseParam baseParam, Object obj,
String dbErrorCode, String dbErrorMsg) {
Map<String, Object> resultMap = createResultMapWithDBError(baseParam, RetEnum.RET_SUCCESS, dbErrorCode, dbErrorMsg);
resultMap.put(Constant.BIZ_RESULT_KEY, obj);
return resultMap;
}
/**
* 构建失败返回结果
* @param rpcBaseParam
* @param retEnum
* @return
*/
public static Map<String, Object> createFailResult(RpcBaseParam rpcBaseParam, RetEnum retEnum) {
if (retEnum == null) {
retEnum = RetEnum.RET_PARAM_NOT_FOUND;
}
return createResultMap(rpcBaseParam, retEnum);
}
public static Map<String, Object> createFailResultWithDBError(RpcBaseParam rpcBaseParam, RetEnum retEnum,
String dbErrorCode, String dbErrorMsg) {
if (retEnum == null) {
retEnum = RetEnum.RET_PARAM_NOT_FOUND;
}
return createResultMapWithDBError(rpcBaseParam, retEnum, dbErrorCode, dbErrorMsg);
}
private static Map<String, Object> createResultMap(RpcBaseParam rpcBaseParam, RetEnum retEnum) {
Map<String, Object> resultMap = null;
if (rpcBaseParam != null) {
resultMap = rpcBaseParam.convert2Map();
} else {
resultMap = new HashMap<String, Object>();
}
resultMap.put("rpcRetCode", retEnum.getCode());
resultMap.put("rpcRetMsg", retEnum.getMessage());
return resultMap;
}
private static Map<String, Object> createResultMapWithDBError(RpcBaseParam rpcBaseParam, RetEnum retEnum,
String dbErrorCode, String dbErrorMsg) {
Map<String, Object> resultMap = null;
if (rpcBaseParam != null) {
resultMap = rpcBaseParam.convert2Map();
} else {
resultMap = new HashMap<String, Object>();
}
resultMap.put("rpcRetCode", retEnum.getCode());
resultMap.put("rpcRetMsg", retEnum.getMessage());
resultMap.put("dbErrorCode", dbErrorCode);
resultMap.put("dbErrorMsg", dbErrorMsg);
return resultMap;
}
public static String createBaseParam(Map<String, Object> paramMap) {
BaseParam baseParam = new BaseParam("102", "rpc-src-sys-vvlive-config-key", Constant.CF_BIZ_SEQUENCE_NO_PREFIX);
baseParam.setBizParamMap(paramMap);
return baseParam.toJson();
}
public static String mkRet(Map<String, Object> result) {
//_log.info("调用dal返回result={}", result);
if(result == null) return null;
String retCode = (String)result.get("rpcRetCode");
if("0000".equals(retCode)) {
if(result.get("bizResult") == null) return null;
return result.get("bizResult").toString();
}
return null;
}
public static Boolean isSuccess(Map<String, Object> result) {
if(result == null) return false;
String retCode = (String) result.get("rpcRetCode");
if("0000".equals(retCode) && result.get("bizResult") != null) return true;
return false;
}
}
package org.xxpay.common.util;
/**
* @author: dingzhiwei
* @date: 17/11/1
* @description:
*/
public class StrUtil {
public static String toString(Object obj) {
return obj == null?"":obj.toString();
}
public static String toString(Object obj, String nullStr) {
return obj == null?nullStr:obj.toString();
}
}
Supports Markdown
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