Commit 82db2ec2 authored by zhangc's avatar zhangc

commit

parent 31a32d6d
/**
* Copyright (c) 2011-2014 All Rights Reserved.
*/
package com.jz.dm.gateway.common.util;
/**
* @author Admin
* @version $Id: Constants.java 2014年9月3日 下午9:03:44 $
*/
public class Constants {
/**
* 默认时间格式
**/
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMAT = "yyyyMMdd";
/**
* 密码的正则表达式
*/
public static final String PASSWORD_EXG = "^(?![^a-zA-Z]+$)(?!\\D+$).{8,30}$";
/**
* UTF-8字符集
**/
public static final String CHARSET_UTF8 = "UTF-8";
/**
* Date默认时区
**/
public static final String DATE_TIMEZONE = "GMT+8";
public static final String PRINCIPAL_NAME_ATTRIBUTE_OMSNAME = ".OMS_PRINCIPAL_NAME_ATTRIBUTE_NAME";
public static final String PRINCIPAL_NAME_ATTRIBUTE_MCHNAME = ".MCH_PRINCIPAL_NAME_ATTRIBUTE_NAME";
public static final String PRINCIPAL_NAME_ATTRIBUTE_PROXYNAME = ".PROXY_PRINCIPAL_NAME_ATTRIBUTE_NAME";
public static final String PRINCIPAL_NAME_ATTRIBUTE_SUPNAME = ".SUPPLIER_PRINCIPAL_NAME_ATTRIBUTE_NAME";
public static final String PERMISSIONS = "permissions";
/**
* 登录成功后,继续跳转URL
*/
public static final String GOTO_KEY = "to";
/**
* 记录密码控件的密钥key
*/
public final static String TOKEN = "token_%s";
// http请求头UA参数
public static final String UA = "user-agent";
//缓存名称
public static final String MEMBER_CACHE_NAME = "data:members";
public static final String MERCHANT_CACHE_NAME = "data:merchants";
public static final String SECRET_CACHE_NAME = "data:secret_keys";
public static final String ADDR_CACHE_NAME = "data:addrs";
public static final String PRODUCT_CACHE_NAME = "data:products";
public static final String API_WHITE_CACHE_NAME = "data:apiwhite";
//数据库序列名称
public static final String SEQ_ACCOUNT = "ids:accounts";
public static final String SEQ_ACCOUNT_WATER = "ids:accounts:water";
//public static final String SEQ_MEMBER = "ids:members";
public static final String SEQ_RECHARGE = "ids:recharges:loop:7";
public static final String SEQ_TRADE_ORDER = "ids:tradeorders:loop:7";
public static final String SEQ_PAYMENT = "ids:payment:loop:7";
public static final String SEQ_WITHDRAW = "ids:withdraws:loop:7";
public static final String SEQ_TRANSFER = "ids:transfer:loop:7";
/**
* key = 产线名:服务名:用途:数据类型:key
*/
public static final String VALID_CODE_KEY_PREFIX = "data:merchants:valid:string:";
public static final String VALID_CODE_KEY_COUNT_PREFIX = "data:merchants:valid:long:";
/** 短信签约缓存名称 **/
public static final String SMS_SIGN_KEY_PREFIX = "data:smssign:shortcode:string:";
public static final String SMS_SIGN_VALID_CODE_PREFIX = "data:smssign:validcode:string:";
public static final String SMS_SIGN_VALID_CODE_LIMIT_PREFIX = "data:smssign:validlimit:string:";
public static final String SMS_BROKER_VALID_CODE_PREFIX = "data:smsbroker:valid:string:";
/**
* 发送短信验证
*/
public static final String SEND_PAY_VALID_CODE = "sendPayValidCode";
public static final String SEND_EDIT_PASSWORD_VALID_CODE = "sendPasswordValidCode";
public static final String SEND_SIGN_VALID_CODE = "sendSignValidCode";
public static final String SMS_BROKER_VALID_CODE_TEMPLATE = "sendBrokerValidCode";
/**
* 代理商分润汇总key
*/
public static final String PROXY_ALL_FEE_SUMMARY = "PROXY_ALL_FEE_SUMMARY";
public static final String PROXYER_Fee = "PROXYER_Fee";
public static final String MERCHANT_Fee = "MERCHANT_Fee";
}
package com.jz.dm.gateway.common.util;
import java.util.HashMap;
import java.util.Map;
/**
* HDD HashMap
*
*/
public class HddHashMap extends HashMap<String, String> {
private static final long serialVersionUID = -3440305725602261736L;
public HddHashMap() {
super();
}
public HddHashMap(Map<? extends String, ? extends String> map) {
super(map);
}
/**
* if key or value is null, not put into hash map
*
* @see HashMap#put(Object, Object)
*/
@Override
public String put(String key, String value) {
if (StringUtil.isNotEmpty(key, value)) {
return super.put(key, value);
} else {
return null;
}
}
}
package com.jz.dm.gateway.common.util;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.CharacterIterator;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.*;
public class JSONWriter {
private StringBuffer buf = new StringBuffer();
private Stack<Object> calls = new Stack<Object>();
private boolean emitClassName = true;
private DateFormat format;
public JSONWriter(boolean emitClassName) {
this.emitClassName = emitClassName;
}
public JSONWriter() {
this(false);
}
public JSONWriter(DateFormat format) {
this(false);
this.format = format;
}
public String write(Object object) {
buf.setLength(0);
value(object);
return buf.toString();
}
public String write(long n) {
return String.valueOf(n);
}
public String write(double d) {
return String.valueOf(d);
}
public String write(char c) {
return "\"" + c + "\"";
}
public String write(boolean b) {
return String.valueOf(b);
}
private void value(Object object) {
if (object == null || cyclic(object)) {
add(null);
} else {
calls.push(object);
if (object instanceof Class<?>) string(object);
else if (object instanceof Boolean) bool(((Boolean) object).booleanValue());
else if (object instanceof Number) add(object);
else if (object instanceof String) string(object);
else if (object instanceof Character) string(object);
else if (object instanceof Map<?, ?>) map((Map<?, ?>)object);
else if (object.getClass().isArray()) array(object);
else if (object instanceof Iterator<?>) array((Iterator<?>)object);
else if (object instanceof Collection<?>) array(((Collection<?>)object).iterator());
else if (object instanceof Date) date((Date)object);
else bean(object);
calls.pop();
}
}
private boolean cyclic(Object object) {
Iterator<Object> it = calls.iterator();
while (it.hasNext()) {
Object called = it.next();
if (object == called) return true;
}
return false;
}
private void bean(Object object) {
add("{");
BeanInfo info;
boolean addedSomething = false;
try {
info = Introspector.getBeanInfo(object.getClass());
PropertyDescriptor[] props = info.getPropertyDescriptors();
for (int i = 0; i < props.length; ++i) {
PropertyDescriptor prop = props[i];
String name = prop.getName();
Method accessor = prop.getReadMethod();
if ((emitClassName || !"class".equals(name)) && accessor != null) {
if (!accessor.isAccessible()) accessor.setAccessible(true);
Object value = accessor.invoke(object, (Object[])null);
if (value == null) continue;
if (addedSomething) add(',');
add(name, value);
addedSomething = true;
}
}
} catch (IllegalAccessException iae) {
} catch (InvocationTargetException ite) {
} catch (IntrospectionException ie) {
}
add("}");
}
private void add(String name, Object value) {
add('"');
add(name);
add("\":");
value(value);
}
private void map(Map<?, ?> map) {
add("{");
Iterator<?> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<?, ?> e = (Map.Entry<?, ?>) it.next();
value(e.getKey());
add(":");
value(e.getValue());
if (it.hasNext()) add(',');
}
add("}");
}
private void array(Iterator<?> it) {
add("[");
while (it.hasNext()) {
value(it.next());
if (it.hasNext()) add(",");
}
add("]");
}
private void array(Object object) {
add("[");
int length = Array.getLength(object);
for (int i = 0; i < length; ++i) {
value(Array.get(object, i));
if (i < length - 1) add(',');
}
add("]");
}
private void bool(boolean b) {
add(b ? "true" : "false");
}
private void date(Date date) {
if (this.format == null) {
this.format = new SimpleDateFormat(Constants.DATE_TIME_FORMAT);
this.format.setTimeZone(TimeZone.getTimeZone(Constants.DATE_TIMEZONE));
}
add("\"");
add(format.format(date));
add("\"");
}
private void string(Object obj) {
add('"');
CharacterIterator it = new StringCharacterIterator(obj.toString());
for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
if (c == '"') add("\\\"");
else if (c == '\\') add("\\\\");
else if (c == '/') add("\\/");
else if (c == '\b') add("\\b");
else if (c == '\f') add("\\f");
else if (c == '\n') add("\\n");
else if (c == '\r') add("\\r");
else if (c == '\t') add("\\t");
else if (Character.isISOControl(c)) {
unicode(c);
} else {
add(c);
}
}
add('"');
}
private void add(Object obj) {
buf.append(obj);
}
private void add(char c) {
buf.append(c);
}
static char[] hex = "0123456789ABCDEF".toCharArray();
private void unicode(char c) {
add("\\u");
int n = c;
for (int i = 0; i < 4; ++i) {
int digit = (n & 0xf000) >> 12;
add(hex[digit]);
n <<= 4;
}
}
}
package com.jz.dm.gateway.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.NameFilter;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Json工具类
*/
public class JsonUtil {
private static final ParserConfig PARSER_CONFIG = new ParserConfig();
static {
PARSER_CONFIG.propertyNamingStrategy = PropertyNamingStrategy.CamelCase;
}
private static final Map<PropertyNamingStrategy, NameFilter> NAME_FILTERS = new HashMap<PropertyNamingStrategy, NameFilter>();
static {
NAME_FILTERS.put(PropertyNamingStrategy.SnakeCase, new SnakeNameFilter());
NAME_FILTERS.put(PropertyNamingStrategy.CamelCase, new CamelNameFilter());
NAME_FILTERS.put(PropertyNamingStrategy.PascalCase, new PascalNameFilter());
NAME_FILTERS.put(PropertyNamingStrategy.KebabCase, new KebabNameFilter());
}
public static class SnakeNameFilter implements NameFilter {
/**
* @see NameFilter#process(Object, String, Object)
*/
@Override
public String process(Object object, String name, Object value) {
return PropertyNamingStrategy.SnakeCase.translate(name);
}
}
public static class CamelNameFilter implements NameFilter {
/**
* @see NameFilter#process(Object, String, Object)
*/
@Override
public String process(Object object, String name, Object value) {
return PropertyNamingStrategy.CamelCase.translate(name);
}
}
public static class PascalNameFilter implements NameFilter {
/**
* @see NameFilter#process(Object, String, Object)
*/
@Override
public String process(Object object, String name, Object value) {
return PropertyNamingStrategy.PascalCase.translate(name);
}
}
public static class KebabNameFilter implements NameFilter {
/**
* @see NameFilter#process(Object, String, Object)
*/
@Override
public String process(Object object, String name, Object value) {
return PropertyNamingStrategy.KebabCase.translate(name);
}
}
/**
* object serialize to string
*
* @param object
* @param strategy
* @return
*/
public static String toJSONString(Object object, PropertyNamingStrategy strategy) {
if (object == null) {
return null;
}
if (strategy == null) {
return JSON.toJSONString(object);
}
NameFilter nameFilter = NAME_FILTERS.get(strategy);
if (nameFilter == null) {
return JSON.toJSONString(object);
} else {
return JSON.toJSONString(object, nameFilter);
}
}
/**
* String转换为JSONObject对象
*
* @param data
* @return
*/
public static JSONObject stringToJsonObject(String data) {
if (StringUtils.isNotEmpty(data)) {
return JSONObject.parseObject(data);
}
return null;
}
}
package com.jz.dm.gateway.common.util;
import org.slf4j.Logger;
/**
* 日志打印工具
*
*/
public class LogUtil {
/** 摘要日志的内容分隔符 */
public static final String SEP = ",";
/** 修饰符 */
private static final char RIGHT_TAG = ']';
/** 修饰符 */
private static final char LEFT_TAG = '[';
/**
* 日志信息
*
*/
public interface LogInfo {
/**
* 获取日志信息
*
* @return 日志信息
*/
String getLogInfo();
}
/**
* 打印info日志。
*
* @param logger 日志对象
* @param objs 任意个要输出到日志的参数
*/
public static void info(Logger logger, Object... objs) {
if (logger.isInfoEnabled()) {
logger.info(getLogString(objs));
}
}
/**
* 打印info级别日志
*
* @param logger 日志对象
* @param logInfo 日志信息
*/
public static void info(Logger logger, LogInfo logInfo) {
if (logger.isInfoEnabled()) {
logger.info(logInfo.getLogInfo());
}
}
/**
* 打印info级别日志
*
* @param logger 日志对象
* @param e 异常信息
* @param objs 任意个要输出到日志的参数
*/
public static void info(Logger logger, Throwable e, Object... objs) {
if (logger.isInfoEnabled()) {
logger.info(getLogString(objs), e);
}
}
/**
* 打印warn级别日志
*
* @param logger 日志对象
* @param objs 任意个要输出到日志的参数
*/
public static void warn(Logger logger, Object... objs) {
logger.warn(getLogString(objs));
}
/**
* 打印warn级别日志
*
* @param logger 日志对象
* @param e 异常信息
* @param objs 任意个要输出到日志的参数
*/
public static void warn(Logger logger, Throwable e, Object... objs) {
logger.warn(getLogString(objs), e);
}
/**
* 打印error级别日志
*
* @param logger 日志对象
* @param e 异常信息
* @param objs 任意个要输出到日志的参数
*/
public static void error(Logger logger, Throwable e, Object... objs) {
logger.error(getLogString(objs), e);
}
/**
* 打印error级别日志
*
* @param logger 日志对象
* @param objs 任意个要输出到日志的参数
*/
public static void error(Logger logger, Object... objs) {
logger.error(getLogString(objs));
}
/**
* 打印debug日志。
*
* @param logger 日志对象
* @param objs 任意个要输出到日志的参数
*/
public static void debug(Logger logger, Object... objs) {
if (logger.isDebugEnabled()) {
logger.debug(getLogString(objs));
}
}
/**
* 打印debug日志。
*
* @param logger 日志对象
* @param e 异常信息
* @param objs 任意个要输出到日志的参数
*/
public static void debug(Logger logger, Throwable e, Object... objs) {
if (logger.isDebugEnabled()) {
logger.debug(getLogString(objs), e);
}
}
/**
* 生成输出到日志的字符串
*
* @param objs 任意个要输出到日志的参数
* @return 日志字符串
*/
public static String getLogString(Object... objs) {
StringBuilder log = new StringBuilder();
log.append(LEFT_TAG).append(getThreadId()).append(RIGHT_TAG);
for (Object o : objs) {
log.append(o).append(SEP);
}
return log.toString();
}
/**
* 获取线程id。
*
* @return 线程id
*/
public static String getThreadId() {
return String.valueOf(Thread.currentThread().getId());
}
}
package com.jz.dm.gateway.common.util;
import java.util.HashMap;
import java.util.Map;
/**
* 结果码
*
*/
public enum NotifyResultCode implements ResultCode {
/** 处理成功 */
SUCCESS("SUCCESS", "处理成功"),
/** 处理失败 */
FAILED("FAILED", "处理失败"),
/** 未知异常 */
UNKNOWN_EXCEPTION("UNKNOWN_EXCEPTION", "未知异常"),
/** 数据库异常 */
DATABASE_EXCEPTION("DATABASE_EXCEPTION", "数据库异常"),
/** IO异常 */
IO_EXCEPTION("IO_EXCEPTION", "IO异常"),
/** 参数不能为空 */
PARAM_CAN_NOT_NULL("PARAM_CAN_NOT_NULL", "参数不能为空"),
/** 参数不能为空 */
PARAM_CAN_NOT_EMPTY("PARAM_CAN_NOT_EMPTY", "参数不能为空"),
/** 重复发送 */
RETRANSMISSION("RETRANSMISSION", "重复发送"),
/** 无效参数 */
ILLEGAL_ARGUMENT("ILLEGAL_ARGUMENT", "无效参数"),
/** 时间格式不合法*/
ILLEGAL_DATE_FORMAT("ILLEGAL_DATE_FORMAT", "时间格式不合法"),
;
/**
* 初始化保存到map里方便根据code获取
*/
private static Map<String, NotifyResultCode> RESULT_CODES = new HashMap<String, NotifyResultCode>();
static {
for (NotifyResultCode resultCode : NotifyResultCode.values()) {
RESULT_CODES.put(resultCode.code, resultCode);
}
}
/** 结果码 */
private String code;
/** 结果码信息 */
private String msg;
/** 结果分类 */
private NotifyResultCode classification;
/**
* 构造函数
*
* @param code 结果码
* @param msg 结果码信息
*/
private NotifyResultCode(String code, String message) {
this(code, message, null);
}
/**
* 构造函数
*
* @param code 结果码
* @param msg 结果码信息
* @param classification 结果分组
*/
private NotifyResultCode(String code, String msg, NotifyResultCode classification) {
this.code = code;
this.msg = msg;
this.classification = classification;
}
/**
* 通过枚举<code>code</code>获得枚举
*
* @param code 结果码
* @return 枚举
*/
public static NotifyResultCode getResultCode(String code) {
return RESULT_CODES.get(code);
}
/**
* Getter method for property <tt>code</tt>.
*
* @return property value of code
*/
@Override
public String getCode() {
return code;
}
/**
* Setter method for property <tt>code</tt>.
*
* @param code value to be assigned to property code
*/
public void setCode(String code) {
this.code = code;
}
/**
* Getter method for property <tt>msg</tt>.
*
* @return property value of msg
*/
@Override
public String getMsg() {
return msg;
}
/**
* Setter method for property <tt>msg</tt>.
*
* @param msg value to be assigned to property msg
*/
public void setMsg(String msg) {
this.msg = msg;
}
/**
* Getter method for property <tt>classification</tt>.
*
* @return property value of classification
*/
public NotifyResultCode getClassification() {
return classification;
}
/**
* Setter method for property <tt>classification</tt>.
*
* @param classification value to be assigned to property classification
*/
public void setClassification(NotifyResultCode classification) {
this.classification = classification;
}
}
package com.jz.dm.gateway.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jz.dm.gateway.common.exception.OpenApiException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* openapi请求
*
*/
public class OpenApiRequest {
private String appId;
private String openApiParams;
private JSONObject parameters;
private Object parameterObject;
private Map<String, Object> extAttributes = new HashMap<String, Object>();
public OpenApiRequest(String openApiParams) {
setOpenApiParams(openApiParams);
}
private void setOpenApiParams(String openApiParams) {
this.openApiParams = openApiParams;
try {
parameters = JSON.parseObject(openApiParams, JSONObject.class);
} catch (Exception ex) {
throw new OpenApiException(OpenApiResultCode.ILLEGAL_ARGUMENT,
"parse openapi params error, openApiParams=" + openApiParams, ex);
}
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
@SuppressWarnings("unchecked")
public <T> T getObject(Class<?> clazz) {
if (parameterObject != null) {
return (T) parameterObject;
}
try {
this.parameterObject = JSON.parseObject(openApiParams, clazz);
} catch (Exception ex) {
throw new OpenApiException(OpenApiResultCode.ILLEGAL_ARGUMENT, ex);
}
return (T) parameterObject;
}
public String getOpenApiParams() {
return this.openApiParams;
}
@SuppressWarnings("unchecked")
@Deprecated
public <T> T getParameter(String key) {
return (T) parameters.get(key);
}
public <T> T getObject(String key, Class<T> clazz) {
return parameters.getObject(key, clazz);
}
public byte[] getBytes(String key) {
return parameters.getBytes(key);
}
public Boolean getBoolean(String key) {
return parameters.getBoolean(key);
}
public boolean getBooleanValue(String key) {
return parameters.getBooleanValue(key);
}
public Byte getByte(String key) {
return parameters.getByte(key);
}
public byte getByteValue(String key) {
return parameters.getByteValue(key);
}
public Short getShort(String key) {
return parameters.getShortValue(key);
}
public short getShortValue(String key) {
return parameters.getShortValue(key);
}
public Integer getInteger(String key) {
return parameters.getInteger(key);
}
public int getIntValue(String key) {
return parameters.getIntValue(key);
}
public Long getLong(String key) {
return parameters.getLong(key);
}
public long getLongValue(String key) {
return parameters.getLongValue(key);
}
public Float getFloat(String key) {
return parameters.getFloat(key);
}
public float getFloatValue(String key) {
return parameters.getFloatValue(key);
}
public Double getDouble(String key) {
return parameters.getDouble(key);
}
public double getDoubleValue(String key) {
return parameters.getDoubleValue(key);
}
public BigDecimal getBigDecimal(String key) {
return parameters.getBigDecimal(key);
}
public BigInteger getBigInteger(String key) {
return parameters.getBigInteger(key);
}
public String getString(String key) {
return parameters.getString(key);
}
public Date getDate(String key) {
return parameters.getDate(key);
}
/**
* Get Extend Attribute
*
* @param attributeName
* @return
*/
@SuppressWarnings("unchecked")
public <T> T getExtAttribute(String attributeName) {
return (T) extAttributes.get(attributeName);
}
/**
* Set Extend Attribute
*
* @param attributeName
* @param attributeValue
*/
public void setExtAttribute(String attributeName, String attributeValue) {
this.extAttributes.put(attributeName, attributeValue);
}
/**
* Getter method for property <tt>extAttributes</tt>.
*
* @return property value of extAttributes
*/
public Map<String, Object> getExtAttributes() {
return extAttributes;
}
/**
* Setter method for property <tt>extAttributes</tt>.
*
* @param extAttributes value to be assigned to property extAttributes
*/
public void setExtAttributes(Map<String, Object> extAttributes) {
this.extAttributes = extAttributes;
}
}
package com.jz.dm.gateway.common.util;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.HashMap;
import java.util.Map;
/**
* openapi响应
*
*/
public class OpenApiResponse {
/**
* 结果码
*/
private static final String ATTRIBUTE_NAME_CODE = "code";
/**
* 结果消息
*/
private static final String ATTRIBUTE_NAME_MSG = "msg";
/**
* 属性
*/
private final Map<String, Object> attributes = new HashMap<String, Object>();
/**
* 获取结果码
*
* @return
*/
public String getCode() {
return (String) attributes.get(ATTRIBUTE_NAME_CODE);
}
/**
* 设置结果码
*
* @param code
*/
public void setCode(String code) {
attributes.put(ATTRIBUTE_NAME_CODE, code);
}
/**
* 获取结果信息
*
* @return
*/
public String getMsg() {
return (String) attributes.get(ATTRIBUTE_NAME_MSG);
}
/**
* 设置结果信息
*
* @param msg
*/
public void setMsg(String msg) {
attributes.put(ATTRIBUTE_NAME_MSG, msg);
}
/**
* 获取属性
*
* @param attributeName
* @return
*/
@SuppressWarnings("unchecked")
public <T> T getAttribute(String attributeName) {
return (T) attributes.get(attributeName);
}
/**
* 设置属性
*
* @param attributeName
* @param attributeValue
*/
public void setAttribute(String attributeName, Object attributeValue) {
attributes.put(attributeName, attributeValue);
}
/**
* 设置对象属性
*
* @param object
*/
public void setAttribute(Object object) {
Object jsonObject = JSON.toJSON(object);
if (!(jsonObject instanceof JSONObject)) {
throw new IllegalArgumentException("object must be a javabean.");
}
attributes.putAll((JSONObject) jsonObject);
}
/**
* 获取所有属性
*
* @return
*/
public Map<String, Object> getAttributes() {
return attributes;
}
}
package com.jz.dm.gateway.common.util;
import java.util.HashMap;
import java.util.Map;
/**
* 结果码
*
*/
public enum OpenApiResultCode implements ResultCode {
/** 处理成功 */
SUCCESS("SUCCESS", "处理成功"),
/** 未知异常 */
UNKNOWN_EXCEPTION("UNKNOWN_EXCEPTION", "未知异常"),
/** 无效接口 */
ILLEGAL_INTERFACE("ILLEGAL_INTERFACE", "无效接口"),
/** 无效参数 */
ILLEGAL_ARGUMENT("ILLEGAL_ARGUMENT", "无效参数"),
/** 名类型不支持 */
SIGN_TYPE_NOT_SUPPORT("SIGN_TYPE_NOT_SUPPORT", "签名类型不支持"),
/** 数据签名错误 */
DATA_SIGN_ERROR("DATA_SIGN_ERROR", "数据签名错误"),
/** 公钥格式错误 */
PUBLIC_KEY_FORMAT_ERROR("PUBLIC_KEY_FORMAT_ERROR", "公钥格式错误"),
/** 私钥格式错误 */
PRIVATE_KEY_FORMAT_ERROR("PRIVATE_KEY_FORMAT_ERROR", "私钥格式错误"),
/** 响应数据格式错误 */
RESPONSE_DATA_FORMAT_ERROR("RESPONSE_DATA_FORMAT_ERROR", "响应数据格式错误"),
/** 签名校验错误 */
SIGN_VERIFY_ERROR("SIGN_VERIFY_ERROR", "签名校验错误"),
/** 不支持该信息摘要算法 */
NO_SUCH_MD_ALGORITHM("NO_SUCH_MD_ALGORITHM", "不支持该信息摘要算法"),
/** 信息摘要错误 */
MESSAGE_DIGEST_ERROR("MESSAGE_DIGEST_ERROR", "信息摘要错误"),
/** 数据加密错误 */
DATA_ENCRYPTION_ERROR("DATA_ENCRYPTION_ERROR", "数据加密错误"),;
/**
* 初始化保存到map里方便根据code获取
*/
private static Map<String, OpenApiResultCode> RESULT_CODES = new HashMap<String, OpenApiResultCode>();
static {
for (OpenApiResultCode openApiCode : OpenApiResultCode.values()) {
RESULT_CODES.put(openApiCode.code, openApiCode);
}
}
/** 结果码 */
private String code;
/** 结果码信息 */
private String msg;
/**
* 构造函数
*
* @param code 结果码
* @param msg 结果码信息
*/
private OpenApiResultCode(String code, String msg) {
this.code = code;
this.msg = msg;
}
/**
* 通过枚举<code>code</code>获得枚举
*
* @param code 结果码
* @return 枚举
*/
public static OpenApiResultCode getOpenApiResultCode(String code) {
return RESULT_CODES.get(code);
}
/**
* Getter method for property <tt>code</tt>.
*
* @return property value of code
*/
@Override
public String getCode() {
return code;
}
/**
* Setter method for property <tt>code</tt>.
*
* @param code value to be assigned to property code
*/
public void setCode(String code) {
this.code = code;
}
/**
* Getter method for property <tt>msg</tt>.
*
* @return property value of msg
*/
@Override
public String getMsg() {
return msg;
}
/**
* Setter method for property <tt>msg</tt>.
*
* @param msg value to be assigned to property msg
*/
public void setMsg(String msg) {
this.msg = msg;
}
}
package com.jz.dm.gateway.common.util;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class RSAUtils {
public static final String CHARSET = "UTF-8";
public static final String RSA_ALGORITHM = "RSA";
public static Map<String, String> createKeys(int keySize){
//为RSA算法创建一个KeyPairGenerator对象
KeyPairGenerator kpg;
try{
kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
}catch(NoSuchAlgorithmException e){
throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
}
//初始化KeyPairGenerator对象,密钥长度
kpg.initialize(keySize);
//生成密匙对
KeyPair keyPair = kpg.generateKeyPair();
//得到公钥
Key publicKey = keyPair.getPublic();
String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
//得到私钥
Key privateKey = keyPair.getPrivate();
System.out.println("私钥格式:"+privateKey.getFormat());
String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
Map<String, String> keyPairMap = new HashMap<String, String>();
keyPairMap.put("publicKey", publicKeyStr);
keyPairMap.put("privateKey", privateKeyStr);
return keyPairMap;
}
/**
* 得到公钥
* @param publicKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
//通过X509编码的Key指令获得公钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
return key;
}
/**
* 得到私钥
* @param privateKey 密钥字符串(经过base64编码)
* @throws Exception
*/
public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
//通过PKCS#8编码的Key指令获得私钥对象
KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
return key;
}
/**
* 公钥加密
* @param data
* @param publicKey
* @return
*/
public static String publicEncrypt(String data, RSAPublicKey publicKey){
try{
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
}catch(Exception e){
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 私钥解密
* @param data
* @param privateKey
* @return
*/
public static String privateDecrypt(String data, RSAPrivateKey privateKey){
try{
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
}catch(Exception e){
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 私钥加密
* @param data
* @param privateKey
* @return
*/
public static String privateEncrypt(String data, RSAPrivateKey privateKey){
try{
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
}catch(Exception e){
throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
}
}
/**
* 公钥解密
* @param data
* @param publicKey
* @return
*/
public static String publicDecrypt(String data, RSAPublicKey publicKey){
try{
Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
}catch(Exception e){
throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
}
}
private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){
int maxBlock = 0;
if(opmode == Cipher.DECRYPT_MODE){
maxBlock = keySize / 8;
}else{
maxBlock = keySize / 8 - 11;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] buff;
int i = 0;
try{
while(datas.length > offSet){
if(datas.length-offSet > maxBlock){
buff = cipher.doFinal(datas, offSet, maxBlock);
}else{
buff = cipher.doFinal(datas, offSet, datas.length-offSet);
}
out.write(buff, 0, buff.length);
i++;
offSet = i * maxBlock;
}
}catch(Exception e){
throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
}
byte[] resultDatas = out.toByteArray();
IOUtils.closeQuietly(out);
return resultDatas;
}
}
package com.jz.dm.gateway.common.util;
/**
* 结果码
*
*/
public interface ResultCode {
/**
* 编码
*
* @return
*/
public String getCode();
/**
* 信息
*
* @return
*/
public String getMsg();
}
package com.jz.dm.gateway.common.util;
/**
* 签名类型
*
*/
public enum SignType {
RSA, RSA2, MD5
}
package com.jz.dm.gateway.common.util;
import java.io.*;
/**
* 流处理工具
*
*/
public class StreamUtil {
private static final int DEFAULT_BUFFER_SIZE = 8192;
public static void io(InputStream in, OutputStream out) throws IOException {
io(in, out, -1);
}
public static void io(InputStream in, OutputStream out, int bufferSize) throws IOException {
if (bufferSize == -1) {
bufferSize = DEFAULT_BUFFER_SIZE;
}
byte[] buffer = new byte[bufferSize];
int amount;
while ((amount = in.read(buffer)) >= 0) {
out.write(buffer, 0, amount);
}
}
public static void io(Reader in, Writer out) throws IOException {
io(in, out, -1);
}
public static void io(Reader in, Writer out, int bufferSize) throws IOException {
if (bufferSize == -1) {
bufferSize = DEFAULT_BUFFER_SIZE >> 1;
}
char[] buffer = new char[bufferSize];
int amount;
while ((amount = in.read(buffer)) >= 0) {
out.write(buffer, 0, amount);
}
}
public static OutputStream synchronizedOutputStream(OutputStream out) {
return new SynchronizedOutputStream(out);
}
public static OutputStream synchronizedOutputStream(OutputStream out, Object lock) {
return new SynchronizedOutputStream(out, lock);
}
public static String readText(InputStream in) throws IOException {
return readText(in, null, -1);
}
public static String readText(InputStream in, String encoding) throws IOException {
return readText(in, encoding, -1);
}
public static String readText(InputStream in, String encoding,
int bufferSize) throws IOException {
Reader reader = (encoding == null) ? new InputStreamReader(in)
: new InputStreamReader(in, encoding);
return readText(reader, bufferSize);
}
public static String readText(Reader reader) throws IOException {
return readText(reader, -1);
}
public static String readText(Reader reader, int bufferSize) throws IOException {
StringWriter writer = new StringWriter();
io(reader, writer, bufferSize);
return writer.toString();
}
private static class SynchronizedOutputStream extends OutputStream {
private OutputStream out;
private Object lock;
SynchronizedOutputStream(OutputStream out) {
this(out, out);
}
SynchronizedOutputStream(OutputStream out, Object lock) {
this.out = out;
this.lock = lock;
}
public void write(int datum) throws IOException {
synchronized (lock) {
out.write(datum);
}
}
public void write(byte[] data) throws IOException {
synchronized (lock) {
out.write(data);
}
}
public void write(byte[] data, int offset, int length) throws IOException {
synchronized (lock) {
out.write(data, offset, length);
}
}
public void flush() throws IOException {
synchronized (lock) {
out.flush();
}
}
public void close() throws IOException {
synchronized (lock) {
out.close();
}
}
}
}
package com.jz.dm.gateway.common.util;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
/**
*
* @author Admin
*/
public final class TtpayUtils {
/**
* 除去数组中的空值和签名参数
* 为了兼容健康商城签名问题,过滤sign2参数
* @param sArray 签名参数组
* @return 去掉空值与签名参数后的新签名参数组
*/
public static Map<String, String> filter(Map<String, String> sArray) {
Map<String, String> result = new HashMap<String, String>();
if (sArray == null || sArray.size() <= 0) {
return result;
}
for (String key : sArray.keySet()) {
String value = sArray.get(key);
if (StringUtils.isEmpty(value) || key.equalsIgnoreCase("sign")) {
continue;
}
result.put(key, value);
}
return result;
}
/**
* 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
* @param params 需要排序并参与字符拼接的参数组
* @return 拼接后字符串
*/
public static String createLinkString(Map<String, String> params) {
// 第一步:把字典按Key的字母顺序排序,参数使用TreeMap已经完成排序
List<String> keys = new ArrayList<String>(params.keySet());
Collections.sort(keys);
// 第二步:把所有参数名和参数值串在一起
StringBuilder sb = new StringBuilder();
for (String key : keys) {
String value = params.get(key);
if (!StringUtils.isEmpty(value)) {
sb.append(key).append("=").append(value);
}
}
return sb.toString();
}
/**
* 方法说明:根据运单号返回还有校验位
*
* @param no
* @return
*/
public static String createId(String mobile, int length) {
int count = 0;
String no = mobile.substring(0, length);//计算前6位校验码
int len = no.length();
for (int i=0;i<len;i++) {
int p = (no.charAt(len - i -1)) * (i * 2 + 1);
int q = divide(p, 10);
int r = p - q * 10;
count += (q + r);
}
return ((divide(count, 10) + 1) * 10 - count) % 10 + mobile.substring(mobile.length() - length + 1);
}
public static int divide(int x, int y) {
if (y == 0) {
return 0;
}
BigDecimal bigX = new BigDecimal(x);
BigDecimal bigY = new BigDecimal(y);
return bigX.divide(bigY, 0, RoundingMode.HALF_UP).intValue();
}
public static void main(String[] args) {
System.out.println(TtpayUtils.createId("15000000013", 7));
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jz.dm.gateway.mapper.DataGoodsApiDao">
<resultMap type="com.jz.common.entity.DataGoodsApi" id="TDataGoodsApiMap">
<result property="goodsApi" column="goods_api" jdbcType="INTEGER"/>
<result property="dataGoodsId" column="data_goods_id" jdbcType="INTEGER"/>
<result property="apiName" column="api_name" jdbcType="VARCHAR"/>
<result property="requestType" column="request_type" jdbcType="VARCHAR"/>
<result property="apiUrl" column="api_url" jdbcType="VARCHAR"/>
<result property="apiMethod" column="api_method" jdbcType="VARCHAR"/>
<result property="apiProtocl" column="api_protocl" jdbcType="VARCHAR"/>
<result property="returnDataExample" column="return_data_example" jdbcType="VARCHAR"/>
<result property="requestExample" column="request_example" jdbcType="VARCHAR"/>
<result property="returnType" column="return_type" jdbcType="VARCHAR"/>
<result property="apiKey" column="api_key" jdbcType="VARCHAR"/>
<result property="creTime" column="cre_time" jdbcType="TIMESTAMP"/>
<result property="crePerson" column="cre_person" jdbcType="VARCHAR"/>
<result property="uptPerson" column="upt_person" jdbcType="VARCHAR"/>
<result property="uptTime" column="upt_time" jdbcType="TIMESTAMP"/>
<result property="delFlag" column="del_flag" jdbcType="VARCHAR"/>
</resultMap>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jz.dm.gateway.mapper.DataGoodsApiParamsDao">
<resultMap type="com.jz.common.entity.DataGoodsApiParams" id="TDataGoodsApiParamsMap">
<result property="apiParamsId" column="api_params_id" jdbcType="INTEGER"/>
<result property="goodsApi" column="goods_api" jdbcType="INTEGER"/>
<result property="paramsDiff" column="params_diff" jdbcType="VARCHAR"/>
<result property="paramsName" column="params_name" jdbcType="VARCHAR"/>
<result property="paramsType" column="params_type" jdbcType="VARCHAR"/>
<result property="paramsDesc" column="params_desc" jdbcType="VARCHAR"/>
<result property="defaultValue" column="default_value" jdbcType="VARCHAR"/>
<result property="remark" column="remark" jdbcType="VARCHAR"/>
<result property="ifRequird" column="if_requird" jdbcType="VARCHAR"/>
<result property="delFlag" column="del_flag" jdbcType="VARCHAR"/>
<result property="creTime" column="cre_time" jdbcType="TIMESTAMP"/>
<result property="uptTime" column="upt_time" jdbcType="TIMESTAMP"/>
</resultMap>
</mapper>
\ No newline at end of file
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