标签:
package com.scd.core;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.security.Key;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.scd.response.ImageResponse;
public class BaseUnit {
private static String secretKey = "songcaidai@ver1001#$2015";
private final static String iv = "01234567";
private final static String encoding = "utf-8";
/**
* 将jsonStr中的值写入到对象成员字段中
* */
public static void toObject(Object object, String jsonStr) {
JSONObject dataJson = JSON.parseObject(jsonStr);
JSONArray data = (JSONArray) dataJson.get("data");
for (int i = 0; i < data.size(); i++) {
JSONObject item = (JSONObject) data.get(i);
for (java.util.Map.Entry<String, Object> entry : item.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
@SuppressWarnings("rawtypes")
Class c = object.getClass();
try {
Field field = c.getDeclaredField(fieldName);
field.setAccessible(true);
switch (field.getGenericType().toString()) {
case "class java.lang.Integer":
Integer intvalue = Integer.parseInt(fieldValue
.toString());
field.set(object, intvalue);
break;
case "class java.lang.Double":
Double dubvalue = Double.parseDouble(fieldValue
.toString());
field.set(object, dubvalue);
break;
default:
field.set(object, fieldValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* isDecode 是否需要解密
* */
public static void toObject(Object object, String jsonStr, boolean isDecode) {
String val = jsonStr;
if (isDecode)
val = decode(val);
toObject(object, val);
}
public static String toJsonString(Object object) {
String ret = JSON.toJSONString(object);
return ret;
}
/**
* isEncode 是否需要加密
* */
public static String toJsonString(Object object, boolean isEncode) {
String ret = toJsonString(object);
if (isEncode)
ret = encode(ret);
return ret;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List toList(Class classType, String jsonStr) {
List list = new ArrayList();
JSONObject dataJson = JSON.parseObject(jsonStr);
JSONArray data = (JSONArray) dataJson.get("data");
for (int i = 0; i < data.size(); i++) {
Object object = null;
try {
object = classType.newInstance();
} catch (Exception e1) {
e1.printStackTrace();
return null;
}
JSONObject item = (JSONObject) data.get(i);
for (java.util.Map.Entry<String, Object> entry : item.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
Class c = object.getClass();
try {
Field field = c.getDeclaredField(fieldName);
field.setAccessible(true);
switch (field.getGenericType().toString()) {
case "class java.lang.Integer":
Integer intvalue = Integer.parseInt(fieldValue
.toString());
field.set(object, intvalue);
break;
case "class java.lang.Double":
Double dubvalue = Double.parseDouble(fieldValue
.toString());
field.set(object, dubvalue);
break;
default:
field.set(object, fieldValue);
}
} catch (Exception e) {
e.printStackTrace();
}
}
list.add(object);
}
return list;
}
/**
* 对请求数据做md5验证
* */
public static boolean MD5Check(String jsonStr) {
boolean res = true;
JSONObject dataJson = JSON.parseObject(jsonStr);
JSONArray data = (JSONArray) dataJson.get("data");
String mdCode = dataJson.getString("md5code");
HashMap<String, String> dataMap = new HashMap<String, String>();
for (int i = 0; i < data.size(); i++) {
JSONObject item = (JSONObject) data.get(i);
for (java.util.Map.Entry<String, Object> entry : item.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
dataMap.put(fieldName, fieldValue.toString());
}
}
List<Map.Entry<String, String>> dataSorted = hashMapSort(dataMap);
StringBuilder allValue = new StringBuilder();
for (Map.Entry<String, String> item : dataSorted) {
allValue.append(item.getValue());
}
res = mdCode.equals(buildMD5Code(allValue.toString() + "songcaidaipc"))
|| mdCode.equals(buildMD5Code(allValue.toString()
+ "songcaidaiadd"))
|| mdCode.equals(buildMD5Code(allValue.toString()
+ "songcaidaiios"))
|| mdCode.equals(buildMD5Code(allValue.toString()
+ "songcaidaiwap"));
return res;
}
/**
* hashmap排序
* */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List<Map.Entry<String, String>> hashMapSort(HashMap hashMap) {
List<Map.Entry<String, String>> resultList = new ArrayList<Map.Entry<String, String>>(
hashMap.entrySet());
Collections.sort(resultList,
new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Entry<String, String> o1,
Entry<String, String> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
return resultList;
}
/**
* MD5编码
* */
public static String buildMD5Code(String source) {
char hexDigits[] = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘,
‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘ };
try {
byte[] btInput = source.getBytes("utf-8");
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 随机产生6位验证码
*
* @return
* @author 杨旭
*/
public static String createRandomVcode() {
String vcode = "";
for (int i = 0; i < 6; i++) {
vcode = vcode + (int) (Math.random() * 9);
}
return vcode;
}
/**
* 获取远程IP
*
* @param request
* @return
* @author 杨旭
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* 对象序列化
* */
public static byte[] serialize(Object object) {
ObjectOutputStream objectStream = null;
ByteArrayOutputStream byteStream = null;
try {
byteStream = new ByteArrayOutputStream();
objectStream = new ObjectOutputStream(byteStream);
objectStream.writeObject(object);
byte[] bytes = byteStream.toByteArray();
return bytes;
} catch (Exception e) {
return null;
}
}
/**
* 反序列化
* */
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream byteStream = null;
try {
byteStream = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(byteStream);
return ois.readObject();
} catch (Exception e) {
return null;
}
}
/**
* 对身份证简单校验
*
* @return author:李细军
*/
public static boolean CheckIdentityNo(String idno) {
String reg = "^[1-9]([0-9]{14}|([0-9]{16}[0-9Xx]))$";
if (idno.matches(reg)) {
if (idno.length() == 18) {
Integer Year = Integer.parseInt(idno.substring(6, 10));// 年份
Integer Month = Integer.parseInt(idno.substring(10, 12));// 月份
Integer Day = Integer.parseInt(idno.substring(12, 14));// 日子
if ((1900 < Year && Year < 2020) && (0 < Month && Month < 13)
&& (0 < Day && Day < 32)) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
/**
* 贝付接口用 排序 Luocx 2015-8-28 08:45:45
*
* @return
* @throws Exception
*/
public static String makeUrl(HashMap<String, String> hm, String securityCode)
throws Exception {
List<String> keys = new ArrayList<String>(hm.keySet());
Collections.sort(keys);// 要求参数必须按字母排序
StringBuffer content = new StringBuffer();
for (int i = 0; i < keys.size(); i++) {
content.append((String) keys.get(i));
content.append("=");
content.append((String) hm.get((String) keys.get(i)));
if (i != keys.size() - 1) {
content.append("&");
}
}
System.out.println("加签排序后的参数为:" + content);
// 添加签名密钥
content.append(securityCode);
System.out.println("待 签 名 数 据 为:" + content);
return content.toString();
}
/**
* 贝付接口用 hashmap转json Luocx 2015-8-28 08:45:45
*
* @param map
* @return
*/
public static String hashMapToJson(HashMap<String, String> map) {
String string = "{";
for (Iterator<?> it = map.entrySet().iterator(); it.hasNext();) {
Entry<?, ?> e = (Entry<?, ?>) it.next();
string += "\"" + e.getKey() + "\":";
string += "\"" + e.getValue() + "\",";
}
string = string.substring(0, string.lastIndexOf(","));
string += "}";
return string;
}
/**
* 生成订单号
*
* @return
*/
public static String no() {
String code = "10"
+ new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
+ "01";
return code;
}
/**
* des加密
* */
public static String encode(String text) {
String ret = "";
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory
.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] encryptData;
encryptData = cipher.doFinal(text.getBytes(encoding));
ret = com.scd.core.Base64.encode(encryptData);
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
/**
* des解密
* */
public static String decode(String text) {
System.out.println("接收的req---->" + text);
// String secretKey = "songcaidai@ver1001#$2015";
String ret = "";
try {
Key deskey = null;
DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
SecretKeyFactory keyfactory = SecretKeyFactory
.getInstance("desede");
deskey = keyfactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] decryptData = cipher.doFinal(com.scd.core.Base64
.decode(text));
ret = new String(decryptData, encoding);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("解密后的req===>" + ret);
return ret;
}
/**
* 验证是否是手机号
*
* @param mobiles
* @return
*/
public static boolean isMobileNO(String mobiles) {
// Pattern p = Pattern.compile("^(1[3|4|5|7|8][0-9])\\d{4,8}$");
Pattern p = Pattern.compile("^((13)|(14)|(15)|(17)|(18))\\d{9}$");
Matcher m = p.matcher(mobiles);
return m.matches();
}
public static List<ImageResponse> getUrlList(String source) {
List<ImageResponse> urlList = new ArrayList<ImageResponse>();
String str = source;
String shortKey = "img";
int index = str.indexOf(shortKey);
while (index > 0) {
str = str.substring(index + shortKey.length() + 8, str.length());
index = str.indexOf("\"");
// String url = str.substring(0,index);
ImageResponse ir = new ImageResponse();
if (str.indexOf(".") == 0)
ir.setImageurl(Contant.RISKSECURITY_ING_URL
+ str.substring(1, index));
else
ir.setImageurl(Contant.RISKSECURITY_ING_URL
+ str.substring(0, index));
urlList.add(ir);
str = str.substring(index, str.length());
index = str.indexOf(shortKey);
}
return urlList;
}
public static List<ImageResponse> getContentList(String content) {
List<ImageResponse> urlList = new ArrayList<ImageResponse>();
String str = content;
String shortKey = "src=\"";
int index = str.indexOf(shortKey);
while (index > 0) {
str = str.substring(index + shortKey.length(), str.length());
index = str.indexOf("\"");
// String url = str.substring(0,index);
ImageResponse ir = new ImageResponse();
if (str.indexOf(".") == 0)
ir.setImageurl( str.substring(1, index));
else
ir.setImageurl(str.substring(0, index));
urlList.add(ir);
str = str.substring(index, str.length());
index = str.indexOf(shortKey);
}
return urlList;
}
/**
* 去掉html标记
*
* @param html
* @return
*/
public static String getHtmlText(String html) {
String resultStr = "";
String regex = "<.+?>|\\t|\\n|\\r| ";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(html);
StringBuffer stringBuffer = new StringBuffer();
boolean result = matcher.find();
if (!result) {
resultStr = html;
} else {
while (result) {
matcher.appendReplacement(stringBuffer, "");
result = matcher.find();
}
resultStr = stringBuffer.toString();
}
System.out.println(resultStr);
return resultStr;
}
/**
* 检验用户密码是否合法
*
* @param pwd
* @return
*/
public static String checkPassword(String password) {
String str = password.replace(" ", "");
String result = "";
Pattern p = Pattern.compile("[0-9A-Za-z@!#$%&*+-=]{6,16}");
Matcher m = p.matcher(str);
if (m.matches()) {
if (str.length() < 6 && str.length() > 16) {
result = "";
} else {
result = BaseUnit.buildMD5Code(str);
}
} else {
result = "";
}
return result;
}
}
标签:
原文地址:http://www.cnblogs.com/yangxu6069/p/4844139.html