@@ -0,0 +1,188 @@ | |||
package com.inet.ailink.receiver.controller; | |||
import com.inet.ailink.receiver.common.enums.StatusCode; | |||
import com.inet.ailink.receiver.common.exception.BizException; | |||
import com.inet.ailink.receiver.common.utils.Base64TeaUitls; | |||
import com.inet.ailink.receiver.common.utils.JsonUtils; | |||
import com.inet.ailink.receiver.common.vo.Response; | |||
import com.inet.ailink.receiver.service.impl.SysAccoountServiceImpl; | |||
import org.slf4j.Logger; | |||
import org.slf4j.LoggerFactory; | |||
import org.springframework.beans.factory.annotation.Autowired; | |||
import org.springframework.validation.BindingResult; | |||
import org.springframework.validation.FieldError; | |||
import javax.servlet.http.HttpServletRequest; | |||
import javax.servlet.http.HttpServletResponse; | |||
import java.io.IOException; | |||
import java.io.PrintWriter; | |||
import java.util.HashMap; | |||
import java.util.List; | |||
import java.util.Map; | |||
//import com.google.common.primitives.Bytes; | |||
public abstract class BaseController extends java.beans.PropertyEditorSupport | |||
{ | |||
/** | |||
* 子类可以用这个Logger Log4J Logger for this class | |||
*/ | |||
protected final Logger log = LoggerFactory.getLogger(getClass()); | |||
//系统统一的提示没有权限访问的界面 | |||
protected static final String noRight_page="noRight"; | |||
public final static String KEY_USER = "user"; | |||
@Autowired | |||
private SysAccoountServiceImpl sysAccoountServiceImpl; | |||
/** | |||
* 写回加密数据 | |||
* @param response | |||
* @param result | |||
* @throws IOException | |||
*/ | |||
public void writeOutResponse(HttpServletResponse response, Response<Object> result) throws IOException{ | |||
response.setHeader("Access-Control-Allow-Origin",""); | |||
response.setHeader("Access-Control-Allow-Credentials",""); | |||
response.setHeader("Access-Control-Allow-Methods",""); | |||
response.setHeader("Access-Control-Max-Age",""); | |||
response.setHeader("Access-Control-Allow-Headers",""); | |||
response.setHeader("X-Application-Context",""); | |||
response.setHeader("Transfer-Encoding", ""); | |||
PrintWriter out = response.getWriter(); | |||
if(result.getData() != null){ | |||
String dataValue = result.getData().toString(); | |||
result.setData(Base64TeaUitls.encrypt(dataValue)); | |||
} | |||
String resultJson = JsonUtils.toJson(result); | |||
response.setHeader("ResponseBodySize", resultJson.length()+""); | |||
out.write(resultJson); | |||
out.flush(); | |||
out.close(); | |||
} | |||
/** | |||
* 写回正常数据 | |||
* @param response | |||
* @param result | |||
* @throws IOException | |||
*/ | |||
public void writeOutResponseNoEncrypt(HttpServletResponse response, Response<Object> result) throws IOException{ | |||
response.setHeader("Access-Control-Allow-Origin",""); | |||
response.setHeader("Access-Control-Allow-Credentials",""); | |||
response.setHeader("Access-Control-Allow-Methods",""); | |||
response.setHeader("Access-Control-Max-Age",""); | |||
response.setHeader("Access-Control-Allow-Headers",""); | |||
response.setHeader("X-Application-Context",""); | |||
// response.setHeader("Transfer-Encoding", "chunked"); | |||
//response.setBufferSize(result.toString().length()); | |||
String resultJson = JsonUtils.toJson(result); | |||
response.setHeader("ResponseBodySize", resultJson.length()+""); | |||
PrintWriter out = response.getWriter(); | |||
out.write(resultJson); | |||
out.flush(); | |||
out.close(); | |||
} | |||
/** | |||
* 写回任意原始数据 | |||
* @param response | |||
* @param result | |||
* @throws IOException | |||
*/ | |||
public void writeOutResponseOld(HttpServletResponse response, String result) throws IOException{ | |||
response.setHeader("Access-Control-Allow-Origin",""); | |||
response.setHeader("Access-Control-Allow-Credentials",""); | |||
response.setHeader("Access-Control-Allow-Methods",""); | |||
response.setHeader("Access-Control-Max-Age",""); | |||
response.setHeader("Access-Control-Allow-Headers",""); | |||
response.setHeader("X-Application-Context",""); | |||
response.setHeader("Transfer-Encoding", ""); | |||
response.setHeader("ResponseBodySize", result.length()+""); | |||
PrintWriter out = response.getWriter(); | |||
out.write(result); | |||
out.flush(); | |||
out.close(); | |||
} | |||
/** | |||
* 写回数据解析失败数据 | |||
* @param response | |||
* @param result | |||
* @throws IOException | |||
*/ | |||
public void writeOutResponse(HttpServletResponse response, byte[] paramsByte) throws IOException { | |||
Response<Object> result = new Response<Object>(); | |||
result.setStatus(paramsByte[0]+""); | |||
response.setHeader("Access-Control-Allow-Origin",""); | |||
response.setHeader("Access-Control-Allow-Credentials",""); | |||
response.setHeader("Access-Control-Allow-Methods",""); | |||
response.setHeader("Access-Control-Max-Age",""); | |||
response.setHeader("Access-Control-Allow-Headers",""); | |||
response.setHeader("X-Application-Context",""); | |||
response.setHeader("Transfer-Encoding", ""); | |||
String resultJson = JsonUtils.toJson(result); | |||
response.setHeader("ResponseBodySize", resultJson.length()+""); | |||
PrintWriter out = response.getWriter(); | |||
out.write(resultJson); | |||
out.flush(); | |||
out.close(); | |||
} | |||
/** | |||
* 校验参数是否为空 | |||
* @param response | |||
* @param params | |||
* @throws IOException | |||
*/ | |||
public void checkParams(HttpServletResponse response, String params) throws IOException{ | |||
Response<Object> result = new Response<Object>(); | |||
if(params == null || params.isEmpty() || params.equals("")){ | |||
result.setStatus(StatusCode.PARAM_EMPTY.getCode()); | |||
writeOutResponse(response, result); | |||
} | |||
} | |||
/** | |||
* 解密数据 | |||
* @param params | |||
* @return | |||
* @throws IOException | |||
*/ | |||
public byte[] decryptParams(HttpServletResponse response, String params) throws IOException{ | |||
//解密数据失败 | |||
byte[] paramsByte = new byte[]{}; | |||
//数据格式不正确 | |||
Map<String,String> paramsMap = new HashMap<String, String>(); | |||
try { | |||
paramsMap = JsonUtils.fromJson(params, Map.class); | |||
// System.out.println("decryptParams() paramsMap: " + paramsMap); | |||
} catch (Exception e) { | |||
paramsByte = new byte[]{(byte) Integer.parseInt(StatusCode.PARAMS_JSON_ERROR.getCode())}; | |||
// System.out.println("decryptParams() Exception: " + e); | |||
return paramsByte; | |||
} | |||
//关键参数字段获取失败 | |||
String paramsValue = paramsMap.get("params"); | |||
// System.out.println("decryptParams() paramsValue: " + paramsValue); | |||
if(paramsValue == null || paramsValue.equals("")){ | |||
paramsByte = new byte[]{(byte) Integer.parseInt(StatusCode.PARAMS_JSON_KEY_ERROR.getCode())}; | |||
return paramsByte; | |||
} | |||
try { | |||
paramsByte = Base64TeaUitls.decrypt(paramsValue); | |||
// System.out.println("decryptParams() paramsByte: " + paramsByte); | |||
} catch (Exception e) { | |||
paramsByte = new byte[]{(byte) Integer.parseInt(StatusCode.PARAMS_dECRYPT_ERROR.getCode())}; | |||
// System.out.println("decryptParams() paramsByte2: " + paramsByte); | |||
return paramsByte; | |||
} | |||
return paramsByte; | |||
} | |||
} | |||
@@ -0,0 +1,43 @@ | |||
package com.inet.ailink.receiver.controller; | |||
import com.inet.ailink.receiver.service.impl.BodyFatServiceImpl; | |||
import org.springframework.beans.factory.annotation.Autowired; | |||
import org.springframework.web.bind.annotation.RequestBody; | |||
import org.springframework.web.bind.annotation.RequestMapping; | |||
import org.springframework.web.bind.annotation.ResponseBody; | |||
import org.springframework.web.bind.annotation.RestController; | |||
import javax.servlet.http.HttpServletRequest; | |||
import javax.servlet.http.HttpServletResponse; | |||
import java.io.IOException; | |||
@RestController | |||
@RequestMapping(value="bodyFat",produces={"application/json;charset=UTF-8"}) | |||
public class BodyFatController extends BaseController { | |||
@Autowired | |||
private BodyFatServiceImpl bodyFatServiceImpl; | |||
/** | |||
* 上报称重数据(原始数据) | |||
* @param params | |||
* @param request | |||
* @param response | |||
* @throws IOException | |||
*/ | |||
@RequestMapping(value="saveWeighDataByAdc") | |||
@ResponseBody | |||
public void saveWeighDataByAdc(@RequestBody String params, HttpServletRequest request, HttpServletResponse response) throws IOException { | |||
checkParams(response, params); | |||
// System.out.println("saveWeighDataByAdc() params: " + params); | |||
byte[] paramsByte = decryptParams(response,params); | |||
if(paramsByte.length >1){ | |||
writeOutResponse(response, bodyFatServiceImpl.saveWeighDataByAdc(paramsByte, request)); | |||
}else{ | |||
writeOutResponse(response,paramsByte); | |||
} | |||
} | |||
} |
@@ -0,0 +1,57 @@ | |||
package com.inet.ailink.receiver.controller; | |||
@RestController | |||
//@RequestMapping(value="devivce",produces={"application/json;charset=UTF-8"}) | |||
@RequestMapping(value="devivce") | |||
public class DeviceController extends BaseController { | |||
@Autowired | |||
private SysDeviceInfoServiceImpl sysDeviceInfoServiceImpl; | |||
@Autowired | |||
private SysAccoountServiceImpl sysAccoountServiceImpl; | |||
/** | |||
* 设备注册 | |||
* @param params | |||
* @param request | |||
* @param response | |||
* @throws IOException | |||
*/ | |||
@RequestMapping(value="register") | |||
@ResponseBody | |||
public void register(@RequestBody String params, HttpServletRequest request, HttpServletResponse response) throws IOException { | |||
checkParams(response, params); | |||
// System.out.println("devivce/register() params: " + params); | |||
byte[] paramsByte = decryptParams(response,params); | |||
if(paramsByte.length >1){ | |||
writeOutResponse(response, sysDeviceInfoServiceImpl.register(paramsByte, request)); | |||
}else{ | |||
writeOutResponse(response,paramsByte); | |||
} | |||
} | |||
/** | |||
* 获取设备绑定的用户 | |||
* @param params | |||
* @param request | |||
* @param response | |||
* @throws IOException | |||
*/ | |||
@RequestMapping(value="getUsers") | |||
@ResponseBody | |||
public void getUsers(@RequestBody String params, HttpServletRequest request, HttpServletResponse response) throws IOException { | |||
checkParams(response, params); | |||
// System.out.println("devivce/register() params: " + params); | |||
byte[] paramsByte = decryptParams(response,params); | |||
if(paramsByte.length >1){ | |||
writeOutResponseNoEncrypt(response, sysAccoountServiceImpl.getUsersByDeviceId(paramsByte, request)); | |||
}else{ | |||
writeOutResponse(response,paramsByte); | |||
} | |||
} | |||
} |
@@ -0,0 +1,53 @@ | |||
package com.inet.ailink.receiver.service.impl; | |||
@Service | |||
@Transactional(rollbackFor=Exception.class) | |||
public class BodyFatServiceImpl | |||
{ | |||
@Autowired | |||
IBodyFatDao bodyFatDao; | |||
@Override | |||
protected IBodyFatDao getEntityDao() { | |||
return bodyFatDao; | |||
} | |||
public Response<Object> saveWeighDataByAdc(byte[] paramsByte, HttpServletRequest request){ | |||
Response<Object> result = new Response<Object>(); | |||
//解析数据 | |||
//设备ID | |||
Integer deviceId = Integer.parseInt(Base64TeaUitls.getLowConactHighEndForInt(0, 3, paramsByte)); | |||
//设备时间 | |||
String devivceTimeStr = Base64TeaUitls.getStartToEndForInt(4,9, paramsByte); | |||
System.out.println("devivceTimeStr = " + devivceTimeStr); | |||
String[] devivceTimeArry = devivceTimeStr.split(":"); | |||
String deviceTimeFormate = (2000+Integer.parseInt(devivceTimeArry[0]))+"-"+devivceTimeArry[1]+"-"+devivceTimeArry[2]+" "+devivceTimeArry[3]+":"+devivceTimeArry[4]+":"+devivceTimeArry[5]; | |||
System.out.println("deviceTimeFormate = " + deviceTimeFormate); | |||
Date devivceTime = DateUtils.parse(deviceTimeFormate, DateUtils.DATETIME_FORMAT_PATTERN); | |||
System.out.println("devivceTime = " + devivceTime); | |||
//设备在线状态 | |||
String deviceOnlineStatus = Base64TeaUitls.getStartToEndForInt(10, 10, paramsByte); | |||
//体重 | |||
String deviceWeigh = Base64TeaUitls.getLowConactHighEndForInt(11, 13, paramsByte); | |||
//体重单位 | |||
String deviceWeighUnit = Base64TeaUitls.getStartToEndForInt(14, 14, paramsByte); | |||
//体重精度 | |||
String deviceWeighPoint = Base64TeaUitls.getStartToEndForInt(15, 15, paramsByte); | |||
//阻抗 | |||
String deviceAdc = Base64TeaUitls.getLowConactHighEndForInt(16, 17, paramsByte); | |||
//心率 | |||
String deviceHeartRate = Base64TeaUitls.getStartToEndForInt(18, 18, paramsByte); | |||
//算法 | |||
String deviceAlgorithm = Base64TeaUitls.getStartToEndForInt(19, 19, paramsByte); | |||
//用户id | |||
Integer subUserId = Integer.parseInt(Base64TeaUitls.getLowConactHighEndForInt(20, 23, paramsByte)); | |||
//将解析出的数据,赋值 | |||
} | |||
} |
@@ -0,0 +1,40 @@ | |||
package com.inet.ailink.receiver.service.impl; | |||
import com.inet.ailink.receiver.common.enums.StatusCode; | |||
import com.inet.ailink.receiver.common.vo.Response; | |||
import org.springframework.stereotype.Service; | |||
import org.springframework.transaction.annotation.Transactional; | |||
import javax.servlet.http.HttpServletRequest; | |||
import java.util.ArrayList; | |||
import java.util.List; | |||
@Service | |||
@Transactional(rollbackFor=Exception.class) | |||
public class SysAccoountServiceImpl | |||
{ | |||
public Response<Object> getUsersByDeviceId(byte[] paramsByte, HttpServletRequest request) { | |||
Response<Object> result = new Response<Object>(); | |||
//以下只是返回示例,请根据具体项目情况去数据库查询绑定wifi秤的用户信息并返回 | |||
List<Object> data = new ArrayList<Object>(); | |||
List<Object> listMap = new ArrayList<Object>(); | |||
listMap.add(1024);//用户id | |||
listMap.add(1);//用户性别 | |||
listMap.add(25);//用户年龄 | |||
listMap.add("170");//用户身高 | |||
listMap.add("0");//用户身高单位 | |||
listMap.add("0");//最新体重单位 | |||
listMap.add(0); //用户类型:0普通人 1运动员 | |||
listMap.add("67.70");//最新体重单位 | |||
data.add(listMap); | |||
result.setStatus(StatusCode.SUCCESS.getCode()); | |||
result.setData(data); | |||
return result; | |||
} | |||
} |
@@ -0,0 +1,117 @@ | |||
package com.inet.ailink.receiver.service.impl; | |||
@Service | |||
@Transactional(rollbackFor=Exception.class) | |||
public class SysDeviceInfoServiceImpl | |||
{ | |||
@Autowired | |||
ISysDeviceInfoDao sysDeviceInfoDao; | |||
@Override | |||
protected ISysDeviceInfoDao getEntityDao() { | |||
return sysDeviceInfoDao; | |||
} | |||
public static String byteArr2HexStr(byte[] arrB) { | |||
int iLen = arrB.length; | |||
// 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍 | |||
StringBuffer sb = new StringBuffer(iLen * 2); | |||
for (int i = 0; i < iLen; i++) { | |||
int intTmp = arrB[i]; | |||
// 把负数转换为正数 | |||
while (intTmp < 0) { | |||
intTmp = intTmp + 256; | |||
} | |||
// 小于0F的数需要在前面补0 | |||
if (intTmp < 16) { | |||
sb.append("0"); | |||
} | |||
sb.append(Integer.toString(intTmp, 16).toUpperCase()); | |||
sb.append(" "); | |||
} | |||
return sb.toString(); | |||
} | |||
public Response<Object> register(byte[] paramsByte, HttpServletRequest request){ | |||
// System.out.println("register(): " + byteArr2HexStr(paramsByte)); | |||
Response<Object> result = new Response<Object>(); | |||
//解析数据 | |||
//设备地址 | |||
String deviceMac = Base64TeaUitls.getStartToEndForHex(0, 5, paramsByte); | |||
// | |||
Integer cid = Integer.parseInt(Base64TeaUitls.getLowConactHighEndForInt(6, 7, paramsByte)); | |||
Integer pid = Integer.parseInt(Base64TeaUitls.getLowConactHighEndForInt(8, 9, paramsByte)); | |||
Integer vid = Integer.parseInt(Base64TeaUitls.getLowConactHighEndForInt(10, 11, paramsByte)); | |||
//设备名 | |||
String deviceName = Base64TeaUitls.getStartToEndForHex(12, 13, paramsByte); | |||
//产品型号 | |||
String deviceType = Base64TeaUitls.getStartToEndForHex(14, 14, paramsByte); | |||
// //硬件版本 | |||
// String deviceHardwareVersion = Base64TeaUitls.getStartToEndForInt(15, 15, paramsByte); | |||
// //软件版本 | |||
// String deviceSoftwareVersion = Base64TeaUitls.getStartToEndForInt(16, 16, paramsByte); | |||
// //用户版本 | |||
// String deviceUserAutoVersion = Base64TeaUitls.getStartToEndForInt(17, 17, paramsByte); | |||
// //年月日 | |||
String deviceDate = Base64TeaUitls.getStartToEndForInt(18, 20, paramsByte); | |||
// System.out.println("deviceDate: " + deviceDate); | |||
//芯片id | |||
String chipId = Base64TeaUitls.getStartToEndForHex(21, 26, paramsByte); | |||
//设备SN [12-14]WM05+[0-5]设备地址+[21-26]芯片id | |||
String deviceSN = deviceName +deviceType+deviceMac+chipId; | |||
deviceSN = deviceSN.replaceAll(":", ""); | |||
//设备单位 | |||
String deviceUnit = Base64TeaUitls.getStartToEndForInt(27, 27, paramsByte); | |||
//如果IMEI不为空,则使用IMEI当作设备的唯一标识 | |||
String imei = null; | |||
if(paramsByte.length > 28){ | |||
//设备IMEI长度 | |||
int imeiLength = Integer.parseInt(Base64TeaUitls.getStartToEndForInt(28, 28, paramsByte)); | |||
if(imeiLength > 0){ | |||
//获取imei | |||
imei = Base64TeaUitls.getStartToEndForASIII(28+1, 28+imeiLength, paramsByte); | |||
} | |||
} | |||
//将解析出的数据,赋值 | |||
// Device device = new Device(deviceName, deviceMac, new Date(), cid, pid, vid, "", | |||
// deviceType,deviceSoftwareVersion, deviceHardwareVersion, deviceUserAutoVersion, deviceDate,chipId,deviceSN,deviceUnit); | |||
byte[] name = new byte[2]; | |||
name[0] = paramsByte[12]; | |||
name[1] = paramsByte[13]; | |||
String moduleName = new String(name, StandardCharsets.UTF_8); | |||
// System.out.println("moduleName: " + moduleName); | |||
int type = paramsByte[14] & 0xFF; | |||
String moduleType = (type<10?("0"):"") + type; | |||
// System.out.println("moduleType: " + moduleType); | |||
int hardware = paramsByte[15] & 0xFF; | |||
String hardwareVer = "H" + hardware; | |||
// System.out.println("hardwareVer: " + hardwareVer); | |||
int software = paramsByte[16] & 0xFF; | |||
String softwareVer = "S" + String.valueOf(software / 10) + "." + String.valueOf(software % 10); | |||
// System.out.println("softwareVer: " + softwareVer); | |||
int custom = paramsByte[17] & 0xFF; | |||
String customVer = "." + String.valueOf(custom); | |||
// System.out.println("customVer: " + customVer); | |||
int year = paramsByte[18] & 0xFF; | |||
int month = paramsByte[19] & 0xFF; | |||
int day = paramsByte[20] & 0xFF; | |||
String dateStr = "_20" + (year<10?("0"+year):year) + (month<10?("0"+month):month) + (day<10?("0"+day):day); | |||
// System.out.println("dateStr: " + dateStr); | |||
String version = moduleName + moduleType + hardwareVer + softwareVer + customVer + dateStr; | |||
// System.out.println("version: " + version); | |||
Device device = new Device(null, deviceMac, new Date(), cid, pid, vid, "", | |||
null, version, null, null, null, chipId, deviceSN, deviceUnit); | |||
//如果IMEI不为空,则使用IMEI当作设备的唯一标识 | |||
if(imei != null && !isEmpty(imei)){ | |||
device.setMac(imei.replaceAll(":", "")); | |||
device.setDeviceSN(imei.replaceAll(":", "")); | |||
} | |||
System.out.println(JsonUtils.toJson(device)); | |||
//注册设备 | |||
result = saveDevice(device); | |||
return result; | |||
} | |||
} |
@@ -0,0 +1,396 @@ | |||
package com.inet.ailink.receiver.common.utils; | |||
import java.io.UnsupportedEncodingException; | |||
public class Base64TeaUitls { | |||
//加密 | |||
public static String encrypt(String dataValue){ | |||
byte[] old = BytesUtils.getBytes(Integer.parseInt(dataValue)); | |||
String result = ""; | |||
try { | |||
//tea加密 | |||
byte[] teaDscrypt =TeaUtils.encrypt(old,null); | |||
//base编码 | |||
result= Base64Util.encoderString(teaDscrypt); | |||
} catch (UnsupportedEncodingException e) { | |||
return result; | |||
} | |||
return result; | |||
} | |||
//解密 | |||
public static byte[] decrypt(String base64Text){ | |||
//base解码 | |||
String base64TextEn; | |||
try { | |||
base64TextEn = Base64Util.decoderString(base64Text); | |||
//解码数据转换为byte数组 | |||
byte[] base64TeaByteOld = Base64Util.hexStrToByteArray(base64TextEn); | |||
//tea解密byte数组 | |||
byte[] base64TeaByte =TeaUtils.decrypt(base64TeaByteOld,null); | |||
//将负数转换为整数 | |||
/*if(base64TeaByte != null){ | |||
for(int i=0;i<base64TeaByte.length;i++){ | |||
if(base64TeaByte[i]<0){ | |||
base64TeaByte[i] = (byte) (256 + base64TeaByte[i]); | |||
} | |||
} | |||
}*/ | |||
return base64TeaByte; | |||
} catch (UnsupportedEncodingException e) { | |||
return null; | |||
} | |||
} | |||
/** | |||
* 十进制转16进制 | |||
* @param n | |||
* @return | |||
*/ | |||
private static String intToHex(int n) { | |||
StringBuilder sb = new StringBuilder(8); | |||
String a; | |||
char []b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; | |||
if(n==0){ | |||
return "00"; | |||
} | |||
while(n != 0){ | |||
if(n<0){ | |||
n= 256 +n; | |||
} | |||
sb = sb.append(b[n%16]); | |||
n = n/16; | |||
} | |||
a = sb.reverse().toString(); | |||
if(a.length() == 1){ | |||
a= "0"+a; | |||
} | |||
return a; | |||
} | |||
/** | |||
* 获取开始下标到结束下标的16进制的值 | |||
* @param start | |||
* @param end | |||
* @param params | |||
* @return | |||
*/ | |||
public static String getStartToEndForHex(int start,int end,byte[] params){ | |||
String result = ""; | |||
for(int i=start;i<=end;i++){ | |||
if(i==end){ | |||
result = result+intToHex(params[i]); | |||
}else{ | |||
result = result+intToHex(params[i])+":"; | |||
} | |||
// System.out.println(params[i]+":"+intToHex(params[i])); | |||
} | |||
return result; | |||
} | |||
/** | |||
* 获取开始下标到结束下标的10进制的值 | |||
* @param start | |||
* @param end | |||
* @param params | |||
* @return | |||
*/ | |||
public static String getStartToEndForInt(int start,int end,byte[] params){ | |||
String result = ""; | |||
for(int i=start;i<=end;i++){ | |||
int temp = params[i]; | |||
if(temp < 0){ | |||
temp = 256 + temp; | |||
} | |||
if(i==end){ | |||
result = result+temp; | |||
}else{ | |||
result = result+temp+":"; | |||
} | |||
} | |||
return result; | |||
} | |||
/*public static String getLowToHighEndForInt(int indexLow,int indexHigh,byte[] params){ | |||
String result = ""; | |||
int tempLow = params[indexLow]; | |||
if(tempLow < 0){ | |||
tempLow = 256 + tempLow; | |||
} | |||
int tempHigh = params[indexHigh]; | |||
if(tempHigh < 0){ | |||
tempHigh = 256 + tempHigh; | |||
} | |||
int tempResult = (tempLow << 8) | tempHigh; | |||
return result+tempResult; | |||
}*/ | |||
/** | |||
* 获取低位到高位的移位+或运算的值 | |||
* @param indexLow | |||
* @param indexHigh | |||
* @param params | |||
* @return | |||
*/ | |||
public static String getLowConactHighEndForInt(int indexLow,int indexHigh,byte[] params){ | |||
String result = ""; | |||
int tempResult = 0; | |||
for(int i = indexLow;i<=indexHigh;i++){ | |||
int temp = (params[i] < 0 ? 256 + params[i] : params[i]); | |||
int tempmov = (indexHigh-i)+2; | |||
tempmov = (i == indexHigh ? 0 : (int) Math.pow(2, tempmov)); | |||
tempResult = (temp << tempmov) | tempResult; | |||
} | |||
return result+tempResult; | |||
} | |||
public static String byteToHex(byte b){ | |||
String hex = Integer.toHexString(b & 0xFF); | |||
if(hex.length() < 2){ | |||
hex = "0" + hex; | |||
} | |||
return hex; | |||
} | |||
/** | |||
* 获取开始下标到结束下标的ASIII对应的值 | |||
* @param start | |||
* @param end | |||
* @param params | |||
* @return | |||
*/ | |||
public static String getStartToEndForASIII(int start,int end,byte[] params){ | |||
String result = ""; | |||
for(int i=start;i<=end;i++){ | |||
if(i==end){ | |||
result = result+asciiToString(params[i]+""); | |||
}else{ | |||
result = result+asciiToString(params[i]+"")+":"; | |||
} | |||
} | |||
return result; | |||
} | |||
/** | |||
* ASCII转字符 | |||
* @param value | |||
* @return | |||
*/ | |||
public static String asciiToString(String value) | |||
{ | |||
value = value.replaceAll(":", ""); | |||
char c= (char) Integer.parseInt(value); | |||
//System.out.println(value+":"+c); | |||
return c+""; | |||
} | |||
public static void main(String args[]) throws UnsupportedEncodingException | |||
{ | |||
// String str = "H4CpBA/xguYaSidJuBnCEydjVVdwDBKAfgvuaUpSEuU="; | |||
// byte[] paramsByte = Base64TeaUitls.decrypt(str); | |||
// | |||
// for(byte i : paramsByte) | |||
// System.out.print(byteToHex(i) + " "); | |||
// System.out.println(); | |||
//01 01 16 b7 28 32 18 4a 88 00 0e 00 00 00 00 42 4d 10 01 0a 00 13 05 07 e9 | |||
//注册设备数据 | |||
// byte[] old =new byte[]{ | |||
// (byte)0x01,(byte)0x01,(byte)0x08 ,(byte)0x16 ,(byte)0xb7 ,(byte)0x28 //mac地址 | |||
// ,(byte)0x00 ,(byte)0x00 //cid | |||
// ,(byte)0x00 ,(byte)0x01 //pid | |||
// ,(byte)0x00 ,(byte)0x02 //vid | |||
// ,(byte)0x42 ,(byte)0x4d //产品名称 | |||
// ,(byte)0x01 //产品型号 | |||
// ,(byte)0x01 //硬件版本 | |||
// ,(byte)0x42 //软件版本 | |||
// ,(byte)0x4d //用户版本 | |||
// ,(byte)0x13 //年 | |||
// ,(byte)0x0c //月 | |||
// ,(byte)0x12 //日 | |||
// ,(byte)0x06,(byte)0x06,(byte)0x06 ,(byte)0x06 ,(byte)0x06 ,(byte)0x06 //芯片id | |||
// ,(byte)0x09 //设备单位 | |||
// ,(byte)0x03 //设备IMEI长度 | |||
// ,(byte)0x01,(byte)0x02,(byte)0x20 }; //设备IMEI | |||
//上报称重数据(原始数据) | |||
//5781 | |||
// byte[] old =new byte[]{ | |||
// (byte)0x00,(byte)0x00 ,(byte)0x0f,(byte)0x71 //设备SN号 | |||
// ,(byte)0x15 //年 | |||
// ,(byte)0x03 //月 | |||
// ,(byte)0x04 //日 | |||
// ,(byte)0x0c //时 | |||
// ,(byte)0x00 //分 | |||
// ,(byte)0x00 //秒 | |||
// ,(byte)0x00 //是否离线记录 | |||
// ,(byte)0x00 //体重数据高 | |||
// ,(byte)0x00 //体重数据中 | |||
// ,(byte)0x3C //体重数据低 | |||
// ,(byte)0x00 //体重单位 | |||
// ,(byte)0x00 //体重精度 | |||
// ,(byte)0x01 //阻抗高 | |||
// ,(byte)0xff //阻抗低 | |||
// ,(byte)0x5f //心率 | |||
// ,(byte)0x01 //算法 | |||
// ,(byte)0x00,(byte)0x00,(byte)0x03,(byte)0x97}; //用户id | |||
//最新OTA升级地址 | |||
// byte[] old =new byte[]{ | |||
// (byte)0x01,(byte)0x01,(byte)0x08 ,(byte)0x16 ,(byte)0xb7 ,(byte)0x28 //mac地址 | |||
// ,(byte)0x00 ,(byte)0x00 //cid | |||
// ,(byte)0x00 ,(byte)0x01 //pid | |||
// ,(byte)0x00 ,(byte)0x02 //vid | |||
// ,(byte)0x42 ,(byte)0x4d //产品名称 | |||
// ,(byte)0x01 //产品型号 | |||
// ,(byte)0x01 //硬件版本 | |||
// ,(byte)0x09 //软件版本 | |||
// ,(byte)0x06,(byte)0x06,(byte)0x06 ,(byte)0x06 ,(byte)0x06 ,(byte)0x06 //芯片id | |||
// ,(byte)0x00,(byte)0x00 ,(byte)0x07,(byte)0xBF //设备id | |||
// ,(byte)0x00 //客户定制版本 | |||
// ,(byte)0x00 ,(byte)0x00,(byte)0x00,(byte)0x00 //保留位 | |||
// }; | |||
// //通过cid获取设备访问地址 | |||
byte[] old =new byte[]{ | |||
(byte)0x00 ,(byte)0x00,(byte)0x00, //模块名称 | |||
(byte)0x01,(byte)0x01,(byte)0x08 ,(byte)0x16 ,(byte)0xb7 ,(byte)0x28, //mac地址 | |||
(byte)0x01,(byte)0x01,(byte)0x08 ,(byte)0x16 ,(byte)0xb7 ,(byte)0x28, //芯片id | |||
(byte)0x00 ,(byte)0x11, //cid | |||
(byte)0x00 ,(byte)0x01, //pid | |||
(byte)0x00 ,(byte)0x1B, //vid | |||
(byte)0x00,(byte)0x00 ,(byte)0x00 //保留位 | |||
}; | |||
//通过cid,pid,vid获取设备访问地址 | |||
//57 4d 05 88 4a 18 32 28 a4 02 38 6f a5 dc 12 00 11 00 00 00 00 00 00 00 | |||
// byte[] old =new byte[]{ | |||
// (byte)0x57 ,(byte)0x4d,(byte)0x05, //模块名称 | |||
// (byte)0x88,(byte)0x4a,(byte)0x08 ,(byte)0x32 ,(byte)0x28 ,(byte)0xa4, //mac地址 | |||
// (byte)0x02,(byte)0x38,(byte)0x6f ,(byte)0xa5 ,(byte)0xdc ,(byte)0x12, //芯片id | |||
// (byte)0x00 ,(byte)0x0e, //cid | |||
// (byte)0x00 ,(byte)0x01, //pid | |||
// (byte)0x00 ,(byte)0x32, //vid | |||
// (byte)0x00,(byte)0x00 ,(byte)0x00 //保留位 | |||
// }; | |||
//刷牙数据上传 | |||
// byte[] old =new byte[]{ | |||
// (byte)0x00,(byte)0x00 ,(byte)0x07,(byte)0xBF, //设备SN号 | |||
// (byte)0x01, //牙刷工作模式 | |||
// (byte)0x00, // 刷牙时长高字节 | |||
// (byte)0x03, // 刷牙时长低字节 | |||
// (byte)0x00, //左边刷牙时长高字节 | |||
// (byte)0x02, //左边刷牙时长低字节 | |||
// (byte)0x00, //右边刷牙时长低字节 | |||
// (byte)0x01, //右边刷牙时长低字节 | |||
// (byte)0x09, //剩余电量 | |||
// (byte)0x00,(byte)0x04, //默认刷牙时长 | |||
// (byte)0x00,(byte)0x00,//保留位 | |||
// (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,//保留位 | |||
// (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00 //保留位 | |||
// }; | |||
//血糖数据 | |||
// byte[] old =new byte[]{ | |||
// (byte)0x00,(byte)0x00 ,(byte)0x07,(byte)0xBF, //设备SN号 | |||
// (byte)0x00, //血糖数据高字节 | |||
// (byte)0x00, //血糖数据中字节 | |||
// (byte)0x12, //血糖数据低字节 | |||
// (byte)0x01, //血糖单位 | |||
// (byte)0x01, //小数点 | |||
// (byte)0x00, //状态码 | |||
// (byte)0x10, //剩余电量 | |||
// (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,//保留位 | |||
// (byte)0x00 //保留位 | |||
// }; | |||
/*int a= 1846; | |||
System.out.println("原始数字:"+a); | |||
byte[] old = BytesUtils.getBytes(a);*/ | |||
//通过设备id,获取设备单位 | |||
// byte[] old =new byte[]{ | |||
// (byte)0x00,(byte)0x00 ,(byte)0x0F,(byte)0x72, //设备id | |||
// (byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,//保留位 | |||
// }; | |||
//通过设备id,修改设备单位 | |||
// byte[] old =new byte[]{ | |||
// (byte)0x00,(byte)0x00 ,(byte)0x0B,(byte)0x31, //设备id | |||
// (byte)0x01 //设备单位 | |||
// }; | |||
//注册设备数据 | |||
// byte[] old =new byte[]{ | |||
// (byte)0x00, (byte)0x00 , (byte)0x00 , (byte)0x00 , (byte)0x00, (byte)0x00 //设备MAC | |||
// , (byte)0x00, (byte)0x2c//CID | |||
// , (byte)0x00 , (byte)0x00//PID | |||
// , (byte)0x00 , (byte)0x00//VID | |||
// , (byte)0x4c//模块名称 | |||
// , (byte)0x4d | |||
// , (byte)0x09 | |||
// , (byte)0x00 | |||
// , (byte)0x0a | |||
// , (byte)0x00 , (byte)0x15 , (byte)0x04 , (byte)0x07 , (byte)0x00 , (byte)0x00 | |||
// , (byte)0x00 , (byte)0x00 , (byte)0x00 , (byte)0x00 , (byte)0x00 | |||
// , (byte)0x0f //设备IMEI长度 | |||
// , (byte)0x08 , (byte)0x06 , (byte)0x09 , (byte)0x03 , (byte)0x02 , (byte)0x04 , (byte)0x00 , (byte)0x05 //设备IMEI 86932405 | |||
// , (byte)0x00 , (byte)0x00 , (byte)0x00 , (byte)0x02 , (byte)0x07 , (byte)0x06 , (byte)0x09 //设备IMEI 0002769 | |||
// , (byte)0x00, (byte)0x00 , (byte)0x00 , (byte)0x00 }; //备用字段 | |||
//原始数据 | |||
System.out.println( "原始数据:"); | |||
for(byte i : old) | |||
System.out.print(byteToHex(i) + " "); | |||
System.out.println(); | |||
//tea加密 | |||
byte[] teaDscrypt =TeaUtils.encrypt(old,null); | |||
System.out.println( "tea加密:"); | |||
for(byte i : teaDscrypt) | |||
System.out.print(byteToHex(i) + " "); | |||
System.out.println(); | |||
//base编码 | |||
String base64Text = Base64Util.encoderString(teaDscrypt); | |||
base64Text = "rvXiSvrWrR+/p1ZhAPlXr7x1gxbvrurA"; | |||
System.out.println("base64编码后的数据长度:"+Base64Util.getLength(base64Text)+":"+base64Text); | |||
//base解码 | |||
String base64TextEn= Base64Util.decoderString(base64Text); | |||
//String base64TextEn= Base64Util.decoderString("BCc0vnfr9kd5"); | |||
// System.out.println("base64解码后的数据长度:"+Base64Util.getLength(base64TextEn)+":"+base64TextEn); | |||
/*//转称byte数组(每两位一个16进制byte) | |||
List<String> base64TeaByteOldList = new ArrayList<String>(); | |||
for(int i=0;i<base64TextEn.length();i++){ | |||
if(i%2 == 0){ | |||
base64TeaByteOldList.add("0x"+base64TextEn.charAt(i)+base64TextEn.charAt(i+1)); | |||
} | |||
} | |||
//解码后转换得到的list | |||
System.out.println("解码后转换得到的list:"); | |||
for(String byte16:base64TeaByteOldList){ | |||
System.out.print(byte16+" "); | |||
} | |||
System.out.println();*/ | |||
//解码数据转换为byte数组 | |||
byte[] base64TeaByteOld = Base64Util.hexStrToByteArray(base64TextEn); | |||
System.out.println( "解码后得到的tea加密的byte数组:"); | |||
for(byte i : base64TeaByteOld) | |||
System.out.print(byteToHex(i) + " "); | |||
System.out.println(); | |||
byte[] base64TeaByte =TeaUtils.decrypt(base64TeaByteOld,null); | |||
System.out.println( "tea解密:"); | |||
for(byte i : base64TeaByte) | |||
System.out.print(byteToHex(i) + " "); | |||
System.out.println(); | |||
//int imeiLength = base64TeaByte[28] & 0xFF; | |||
int imeiLength = Integer.parseInt(Base64TeaUitls.getStartToEndForInt(28, 28, base64TeaByte)); | |||
System.out.println("imeiLength:"+imeiLength); | |||
System.out.println("IMEI:"+ Base64TeaUitls.getStartToEndForHex(28+1, 28+imeiLength, base64TeaByte)); | |||
System.out.println("IMEI:"+ Base64TeaUitls.getStartToEndForInt(28+1, 28+imeiLength, base64TeaByte)); | |||
System.out.println("IMEI:"+ Base64TeaUitls.getStartToEndForASIII(28+1, 28+imeiLength, base64TeaByte)); | |||
} | |||
} |
@@ -0,0 +1,167 @@ | |||
package com.inet.ailink.receiver.common.utils; | |||
import java.io.UnsupportedEncodingException; | |||
import java.util.Base64; | |||
//import com.google.common.primitives.Bytes; | |||
public class Base64Util | |||
{ | |||
final static Base64.Decoder decoder = Base64.getDecoder(); | |||
final static Base64.Encoder encoder = Base64.getEncoder(); | |||
public Base64Util(){} | |||
/** | |||
* 解码 | |||
* @param encoderStr | |||
* @return | |||
* @throws UnsupportedEncodingException | |||
*/ | |||
public static String decoderString(String base64Text) throws UnsupportedEncodingException{ | |||
String result = ""; | |||
if(base64Text != null && !base64Text.isEmpty() && !base64Text.equals("")){ | |||
byte[] textByte = decoder.decode(base64Text); | |||
result = bytes_String16(textByte); | |||
} | |||
return result; | |||
} | |||
/** | |||
* byte[]转16进制字符串 | |||
* @param b | |||
* @return | |||
*/ | |||
public static String bytes_String16(byte[] b) { | |||
StringBuilder sb = new StringBuilder(); | |||
for(int i=0;i<b.length;i++) { | |||
sb.append(String.format("%02x", b[i])); | |||
} | |||
return sb.toString(); | |||
} | |||
/** | |||
* 编码 | |||
* @param encoderStr | |||
* @return | |||
* @throws UnsupportedEncodingException | |||
*/ | |||
public static String encoderString(String base64Text) throws UnsupportedEncodingException{ | |||
String result = ""; | |||
if(base64Text != null && !base64Text.isEmpty() && !base64Text.equals("")){ | |||
byte[] textByte = base64Text.getBytes("UTF-8"); | |||
result = encoder.encodeToString(textByte); | |||
} | |||
return result; | |||
} | |||
/** | |||
* 编码 | |||
* @param encoderStr | |||
* @return | |||
* @throws UnsupportedEncodingException | |||
*/ | |||
public static String encoderString(byte[] textByte) throws UnsupportedEncodingException{ | |||
return encoder.encodeToString(textByte); | |||
} | |||
public static int getLength(String s) { | |||
int length = 0; | |||
for (int i = 0; i < s.length(); i++) { | |||
int ascii = Character.codePointAt(s, i); | |||
if (ascii >= 0 && ascii <= 255) { | |||
length++; | |||
} else { | |||
length += 2; | |||
} | |||
} | |||
return length; | |||
} | |||
private static String intToHex(int n) { | |||
StringBuffer s = new StringBuffer(); | |||
String a; | |||
char []b = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; | |||
while(n != 0){ | |||
s = s.append(b[n%16]); | |||
n = n/16; | |||
} | |||
a = s.reverse().toString(); | |||
return a; | |||
} | |||
public static byte[] hexStrToByteArray(String str) | |||
{ | |||
if (str == null) { | |||
return null; | |||
} | |||
if (str.length() == 0) { | |||
return new byte[0]; | |||
} | |||
byte[] byteArray = new byte[str.length() / 2]; | |||
for (int i = 0; i < byteArray.length; i++){ | |||
String subStr = str.substring(2 * i, 2 * i + 2); | |||
byteArray[i] = ((byte)Integer.parseInt(subStr, 16)); | |||
} | |||
return byteArray; | |||
} | |||
public static void main(String args[]) throws UnsupportedEncodingException | |||
{ | |||
//01 01 16 b7 28 32 18 4a 88 00 0e 00 00 00 00 42 4d 10 01 0a 00 13 05 07 e9 | |||
byte[] old =new byte[]{(byte)0x01 | |||
,(byte)0x01 ,(byte)0x16 ,(byte)0xb7 ,(byte)0x28 | |||
,(byte)0x32 ,(byte)0x18 ,(byte)0x4a ,(byte)0x88 | |||
,(byte)0x00 ,(byte)0x0e ,(byte)0x00 ,(byte)0x00 | |||
,(byte)0x00 ,(byte)0x00 ,(byte)0x42 ,(byte)0x4d | |||
,(byte)0x10 ,(byte)0x01 ,(byte)0x0a ,(byte)0x00 | |||
,(byte)0x13 ,(byte)0x05 ,(byte)0x07 ,(byte)0xe9}; | |||
//原始数据 | |||
System.out.println( "原始数据:"); | |||
for(byte i : old) | |||
System.out.print(i + " "); | |||
System.out.println(); | |||
//tea加密 | |||
byte[] teaDscrypt =TeaUtils.encrypt(old,null); | |||
System.out.println( "tea加密:"); | |||
for(byte i : teaDscrypt) | |||
System.out.print(i + " "); | |||
System.out.println(); | |||
//base编码 | |||
String base64Text = encoderString(teaDscrypt); | |||
System.out.println("base64编码后的数据长度:"+getLength(base64Text)+":"+base64Text); | |||
//base解码 | |||
String base64TextEn= decoderString(base64Text); | |||
System.out.println("base64解码后的数据长度:"+getLength(base64TextEn)+":"+base64TextEn); | |||
/*//转称byte数组(每两位一个16进制byte) | |||
List<String> base64TeaByteOldList = new ArrayList<String>(); | |||
for(int i=0;i<base64TextEn.length();i++){ | |||
if(i%2 == 0){ | |||
base64TeaByteOldList.add("0x"+base64TextEn.charAt(i)+base64TextEn.charAt(i+1)); | |||
} | |||
} | |||
//解码后转换得到的list | |||
System.out.println("解码后转换得到的list:"); | |||
for(String byte16:base64TeaByteOldList){ | |||
System.out.print(byte16+" "); | |||
} | |||
System.out.println();*/ | |||
//解码数据转换为byte数组 | |||
byte[] base64TeaByteOld = hexStrToByteArray(base64TextEn); | |||
System.out.println( "解码后得到的tea加密的byte数组:"); | |||
for(byte i : base64TeaByteOld) | |||
System.out.print(i + " "); | |||
System.out.println(); | |||
byte[] base64TeaByte =TeaUtils.decrypt(base64TeaByteOld,null); | |||
System.out.println( "tea解密:"); | |||
for(byte i : base64TeaByte) | |||
System.out.print(i + " "); | |||
System.out.println(); | |||
} | |||
} |
@@ -0,0 +1,895 @@ | |||
package com.inet.ailink.receiver.common.utils; | |||
import org.apache.commons.lang.ArrayUtils; | |||
import java.nio.charset.Charset; | |||
/** | |||
* | |||
* @Description: 字节数组转换工具类 | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public class BytesUtils { | |||
public static final String GBK = "GBK"; | |||
public static final String UTF8 = "utf-8"; | |||
public static final char[] ascii = "0123456789ABCDEF".toCharArray(); | |||
private static char[] HEX_VOCABLE = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; | |||
/** | |||
* 将short整型数值转换为字节数组 | |||
* | |||
* @param data | |||
* @return | |||
*/ | |||
public static byte[] getBytes(short data) { | |||
byte[] bytes = new byte[2]; | |||
bytes[0] = (byte) ((data & 0xff00) >> 8); | |||
bytes[1] = (byte) (data & 0xff); | |||
return bytes; | |||
} | |||
/** | |||
* 将字符转换为字节数组 | |||
* | |||
* @param data | |||
* @return | |||
*/ | |||
public static byte[] getBytes(char data) { | |||
byte[] bytes = new byte[2]; | |||
bytes[0] = (byte) (data >> 8); | |||
bytes[1] = (byte) (data); | |||
return bytes; | |||
} | |||
/** | |||
* 将布尔值转换为字节数组 | |||
* | |||
* @param data | |||
* @return | |||
*/ | |||
public static byte[] getBytes(boolean data) { | |||
byte[] bytes = new byte[1]; | |||
bytes[0] = (byte) (data ? 1 : 0); | |||
return bytes; | |||
} | |||
/** | |||
* 将整型数值转换为字节数组 | |||
* | |||
* @param data | |||
* @return | |||
*/ | |||
public static byte[] getBytes(int data) { | |||
byte[] bytes = new byte[4]; | |||
bytes[0] = (byte) ((data & 0xff000000) >> 24); | |||
bytes[1] = (byte) ((data & 0xff0000) >> 16); | |||
bytes[2] = (byte) ((data & 0xff00) >> 8); | |||
bytes[3] = (byte) (data & 0xff); | |||
return bytes; | |||
} | |||
/** | |||
* 将long整型数值转换为字节数组 | |||
* | |||
* @param data | |||
* @return | |||
*/ | |||
public static byte[] getBytes(long data) { | |||
byte[] bytes = new byte[8]; | |||
bytes[0] = (byte) ((data >> 56) & 0xff); | |||
bytes[1] = (byte) ((data >> 48) & 0xff); | |||
bytes[2] = (byte) ((data >> 40) & 0xff); | |||
bytes[3] = (byte) ((data >> 32) & 0xff); | |||
bytes[4] = (byte) ((data >> 24) & 0xff); | |||
bytes[5] = (byte) ((data >> 16) & 0xff); | |||
bytes[6] = (byte) ((data >> 8) & 0xff); | |||
bytes[7] = (byte) (data & 0xff); | |||
return bytes; | |||
} | |||
/** | |||
* 将float型数值转换为字节数组 | |||
* | |||
* @param data | |||
* @return | |||
*/ | |||
public static byte[] getBytes(float data) { | |||
int intBits = Float.floatToIntBits(data); | |||
return getBytes(intBits); | |||
} | |||
/** | |||
* | |||
* @Title: getBytes | |||
* @Description: 将double型数值转换为字节数组 | |||
* @return byte[] | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static byte[] getBytes(double data) { | |||
long intBits = Double.doubleToLongBits(data); | |||
return getBytes(intBits); | |||
} | |||
/** | |||
* | |||
* @Title: getBytes | |||
* @Description: 将字符串按照charsetName编码格式的字节数组 | |||
* @return byte[] | |||
* @param data 字符串 | |||
* @param charsetName | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static byte[] getBytes(String data, String charsetName) { | |||
Charset charset = Charset.forName(charsetName); | |||
return data.getBytes(charset); | |||
} | |||
/** | |||
* | |||
* @Title: getBytes | |||
* @Description: 将字符串按照GBK编码格式的字节数组 | |||
* @return byte[] | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static byte[] getBytes(String data) { | |||
return getBytes(data, GBK); | |||
} | |||
/** | |||
* | |||
* @Title: getBoolean | |||
* @Description: 将字节数组第0字节转换为布尔值 | |||
* @return boolean | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static boolean getBoolean(byte[] bytes) { | |||
return bytes[0] == 1; | |||
} | |||
/** | |||
* | |||
* @Title: getBoolean | |||
* @Description: 将字节数组的第index字节转换为布尔值 | |||
* @return boolean | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static boolean getBoolean(byte[] bytes, int index) { | |||
return bytes[index] == 1; | |||
} | |||
/** | |||
* | |||
* @Title: getShort | |||
* @Description: 将字节数组前2字节转换为short整型数值 | |||
* @return short | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static short getShort(byte[] bytes) { | |||
return (short) ((0xff00 & (bytes[0] << 8)) | (0xff & bytes[1])); | |||
} | |||
/** | |||
* | |||
* @Title: getShort | |||
* @Description: 将字节数组从startIndex开始的2个字节转换为short整型数值 | |||
* @return short | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static short getShort(byte[] bytes, int startIndex) { | |||
return (short) ((0xff00 & (bytes[startIndex] << 8)) | (0xff & bytes[startIndex + 1])); | |||
} | |||
/** | |||
* | |||
* @Title: getChar | |||
* @Description: 将字节数组前2字节转换为字符 | |||
* @return char | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static char getChar(byte[] bytes) { | |||
return (char) ((0xff00 & (bytes[0] << 8)) | (0xff & bytes[1])); | |||
} | |||
/** | |||
* | |||
* @Title: getChar | |||
* @Description: 将字节数组从startIndex开始的2个字节转换为字符 | |||
* @return char | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static char getChar(byte[] bytes, int startIndex) { | |||
return (char) ((0xff00 & (bytes[startIndex] << 8)) | (0xff & bytes[startIndex + 1])); | |||
} | |||
/** | |||
* | |||
* @Title: getInt | |||
* @Description: 将字节数组前4字节转换为整型数值 | |||
* @return int | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static int getInt(byte[] bytes) { | |||
return (0xff000000 & (bytes[0] << 24) | (0xff0000 & (bytes[1] << 16)) | (0xff00 & (bytes[2] << 8)) | |||
| (0xff & bytes[3])); | |||
} | |||
/** | |||
* | |||
* @Title: getInt | |||
* @Description: 将字节数组从startIndex开始的4个字节转换为整型数值 | |||
* @return int | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static int getInt(byte[] bytes, int startIndex) { | |||
return (0xff000000 & (bytes[startIndex] << 24) | (0xff0000 & (bytes[startIndex + 1] << 16)) | |||
| (0xff00 & (bytes[startIndex + 2] << 8)) | (0xff & bytes[startIndex + 3])); | |||
} | |||
/** | |||
* 将字节数组前8字节转换为long整型数值 | |||
* | |||
* @param bytes | |||
* @return | |||
*/ | |||
public static long getLong(byte[] bytes) { | |||
return (0xff00000000000000L & ((long) bytes[0] << 56) | (0xff000000000000L & ((long) bytes[1] << 48)) | |||
| (0xff0000000000L & ((long) bytes[2] << 40)) | (0xff00000000L & ((long) bytes[3] << 32)) | |||
| (0xff000000L & ((long) bytes[4] << 24)) | (0xff0000L & ((long) bytes[5] << 16)) | |||
| (0xff00L & ((long) bytes[6] << 8)) | (0xffL & (long) bytes[7])); | |||
} | |||
/** | |||
* 将字节数组从startIndex开始的8个字节转换为long整型数值 | |||
* | |||
* @param bytes | |||
* @param startIndex | |||
* @return | |||
*/ | |||
public static long getLong(byte[] bytes, int startIndex) { | |||
return (0xff00000000000000L & ((long) bytes[startIndex] << 56) | |||
| (0xff000000000000L & ((long) bytes[startIndex + 1] << 48)) | |||
| (0xff0000000000L & ((long) bytes[startIndex + 2] << 40)) | |||
| (0xff00000000L & ((long) bytes[startIndex + 3] << 32)) | |||
| (0xff000000L & ((long) bytes[startIndex + 4] << 24)) | |||
| (0xff0000L & ((long) bytes[startIndex + 5] << 16)) | (0xff00L & ((long) bytes[startIndex + 6] << 8)) | |||
| (0xffL & (long) bytes[startIndex + 7])); | |||
} | |||
/** | |||
* 将字节数组前4字节转换为float型数值 | |||
* | |||
* @param bytes | |||
* @return | |||
*/ | |||
public static float getFloat(byte[] bytes) { | |||
return Float.intBitsToFloat(getInt(bytes)); | |||
} | |||
/** | |||
* 将字节数组从startIndex开始的4个字节转换为float型数值 | |||
* | |||
* @param bytes | |||
* @param startIndex | |||
* @return | |||
*/ | |||
public static float getFloat(byte[] bytes, int startIndex) { | |||
byte[] result = new byte[4]; | |||
System.arraycopy(bytes, startIndex, result, 0, 4); | |||
return Float.intBitsToFloat(getInt(result)); | |||
} | |||
/** | |||
* 将字节数组前8字节转换为double型数值 | |||
* | |||
* @param bytes | |||
* @return | |||
*/ | |||
public static double getDouble(byte[] bytes) { | |||
long l = getLong(bytes); | |||
return Double.longBitsToDouble(l); | |||
} | |||
/** | |||
* 将字节数组从startIndex开始的8个字节转换为double型数值 | |||
* | |||
* @param bytes | |||
* @param startIndex | |||
* @return | |||
*/ | |||
public static double getDouble(byte[] bytes, int startIndex) { | |||
byte[] result = new byte[8]; | |||
System.arraycopy(bytes, startIndex, result, 0, 8); | |||
long l = getLong(result); | |||
return Double.longBitsToDouble(l); | |||
} | |||
/** | |||
* 将charsetName编码格式的字节数组转换为字符串 | |||
* | |||
* @param bytes | |||
* @param charsetName | |||
* @return | |||
*/ | |||
public static String getString(byte[] bytes, String charsetName) { | |||
return new String(bytes, Charset.forName(charsetName)); | |||
} | |||
/** | |||
* 将GBK编码格式的字节数组转换为字符串 | |||
* | |||
* @param bytes | |||
* @return | |||
*/ | |||
public static String getString(byte[] bytes) { | |||
return getString(bytes, GBK); | |||
} | |||
/** | |||
* 将16进制字符串转换为字节数组 | |||
* | |||
* @param hex | |||
* @return | |||
*/ | |||
public static byte[] hexStringToBytes(String hex) { | |||
if (hex == null || "".equals(hex)) { | |||
return null; | |||
} | |||
int len = hex.length() / 2; | |||
byte[] result = new byte[len]; | |||
char[] chArr = hex.toCharArray(); | |||
for (int i = 0; i < len; i++) { | |||
int pos = i * 2; | |||
result[i] = (byte) (toByte(chArr[pos]) << 4 | toByte(chArr[pos + 1])); | |||
} | |||
return result; | |||
} | |||
/** | |||
* 将16进制字符串转换为字节数组 | |||
* | |||
* @param hex | |||
* @return | |||
*/ | |||
public static byte[] hexToBytes(String hex) { | |||
if (hex.length() % 2 != 0) | |||
throw new IllegalArgumentException("input string should be any multiple of 2!"); | |||
hex.toUpperCase(); | |||
byte[] byteBuffer = new byte[hex.length() / 2]; | |||
byte padding = 0x00; | |||
boolean paddingTurning = false; | |||
for (int i = 0; i < hex.length(); i++) { | |||
if (paddingTurning) { | |||
char c = hex.charAt(i); | |||
int index = indexOf(hex, c); | |||
padding = (byte) ((padding << 4) | index); | |||
byteBuffer[i / 2] = padding; | |||
padding = 0x00; | |||
paddingTurning = false; | |||
} else { | |||
char c = hex.charAt(i); | |||
int index = indexOf(hex, c); | |||
padding = (byte) (padding | index); | |||
paddingTurning = true; | |||
} | |||
} | |||
return byteBuffer; | |||
} | |||
private static int indexOf(String input, char c) { | |||
int index = ArrayUtils.indexOf(HEX_VOCABLE, c); | |||
if (index < 0) { | |||
throw new IllegalArgumentException("err input:" + input); | |||
} | |||
return index; | |||
} | |||
/** | |||
* 将BCD编码的字节数组转换为字符串 | |||
* | |||
* @param bcds | |||
* @return | |||
*/ | |||
public static String bcdToString(byte[] bcds) { | |||
if (bcds == null || bcds.length == 0) { | |||
return null; | |||
} | |||
byte[] temp = new byte[2 * bcds.length]; | |||
for (int i = 0; i < bcds.length; i++) { | |||
temp[i * 2] = (byte) ((bcds[i] >> 4) & 0x0f); | |||
temp[i * 2 + 1] = (byte) (bcds[i] & 0x0f); | |||
} | |||
StringBuffer res = new StringBuffer(); | |||
for (int i = 0; i < temp.length; i++) { | |||
res.append(ascii[temp[i]]); | |||
} | |||
return res.toString(); | |||
} | |||
/** | |||
* 字节转整形 | |||
* | |||
* @param value | |||
* @return | |||
*/ | |||
public static int bcdToInt(byte value) { | |||
return ((value >> 4) * 10) + (value & 0x0F); | |||
} | |||
/** | |||
* 字节数组转16进制字符串 | |||
* | |||
* @param bs | |||
* @return | |||
*/ | |||
public static String bytesToHex(byte[] bs) { | |||
StringBuilder sb = new StringBuilder(); | |||
for (byte b : bs) { | |||
int high = (b >> 4) & 0x0f; | |||
int low = b & 0x0f; | |||
sb.append(HEX_VOCABLE[high]); | |||
sb.append(HEX_VOCABLE[low]); | |||
} | |||
return sb.toString(); | |||
} | |||
/** | |||
* 字节数组取前len个字节转16进制字符串 | |||
* | |||
* @param bs | |||
* @param len | |||
* @return | |||
*/ | |||
public static String bytesToHex(byte[] bs, int len) { | |||
StringBuilder sb = new StringBuilder(); | |||
for (int i = 0; i < len; i++) { | |||
byte b = bs[i]; | |||
int high = (b >> 4) & 0x0f; | |||
int low = b & 0x0f; | |||
sb.append(HEX_VOCABLE[high]); | |||
sb.append(HEX_VOCABLE[low]); | |||
} | |||
return sb.toString(); | |||
} | |||
/** | |||
* 字节数组偏移offset长度之后的取len个字节转16进制字符串 | |||
* | |||
* @param bs | |||
* @param offset | |||
* @param len | |||
* @return | |||
*/ | |||
public static String bytesToHex(byte[] bs, int offset, int len) { | |||
StringBuilder sb = new StringBuilder(); | |||
for (int i = 0; i < len; i++) { | |||
byte b = bs[offset + i]; | |||
int high = (b >> 4) & 0x0f; | |||
int low = b & 0x0f; | |||
sb.append(HEX_VOCABLE[high]); | |||
sb.append(HEX_VOCABLE[low]); | |||
} | |||
return sb.toString(); | |||
} | |||
/** | |||
* 字节转16进制字符串 | |||
* | |||
* @param bs | |||
* @return | |||
*/ | |||
public static String byteToHex(byte b) { | |||
StringBuilder sb = new StringBuilder(); | |||
int high = (b >> 4) & 0x0f; | |||
int low = b & 0x0f; | |||
sb.append(HEX_VOCABLE[high]); | |||
sb.append(HEX_VOCABLE[low]); | |||
String s = sb.toString(); | |||
if ("".equals(s.substring(0, 1))) { | |||
return s.substring(1); | |||
} else { | |||
return s; | |||
} | |||
} | |||
/** | |||
* 将字节数组取反 | |||
* | |||
* @param src | |||
* @return | |||
*/ | |||
public static String negate(byte[] src) { | |||
if (src == null || src.length == 0) { | |||
return null; | |||
} | |||
byte[] temp = new byte[2 * src.length]; | |||
for (int i = 0; i < src.length; i++) { | |||
byte tmp = (byte) (0xFF ^ src[i]); | |||
temp[i * 2] = (byte) ((tmp >> 4) & 0x0f); | |||
temp[i * 2 + 1] = (byte) (tmp & 0x0f); | |||
} | |||
StringBuffer res = new StringBuffer(); | |||
for (int i = 0; i < temp.length; i++) { | |||
res.append(ascii[temp[i]]); | |||
} | |||
return res.toString(); | |||
} | |||
/** | |||
* 比较字节数组是否相同 | |||
* | |||
* @param a | |||
* @param b | |||
* @return | |||
*/ | |||
public static boolean compareBytes(byte[] a, byte[] b) { | |||
if (a == null || a.length == 0 || b == null || b.length == 0 || a.length != b.length) { | |||
return false; | |||
} | |||
if (a.length == b.length) { | |||
for (int i = 0; i < a.length; i++) { | |||
if (a[i] != b[i]) { | |||
return false; | |||
} | |||
} | |||
} else { | |||
return false; | |||
} | |||
return true; | |||
} | |||
/** | |||
* 只比对指定长度byte | |||
* | |||
* @param a | |||
* @param b | |||
* @param len | |||
* @return | |||
*/ | |||
public static boolean compareBytes(byte[] a, byte[] b, int len) { | |||
if (a == null || a.length == 0 || b == null || b.length == 0 || a.length < len || b.length < len) { | |||
return false; | |||
} | |||
for (int i = 0; i < len; i++) { | |||
if (a[i] != b[i]) { | |||
return false; | |||
} | |||
} | |||
return true; | |||
} | |||
/** | |||
* 将字节数组转换为二进制字符串 | |||
* | |||
* @param items | |||
* @return | |||
*/ | |||
public static String bytesToBinaryString(byte[] items) { | |||
if (items == null || items.length == 0) { | |||
return null; | |||
} | |||
StringBuffer buf = new StringBuffer(); | |||
for (byte item : items) { | |||
buf.append(byteToBinaryString(item)); | |||
} | |||
return buf.toString(); | |||
} | |||
/** | |||
* 将字节转换为二进制字符串 | |||
* | |||
* @param items | |||
* @return | |||
*/ | |||
public static String byteToBinaryString(byte item) { | |||
byte a = item; | |||
StringBuffer buf = new StringBuffer(); | |||
for (int i = 0; i < 8; i++) { | |||
buf.insert(0, a % 2); | |||
a = (byte) (a >> 1); | |||
} | |||
return buf.toString(); | |||
} | |||
/** | |||
* 对数组a,b进行异或运算 | |||
* | |||
* @param a | |||
* @param b | |||
* @return | |||
*/ | |||
public static byte[] xor(byte[] a, byte[] b) { | |||
if (a == null || a.length == 0 || b == null || b.length == 0 || a.length != b.length) { | |||
return null; | |||
} | |||
byte[] result = new byte[a.length]; | |||
for (int i = 0; i < a.length; i++) { | |||
result[i] = (byte) (a[i] ^ b[i]); | |||
} | |||
return result; | |||
} | |||
/** | |||
* 对数组a,b进行异或运算 运算长度len | |||
* | |||
* @param a | |||
* @param b | |||
* @param len | |||
* @return | |||
*/ | |||
public static byte[] xor(byte[] a, byte[] b, int len) { | |||
if (a == null || a.length == 0 || b == null || b.length == 0) { | |||
return null; | |||
} | |||
if (a.length < len || b.length < len) { | |||
return null; | |||
} | |||
byte[] result = new byte[len]; | |||
for (int i = 0; i < len; i++) { | |||
result[i] = (byte) (a[i] ^ b[i]); | |||
} | |||
return result; | |||
} | |||
/** | |||
* 将short整型数值转换为字节数组 | |||
* | |||
* @param num | |||
* @return | |||
*/ | |||
public static byte[] shortToBytes(int num) { | |||
byte[] temp = new byte[2]; | |||
for (int i = 0; i < 2; i++) { | |||
temp[i] = (byte) ((num >>> (8 - i * 8)) & 0xFF); | |||
} | |||
return temp; | |||
} | |||
/** | |||
* 将字节数组转为整型 | |||
* | |||
* @param num | |||
* @return | |||
*/ | |||
public static int bytesToShort(byte[] arr) { | |||
int mask = 0xFF; | |||
int temp = 0; | |||
int result = 0; | |||
for (int i = 0; i < 2; i++) { | |||
result <<= 8; | |||
temp = arr[i] & mask; | |||
result |= temp; | |||
} | |||
return result; | |||
} | |||
/** | |||
* 将整型数值转换为指定长度的字节数组 | |||
* | |||
* @param num | |||
* @return | |||
*/ | |||
public static byte[] intToBytes(int num) { | |||
byte[] temp = new byte[4]; | |||
for (int i = 0; i < 4; i++) { | |||
temp[i] = (byte) ((num >>> (24 - i * 8)) & 0xFF); | |||
} | |||
return temp; | |||
} | |||
/** | |||
* 将整型数值转换为指定长度的字节数组 | |||
* | |||
* @param src | |||
* @param len | |||
* @return | |||
*/ | |||
public static byte[] intToBytes(int src, int len) { | |||
if (len < 1 || len > 4) { | |||
return null; | |||
} | |||
byte[] temp = new byte[len]; | |||
for (int i = 0; i < len; i++) { | |||
temp[len - 1 - i] = (byte) ((src >>> (8 * i)) & 0xFF); | |||
} | |||
return temp; | |||
} | |||
/** | |||
* 将字节数组转换为整型数值 | |||
* | |||
* @param arr | |||
* @return | |||
*/ | |||
public static int bytesToInt(byte[] arr) { | |||
int mask = 0xFF; | |||
int temp = 0; | |||
int result = 0; | |||
for (int i = 0; i < 4; i++) { | |||
result <<= 8; | |||
temp = arr[i] & mask; | |||
result |= temp; | |||
} | |||
return result; | |||
} | |||
/** | |||
* 将long整型数值转换为字节数组 | |||
* | |||
* @param num | |||
* @return | |||
*/ | |||
public static byte[] longToBytes(long num) { | |||
byte[] temp = new byte[8]; | |||
for (int i = 0; i < 8; i++) { | |||
temp[i] = (byte) ((num >>> (56 - i * 8)) & 0xFF); | |||
} | |||
return temp; | |||
} | |||
/** | |||
* 将字节数组转换为long整型数值 | |||
* | |||
* @param arr | |||
* @return | |||
*/ | |||
public static long bytesToLong(byte[] arr) { | |||
int mask = 0xFF; | |||
int temp = 0; | |||
long result = 0; | |||
int len = Math.min(8, arr.length); | |||
for (int i = 0; i < len; i++) { | |||
result <<= 8; | |||
temp = arr[i] & mask; | |||
result |= temp; | |||
} | |||
return result; | |||
} | |||
/** | |||
* 将16进制字符转换为字节 | |||
* | |||
* @param c | |||
* @return | |||
*/ | |||
public static byte toByte(char c) { | |||
byte b = (byte) "0123456789ABCDEF".indexOf(c); | |||
return b; | |||
} | |||
/** | |||
* 功能描述:把两个字节的字节数组转化为整型数据,高位补零,例如:<br/> | |||
* 有字节数组byte[] data = new byte[]{1,2};转换后int数据的字节分布如下:<br/> | |||
* 00000000 00000000 00000001 00000010,函数返回258 | |||
* | |||
* @param lenData | |||
* 需要进行转换的字节数组 | |||
* @return 字节数组所表示整型值的大小 | |||
*/ | |||
public static int bytesToIntWhereByteLengthEquals2(byte lenData[]) { | |||
if (lenData.length != 2) { | |||
return -1; | |||
} | |||
byte fill[] = new byte[] { 0, 0 }; | |||
byte real[] = new byte[4]; | |||
System.arraycopy(fill, 0, real, 0, 2); | |||
System.arraycopy(lenData, 0, real, 2, 2); | |||
int len = byteToInt(real); | |||
return len; | |||
} | |||
/** | |||
* 功能描述:将byte数组转化为int类型的数据 | |||
* | |||
* @param byteVal | |||
* 需要转化的字节数组 | |||
* @return 字节数组所表示的整型数据 | |||
*/ | |||
public static int byteToInt(byte[] byteVal) { | |||
int result = 0; | |||
for (int i = 0; i < byteVal.length; i++) { | |||
int tmpVal = (byteVal[i] << (8 * (3 - i))); | |||
switch (i) { | |||
case 0: | |||
tmpVal = tmpVal & 0xFF000000; | |||
break; | |||
case 1: | |||
tmpVal = tmpVal & 0x00FF0000; | |||
break; | |||
case 2: | |||
tmpVal = tmpVal & 0x0000FF00; | |||
break; | |||
case 3: | |||
tmpVal = tmpVal & 0x000000FF; | |||
break; | |||
} | |||
result = result | tmpVal; | |||
} | |||
return result; | |||
} | |||
public static byte CheckXORSum(byte[] bData) { | |||
byte sum = 0x00; | |||
for (int i = 0; i < bData.length; i++) { | |||
sum ^= bData[i]; | |||
} | |||
return sum; | |||
} | |||
/** | |||
* 从offset开始 将后续长度为len的byte字节转为int | |||
* | |||
* @param data | |||
* @param offset | |||
* @param len | |||
* @return | |||
*/ | |||
public static int bytesToInt(byte[] data, int offset, int len) { | |||
int mask = 0xFF; | |||
int temp = 0; | |||
int result = 0; | |||
len = Math.min(len, 4); | |||
for (int i = 0; i < len; i++) { | |||
result <<= 8; | |||
temp = data[offset + i] & mask; | |||
result |= temp; | |||
} | |||
return result; | |||
} | |||
/** | |||
* byte字节数组中的字符串的长度 | |||
* | |||
* @param data | |||
* @return | |||
*/ | |||
public static int getBytesStringLen(byte[] data) { | |||
int count = 0; | |||
for (byte b : data) { | |||
if (b == 0x00) | |||
break; | |||
count++; | |||
} | |||
return count; | |||
} | |||
/** | |||
* | |||
* @Title: hexString2binaryString | |||
* @Description: 十六进制字符串转二进制字符串 | |||
* @return String | |||
* @author fun | |||
* @date 2019年3月27日 | |||
*/ | |||
public static String hexString2binaryString(String hexString) { | |||
if (hexString == null || hexString.length() % 2 != 0) | |||
return null; | |||
String bString = "", tmp; | |||
for (int i = 0; i < hexString.length(); i++) { | |||
tmp = "0000" + Integer.toBinaryString(Integer.parseInt(hexString.substring(i, i + 1), 16)); | |||
bString += tmp.substring(tmp.length() - 4); | |||
} | |||
return bString; | |||
} | |||
} |
@@ -0,0 +1,688 @@ | |||
package com.inet.ailink.receiver.common.utils; | |||
import org.apache.commons.lang.StringUtils; | |||
import org.apache.commons.lang.time.FastDateFormat; | |||
import java.math.BigDecimal; | |||
import java.text.DateFormat; | |||
import java.text.ParseException; | |||
import java.text.SimpleDateFormat; | |||
import java.util.Calendar; | |||
import java.util.Date; | |||
import java.util.GregorianCalendar; | |||
/** | |||
* @ClassName: DateUtils | |||
* @Description: 日期处理工具类 | |||
* @author david | |||
* @date 2013-8-20 下午3:11:57 | |||
* | |||
*/ | |||
public class DateUtils { | |||
/** | |||
* ISO8601 formatter for date without time zone. The format used is | |||
* <tt>yyyy-MM-dd</tt>. | |||
*/ | |||
public static final FastDateFormat DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd"); | |||
/** | |||
* ISO8601 date format: yyyy-MM-dd | |||
*/ | |||
public static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd"; | |||
public static final String DATE_FORMAT_PATTERN_NO_SEPARATOR = "yyyyMMdd"; | |||
/** | |||
* ISO8601 date-time format: yyyy-MM-dd HH:mm:ss | |||
*/ | |||
public static final String DATETIME_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss"; | |||
/** | |||
* for bet view format: yyyy-MM-dd HH:mm:ss | |||
*/ | |||
public static final String DATETIME_JSVIEW_FORMAT_PATTERN = "yyyy/MM/dd HH:mm:ss"; | |||
public static final String DATETIME_SENDTIME_FORMAT_PATTERN = "yyyyMMddHHmmssSSS"; | |||
/** | |||
* 日期时间格式:yyyy-MM-dd HH:mm,不显示秒 | |||
*/ | |||
public static final String DATETIME_WITHOUT_SECOND_FORMAT_PATTERN = "yyyy-MM-dd HH:mm"; | |||
/** | |||
* 日期时间格式:yyyy-MM-dd HH | |||
*/ | |||
public static final String DATETIME_WITHOUT_MINUTES_FORMAT_PATTERN = "yyyy-MM-dd HH"; | |||
public static final String DATE_TIME_START00 = " 00:00:00"; | |||
public static final String DATE_TIME_END23 = " 23:59:59"; | |||
/** | |||
* 获得当前时间 | |||
*/ | |||
public static Date currentDate() { | |||
return new Date(); | |||
} | |||
public static Date getDate(Long time) { | |||
return new Date(time); | |||
} | |||
public static Long getCurTime() { | |||
return System.currentTimeMillis(); | |||
} | |||
public static Date parse(String str) { | |||
return parse(str, DATE_FORMAT_PATTERN); | |||
} | |||
public static Date parse(String str, String pattern) { | |||
if (StringUtils.isBlank(str)) { | |||
return null; | |||
} | |||
DateFormat parser = new SimpleDateFormat(pattern); | |||
try { | |||
return parser.parse(str); | |||
} catch (ParseException e) { | |||
throw new IllegalArgumentException("Can't parse " + str + " using " + pattern); | |||
} | |||
} | |||
/** | |||
* 根据时间变量返回时间字符串 | |||
*/ | |||
public static String format(Date date, String pattern) { | |||
if (date == null) { | |||
return null; | |||
} | |||
FastDateFormat df = FastDateFormat.getInstance(pattern); | |||
return df.format(date); | |||
} | |||
public static String format(Long time, String pattern) { | |||
if (time == null) { | |||
return null; | |||
} | |||
FastDateFormat df = FastDateFormat.getInstance(pattern); | |||
return df.format(new Date(time)); | |||
} | |||
/** | |||
* return date format is <code>yyyy-MM-dd</code> | |||
*/ | |||
public static String format(Date date) { | |||
return date == null ? null : DATE_FORMAT.format(date); | |||
} | |||
public static Date getEndDateTimeOfCurrentYear() { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(currentDate()); | |||
cal.set(Calendar.MONTH, Calendar.DECEMBER); | |||
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); | |||
cal.set(Calendar.HOUR_OF_DAY, 23); | |||
cal.set(Calendar.MINUTE, 59); | |||
cal.set(Calendar.SECOND, 59); | |||
return cal.getTime(); | |||
} | |||
public static Date getStartDateTimeOfCurrentYear() { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(currentDate()); | |||
cal.set(Calendar.MONTH, Calendar.JANUARY); | |||
cal.set(Calendar.DAY_OF_MONTH, 1); | |||
cal.set(Calendar.HOUR_OF_DAY, 0); | |||
cal.set(Calendar.MINUTE, 0); | |||
cal.set(Calendar.SECOND, 0); | |||
return parse(format(cal.getTime())); | |||
} | |||
public static Date getStartDateTimeOfYear(int year) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.set(Calendar.YEAR, year); | |||
cal.set(Calendar.MONTH, Calendar.JANUARY); | |||
cal.set(Calendar.DAY_OF_MONTH, 1); | |||
cal.set(Calendar.HOUR_OF_DAY, 0); | |||
cal.set(Calendar.MINUTE, 0); | |||
cal.set(Calendar.SECOND, 0); | |||
return parse(format(cal.getTime())); | |||
} | |||
public static Date getEndDateTimeOfYear(int year) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.set(Calendar.YEAR, year); | |||
cal.set(Calendar.MONTH, Calendar.DECEMBER); | |||
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); | |||
cal.set(Calendar.HOUR_OF_DAY, 23); | |||
cal.set(Calendar.MINUTE, 59); | |||
cal.set(Calendar.SECOND, 59); | |||
return cal.getTime(); | |||
} | |||
public static Date getStartTimeOfCurrentDate() { | |||
return getStartTimeOfDate(currentDate()); | |||
} | |||
public static Date getEndTimeOfCurrentDate() { | |||
return getEndTimeOfDate(currentDate()); | |||
} | |||
public static Date getStartTimeOfCurrentMonth() { | |||
return getStartDateTimeOfMonth(DateUtils.currentDate()); | |||
} | |||
public static Date getEndTimeOfCurrentMonth() { | |||
return getEndDateTimeOfMonth(DateUtils.currentDate()); | |||
} | |||
public static Date getStartTimeOfDate(Date date) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(date); | |||
cal.set(Calendar.HOUR_OF_DAY, 0); | |||
cal.set(Calendar.MINUTE, 0); | |||
cal.set(Calendar.SECOND, 0); | |||
return parse(format(cal.getTime())); | |||
} | |||
public static Date getEndTimeOfDate(Date date) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(date); | |||
cal.set(Calendar.HOUR_OF_DAY, 23); | |||
cal.set(Calendar.MINUTE, 59); | |||
cal.set(Calendar.SECOND, 59); | |||
return cal.getTime(); | |||
} | |||
public static Date getSpecialEndTimeOfDate(Date date) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(date); | |||
cal.set(Calendar.HOUR_OF_DAY, 24); | |||
cal.set(Calendar.MINUTE, 00); | |||
cal.set(Calendar.SECOND, 00); | |||
return cal.getTime(); | |||
} | |||
public static Date getStartDateTimeOfMonth(Date date) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(date); | |||
cal.set(Calendar.DAY_OF_MONTH, 1); | |||
cal.set(Calendar.HOUR_OF_DAY, 0); | |||
cal.set(Calendar.MINUTE, 0); | |||
cal.set(Calendar.SECOND, 0); | |||
return parse(format(cal.getTime())); | |||
} | |||
public static Date getStartDateTimeOfMonth(int year, int month) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.set(Calendar.YEAR, year); | |||
cal.set(Calendar.MONTH, month - 1); | |||
cal.set(Calendar.DAY_OF_MONTH, 1); | |||
cal.set(Calendar.HOUR_OF_DAY, 0); | |||
cal.set(Calendar.MINUTE, 0); | |||
cal.set(Calendar.SECOND, 0); | |||
return parse(format(cal.getTime())); | |||
} | |||
public static Date getEndDateTimeOfMonth(Date date) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(date); | |||
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); | |||
cal.set(Calendar.HOUR_OF_DAY, 23); | |||
cal.set(Calendar.MINUTE, 59); | |||
cal.set(Calendar.SECOND, 59); | |||
return cal.getTime(); | |||
} | |||
public static Date addHours(Date date, int hours) { | |||
return add(date, Calendar.HOUR_OF_DAY, hours); | |||
} | |||
public static Date addMinutes(Date date, int minutes) { | |||
return add(date, Calendar.MINUTE, minutes); | |||
} | |||
public static Date addSeconds(Date date, int seconds) { | |||
return add(date, Calendar.SECOND, seconds); | |||
} | |||
public static Date addDays(Date date, int days) { | |||
return add(date, Calendar.DATE, days); | |||
} | |||
public static Date addMonths(Date date, int months) { | |||
return add(date, Calendar.MONTH, months); | |||
} | |||
public static Date addYears(Date date, int years) { | |||
return add(date, Calendar.YEAR, years); | |||
} | |||
private static Date add(Date date, int field, int amount) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(date); | |||
cal.add(field, amount); | |||
return cal.getTime(); | |||
} | |||
public static long calcDateBetween(Date start, Date end) { | |||
if (start == null || end == null) { | |||
return 0; | |||
} | |||
return ((end.getTime() - start.getTime()) / 86400001) + 1; | |||
} | |||
public static long calcHoursBetween(Date start, Date end) { | |||
if (start == null || end == null) { | |||
return 0; | |||
} | |||
return ((end.getTime() - start.getTime()) / (60000 * 60)); | |||
} | |||
public static Double calcHoursDoubleBetween(Date start, Date end) { | |||
if (start == null || end == null) { | |||
return 0d; | |||
} | |||
Double time = ((end.getTime() - start.getTime()) / (60000.0 * 60.0)); | |||
return Double.valueOf(new java.text.DecimalFormat("#.0").format(time)); | |||
} | |||
public static Double calcHoursDouble(Date start, Date end) { | |||
if (start == null || end == null) { | |||
return 0d; | |||
} | |||
// (new BigDecimal(end.getTime()).subtract(new | |||
// BigDecimal(start.getTime()))).divide(new BigDecimal(60000.0*60.0), 7, | |||
// BigDecimal.ROUND_HALF_UP).doubleValue(); | |||
Double time = (new BigDecimal(end.getTime()).subtract(new BigDecimal(start.getTime()))) | |||
.divide(new BigDecimal(60000.0 * 60.0), 7, BigDecimal.ROUND_HALF_UP).doubleValue();// ((end.getTime() - | |||
// start.getTime()) | |||
// / | |||
// (60000.0*60.0)); | |||
return time; | |||
} | |||
public static long calcMinutesBetween(Date start, Date end) { | |||
if (start == null || end == null) { | |||
return 0; | |||
} | |||
return ((end.getTime() - start.getTime()) / 60000); | |||
} | |||
public static long calcSecondsBetween(Date start, Date end) { | |||
if (start == null || end == null) { | |||
return 0; | |||
} | |||
return ((end.getTime() - start.getTime()) / 1000); | |||
} | |||
public static long calcSecondsBetween(Long start, Long end) { | |||
return (end - start) / 1000; | |||
} | |||
/** | |||
* 获得日期是否为星期天。 | |||
* | |||
* @param date 日期 | |||
* @return | |||
*/ | |||
public static boolean isSunday(Date date) { | |||
return getDate(date) == Calendar.SUNDAY; | |||
} | |||
/** | |||
* 获得日期是否为星期一。 | |||
* | |||
* @param date 日期 | |||
* @return | |||
*/ | |||
public static boolean isMonday(Date date) { | |||
return getDate(date) == Calendar.MONDAY; | |||
} | |||
/** | |||
* 获得日期是否为星期二。 | |||
* | |||
* @param date 日期 | |||
* @return | |||
*/ | |||
public static boolean isTuesday(Date date) { | |||
return getDate(date) == Calendar.TUESDAY; | |||
} | |||
/** | |||
* 获得日期是否为星期三。 | |||
* | |||
* @param date 日期 | |||
* @return | |||
*/ | |||
public static boolean isWednesday(Date date) { | |||
return getDate(date) == Calendar.WEDNESDAY; | |||
} | |||
/** | |||
* 获得日期是否为星期四。 | |||
* | |||
* @param date 日期 | |||
* @return | |||
*/ | |||
public static boolean isThursday(Date date) { | |||
return getDate(date) == Calendar.THURSDAY; | |||
} | |||
/** | |||
* 获得日期是否为星期五。 | |||
* | |||
* @param date 日期 | |||
* @return | |||
*/ | |||
public static boolean isFriday(Date date) { | |||
return getDate(date) == Calendar.FRIDAY; | |||
} | |||
/** | |||
* 获得日期是否为星期六。 | |||
* | |||
* @param date 日期 | |||
* @return | |||
*/ | |||
public static boolean isSaturday(Date date) { | |||
return getDate(date) == Calendar.SATURDAY; | |||
} | |||
public static int getDate(Date date) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(date); | |||
return cal.get(Calendar.DAY_OF_WEEK); | |||
} | |||
/** | |||
* 获得相对于今天的昨天的时间。 | |||
* | |||
* @return 昨天此时。 | |||
*/ | |||
public static Date getYesterday() { | |||
return addDays(currentDate(), -1); | |||
} | |||
/** | |||
* 获得月份 | |||
* | |||
* @param date | |||
* @return | |||
*/ | |||
public static int getMonth(Date date) { | |||
Calendar calendar = Calendar.getInstance(); | |||
calendar.setTime(date); | |||
return calendar.get(Calendar.MONTH) + 1; | |||
} | |||
/** | |||
* 获得年份 | |||
* | |||
* @param date | |||
* @return | |||
*/ | |||
public static int getYear(Date date) { | |||
Calendar calendar = Calendar.getInstance(); | |||
calendar.setTime(date); | |||
return calendar.get(Calendar.YEAR); | |||
} | |||
/** | |||
* 获得天 | |||
* | |||
* @param date | |||
* @return | |||
*/ | |||
public static int getDay(Date date) { | |||
Calendar calendar = Calendar.getInstance(); | |||
calendar.setTime(date); | |||
return calendar.get(Calendar.DATE); | |||
} | |||
/** | |||
* 获得天 | |||
* | |||
* @param date | |||
* @return | |||
*/ | |||
public static int getDayOfYear(Date date) { | |||
Calendar calendar = Calendar.getInstance(); | |||
calendar.setTime(date); | |||
return calendar.get(Calendar.DAY_OF_YEAR); | |||
} | |||
/** | |||
* 获得小时 | |||
* | |||
* @param date | |||
* @return | |||
*/ | |||
public static int getHours(Date date) { | |||
Calendar calendar = Calendar.getInstance(); | |||
calendar.setTime(date); | |||
return calendar.get(Calendar.HOUR_OF_DAY); | |||
} | |||
public static int getMinutes(Date date) { | |||
Calendar calendar = Calendar.getInstance(); | |||
calendar.setTime(date); | |||
return calendar.get(Calendar.MINUTE); | |||
} | |||
public static int getSeconds(Date date) { | |||
Calendar calendar = Calendar.getInstance(); | |||
calendar.setTime(date); | |||
return calendar.get(Calendar.SECOND); | |||
} | |||
public static int getMILLISECOND(Date date) { | |||
Calendar calendar = Calendar.getInstance(); | |||
calendar.setTime(date); | |||
return calendar.get(Calendar.MILLISECOND); | |||
} | |||
public static long getTimeDiff(Date beginDate, Date endDate) { | |||
return (endDate.getTime() - beginDate.getTime()) / 1000; | |||
} | |||
public static int getDaysOfMonth(int year, int month) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.set(Calendar.YEAR, year); | |||
cal.set(Calendar.MONTH, month);// 7月 | |||
return cal.getActualMaximum(Calendar.DATE); | |||
} | |||
public static long convertDate2Long(Date date) { | |||
if (date == null) { | |||
return 0l; | |||
} | |||
return date.getTime(); | |||
} | |||
public static Date convertLong2Date(Long unixTimestamp) { | |||
if (unixTimestamp != null) { | |||
return new Date(unixTimestamp); | |||
} | |||
return null; | |||
} | |||
/** | |||
* 判断时间是否在指定的时间范围内。 | |||
* | |||
* @param low | |||
* @param high | |||
* @return | |||
*/ | |||
public static boolean between(Date low, Date high) { | |||
return currentDate().after(low) && currentDate().before(high); | |||
} | |||
public static int getDayValue(Date date) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(date); | |||
int i = cal.get(Calendar.DAY_OF_WEEK); | |||
if (i == 1) { | |||
return 7; | |||
} else { | |||
return i - 1; | |||
} | |||
} | |||
public static boolean isBefore(Date date1, Date date2) { | |||
return date1.getTime() < date2.getTime(); | |||
} | |||
public static Date average(Date date1, Date date2) { | |||
return new Date((date1.getTime() + date2.getTime()) / 2); | |||
} | |||
public static int getDaysOfMonth(Date date) { | |||
Calendar cal = Calendar.getInstance(); | |||
cal.setTime(date); | |||
return cal.get(Calendar.DAY_OF_MONTH); | |||
} | |||
public static int getCurrentRemainingSeconds() { | |||
// *** 计算过期时间 一整天 获取 时:分:秒 | |||
Calendar calendar = Calendar.getInstance(); | |||
int hours = calendar.get(Calendar.HOUR_OF_DAY); // 时 | |||
int minutes = calendar.get(Calendar.MINUTE); // 分 | |||
int seconds = calendar.get(Calendar.SECOND); // 秒 | |||
return 24 * 60 * 60 - hours * 60 * 60 - minutes * 60 - seconds; | |||
} | |||
public static Long getTimeLong(String str) { | |||
return parse(str, DATETIME_FORMAT_PATTERN).getTime(); | |||
} | |||
public static String getStringTodayC() { | |||
Date currentTime = new Date(); | |||
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS"); | |||
String dateString = formatter.format(currentTime); | |||
return dateString; | |||
} | |||
/////////////////////////////////////////////////// | |||
// 引用s https://blog.csdn.net/tz_gx/article/details/25284237 | |||
// s 上月第一天 | |||
public static Date getPreviousMonthDayBegin() { | |||
Calendar lastDate = Calendar.getInstance(); | |||
lastDate.set(Calendar.DATE, 1);// 设为当前月的1号 | |||
lastDate.add(Calendar.MONTH, -1);// 减一个月,变为上月的1号 | |||
return lastDate.getTime(); | |||
} | |||
// s 获得上月最后一天的日期 | |||
public static Date getPreviousMonthDayEnd() { | |||
Calendar lastDate = Calendar.getInstance(); | |||
lastDate.add(Calendar.MONTH, -1);// 减一个月 | |||
lastDate.set(Calendar.DATE, 1);// 把日期设置为当月第一天 | |||
lastDate.roll(Calendar.DATE, -1);// 日期回滚一天,也就是本月最后一天 | |||
return lastDate.getTime(); | |||
} | |||
// s 获取当月第一天 | |||
public static Date getCurrentMonthDayBegin() { | |||
Calendar lastDate = Calendar.getInstance(); | |||
lastDate.set(Calendar.DATE, 1);// 设为当前月的1号 | |||
return lastDate.getTime(); | |||
} | |||
// s 计算当月最后一天,返回字符串 | |||
public static Date getCurrentMonthDayEnd() { | |||
Calendar lastDate = Calendar.getInstance(); | |||
lastDate.set(Calendar.DATE, 1);// 设为当前月的1号 | |||
lastDate.add(Calendar.MONTH, 1);// 加一个月,变为下月的1号 | |||
lastDate.add(Calendar.DATE, -1);// 减去一天,变为当月最后一天 | |||
return lastDate.getTime(); | |||
} | |||
// s 获得本周一的日期 | |||
public static Date getCurrentWeekDayBegin() { | |||
int mondayPlus = getMondayPlus(); | |||
GregorianCalendar currentDate = new GregorianCalendar(); | |||
currentDate.add(GregorianCalendar.DATE, mondayPlus); | |||
return currentDate.getTime(); | |||
} | |||
// s 获得本周星期日的日期 | |||
public static Date getCurrentWeekDayEnd() { | |||
int mondayPlus = getMondayPlus(); | |||
GregorianCalendar currentDate = new GregorianCalendar(); | |||
currentDate.add(GregorianCalendar.DATE, mondayPlus + 6); | |||
Date monday = currentDate.getTime(); | |||
return monday; | |||
} | |||
// s 获得当前日期与本周一相差的天数 | |||
private static int getMondayPlus() { | |||
Calendar cd = Calendar.getInstance(); | |||
// 获得今天是一周的第几天,星期日是第一天,星期二是第二天...... | |||
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK) - 1; // s 因为按中国礼拜一作为第一天所以这里减1 | |||
if (dayOfWeek == 1) { | |||
return 0; | |||
} else { | |||
return 1 - dayOfWeek; | |||
} | |||
} | |||
// s 获得上周星期一的日期 | |||
public static Date getPreviousWeekDayBegin() { | |||
int mondayPlus = getMondayPlus(); | |||
GregorianCalendar currentDate = new GregorianCalendar(); | |||
currentDate.add(GregorianCalendar.DATE, mondayPlus - 7); | |||
return currentDate.getTime(); | |||
} | |||
// s 获得上周星期日的日期 | |||
public static Date getPreviousWeekDayEnd() { | |||
int mondayPlus = getMondayPlus(); | |||
GregorianCalendar currentDate = new GregorianCalendar(); | |||
currentDate.add(GregorianCalendar.DATE, mondayPlus - 1); | |||
return currentDate.getTime(); | |||
} | |||
public static int getAge(Date birthDay){ | |||
Calendar cal = Calendar.getInstance(); | |||
if (cal.before(birthDay)) { //出生日期晚于当前时间,无法计算 | |||
return 0; | |||
} | |||
int yearNow = cal.get(Calendar.YEAR); //当前年份 | |||
int monthNow = cal.get(Calendar.MONTH); //当前月份 | |||
int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期 | |||
cal.setTime(birthDay); | |||
int yearBirth = cal.get(Calendar.YEAR); | |||
int monthBirth = cal.get(Calendar.MONTH); | |||
int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH); | |||
int age = yearNow - yearBirth; //计算整岁数 | |||
if (monthNow <= monthBirth) { | |||
if (monthNow == monthBirth) { | |||
if (dayOfMonthNow < dayOfMonthBirth) age--;//当前日期在生日之前,年龄减一 | |||
}else{ | |||
age--;//当前月份在生日之前,年龄减一 | |||
} | |||
} | |||
return age; | |||
} | |||
/////////////////////////////////// | |||
public static void main(String[] args) { | |||
// System.out.println(getMILLISECOND(new Date())); | |||
System.out.println(format(getPreviousWeekDayEnd())); | |||
} | |||
} |
@@ -0,0 +1,127 @@ | |||
package com.inet.ailink.receiver.common.utils; | |||
import com.fasterxml.jackson.annotation.JsonInclude.Include; | |||
import com.fasterxml.jackson.core.JsonProcessingException; | |||
import com.fasterxml.jackson.databind.DeserializationFeature; | |||
import com.fasterxml.jackson.databind.JavaType; | |||
import com.fasterxml.jackson.databind.ObjectMapper; | |||
import com.fasterxml.jackson.databind.SerializationFeature; | |||
import com.fasterxml.jackson.databind.util.JSONPObject; | |||
import java.io.IOException; | |||
public class JsonMapper { | |||
private ObjectMapper mapper; | |||
public JsonMapper() { | |||
this(null); | |||
} | |||
public JsonMapper(Include include) { | |||
mapper = new ObjectMapper(); | |||
if (include != null) { | |||
mapper.setSerializationInclusion(include); | |||
} | |||
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); | |||
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); | |||
} | |||
public static JsonMapper nonEmptyMapper() { | |||
return new JsonMapper(Include.NON_EMPTY); | |||
} | |||
public static JsonMapper nonDefaultMapper() { | |||
return new JsonMapper(Include.NON_DEFAULT); | |||
} | |||
public static JsonMapper nonAlwaysMapper() { | |||
return new JsonMapper(Include.ALWAYS); | |||
} | |||
public String toJson(Object object) { | |||
try { | |||
return mapper.writeValueAsString(object); | |||
} catch (IOException e) { | |||
return null; | |||
} | |||
} | |||
public <T> T fromMapToObject(Object map, Class<T> cls) { | |||
return this.fromJson(this.toJson(map), cls); | |||
} | |||
public <T> T fromMapToObject(Object map, JavaType cls) { | |||
return this.fromJson(this.toJson(map), cls); | |||
} | |||
public <T> T fromJson(String jsonString, Class<T> clazz) { | |||
if (isEmpty(jsonString)) { | |||
return null; | |||
} | |||
try { | |||
return mapper.readValue(jsonString, clazz); | |||
} catch (IOException e) { | |||
e.printStackTrace(); | |||
return null; | |||
} | |||
} | |||
public <T> T fromJson(String jsonString, JavaType javaType) { | |||
if (isEmpty(jsonString)) { | |||
return null; | |||
} | |||
try { | |||
return (T) mapper.readValue(jsonString, javaType); | |||
} catch (IOException e) { | |||
e.printStackTrace(); | |||
return null; | |||
} | |||
} | |||
public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) { | |||
return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses); | |||
} | |||
public <T> T update(String jsonString, T object) { | |||
try { | |||
return (T) mapper.readerForUpdating(object).readValue(jsonString); | |||
} catch (JsonProcessingException e) { | |||
e.printStackTrace(); | |||
} catch (IOException e) { | |||
e.printStackTrace(); | |||
} | |||
return null; | |||
} | |||
public String toJsonP(String functionName, Object object) { | |||
return toJson(new JSONPObject(functionName, object)); | |||
} | |||
public void enableEnumUseToString() { | |||
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); | |||
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); | |||
} | |||
public ObjectMapper getMapper() { | |||
return mapper; | |||
} | |||
public static boolean isEmpty(String str) { | |||
return str == null || str.length() == 0; | |||
} | |||
} |
@@ -0,0 +1,61 @@ | |||
package com.inet.ailink.receiver.common.utils; | |||
import java.util.ArrayList; | |||
import java.util.List; | |||
public class JsonUtils { | |||
protected static JsonMapper jmapper = JsonMapper.nonEmptyMapper(); | |||
/** | |||
* json数据结构转换对象 | |||
* @param jsonStr | |||
* @param clazz | |||
* @return | |||
*/ | |||
public static <T> T fromJson(String jsonStr,Class<T> clazz){ | |||
return jmapper.fromJson(jsonStr, clazz); | |||
} | |||
/**json数据结构转换List<MyBean> | |||
* @param jsonStr | |||
* @param clazz | |||
* @return | |||
*/ | |||
public static <T> List<T> fromJson2List(String jsonStr,Class<T> clazz){ | |||
return jmapper.fromJson(jsonStr, | |||
JsonMapper.nonDefaultMapper().createCollectionType(List.class, clazz)); | |||
} | |||
/** | |||
* 对象转换json数据结构 | |||
* @param obj | |||
* @return | |||
*/ | |||
public static String toJson(Object obj){ | |||
return jmapper.toJson(obj); | |||
} | |||
public static void main(String[] args){ | |||
/*String s="[{\"level\":\"3\",\"time\":\"1428551739622\"},{\"level\":\"4\",\"time\":\"1428551739623\"}]"; | |||
List<DeviceSignalRecordRequest> ss=fromJson2List(s, DeviceSignalRecordRequest.class); | |||
String sss=toJson(new DeviceSignalRecordRequest()); | |||
System.out.println(ss);*/ | |||
List<String> a=new ArrayList<String>(); | |||
List<String> b=new ArrayList<String>(); | |||
List<List<String>> cc =new ArrayList<List<String>>(); | |||
a.add("11:00"); | |||
a.add("12:00"); | |||
b.add("13:00"); | |||
b.add("14:00"); | |||
cc.add(a); | |||
cc.add(b); | |||
System.out.println(JsonUtils.toJson(a)); | |||
List<String> k= JsonUtils.fromJson2List(JsonUtils.toJson(a),String.class); | |||
for(String s:k){ | |||
System.out.println(s); | |||
} | |||
} | |||
} |
@@ -0,0 +1,279 @@ | |||
package com.inet.ailink.receiver.common.utils; | |||
import com.inet.ailink.receiver.common.enums.Common; | |||
import java.io.UnsupportedEncodingException; | |||
public class TeaUtils { | |||
public static byte[] encrypt(byte[] data, byte[] key) { | |||
int data_len = data.length; // 数据的长度 | |||
if (data_len == 0) { | |||
return new byte[] {}; | |||
} | |||
TeaUtils t = new TeaUtils(); | |||
if (!t.setKey(key)) { | |||
return new byte[] {}; | |||
} | |||
int group_len = 8; | |||
int residues = data_len % group_len; // 余数 | |||
int dlen = data_len - residues; | |||
// 用于储存加密的密文,第一字节为余数的大小 | |||
//int result_len = data_len + 1; | |||
int result_len = data_len; | |||
if (residues > 0) { | |||
result_len += group_len - residues; | |||
} | |||
byte[] result = new byte[result_len]; | |||
//result[0] = (byte)residues; | |||
byte[] plain = new byte[group_len]; | |||
byte[] enc = new byte[group_len]; | |||
for (int i = 0; i < dlen; i += group_len) { | |||
for (int j = 0; j < group_len; j++) { | |||
plain[j] = data[i + j]; | |||
} | |||
enc = t.encrypt_group(plain); | |||
for (int k = 0; k < group_len; k++) { | |||
//result[i + k + 1] = enc[k]; | |||
result[i + k ] = enc[k]; | |||
} | |||
} | |||
if (residues > 0) { | |||
for (int j = 0; j < residues; j++) { | |||
plain[j] = data[dlen + j]; | |||
} | |||
int padding = group_len - residues; | |||
for (int j = 0; j < padding; j++) { | |||
plain[residues + j] = (byte)0x00; | |||
} | |||
enc = t.encrypt_group(plain); | |||
for (int k = 0; k < group_len; k++) { | |||
//result[dlen + k + 1] = enc[k]; | |||
result[dlen + k] = enc[k]; | |||
} | |||
} | |||
return result; | |||
} | |||
public static byte[] decrypt(byte[] data, byte[] key) { | |||
int group_len = 8; | |||
// if (data.length % group_len != 1) { | |||
// return new byte[] {}; | |||
// } | |||
TeaUtils t = new TeaUtils(); | |||
if (!t.setKey(key)) { | |||
return new byte[] {}; | |||
} | |||
//int data_len = data.length - 1, dlen; // 数据的长度 | |||
int data_len = data.length, dlen; // 数据的长度 | |||
dlen = data_len; | |||
//int residues = (int)(data[0]); // 余数 | |||
// if (residues > 0) { | |||
// dlen = data_len - group_len; | |||
// } else { | |||
// dlen = data_len; | |||
// } | |||
//byte[] result = new byte[dlen + residues]; | |||
byte[] result = new byte[dlen]; | |||
byte[] dec = new byte[group_len]; | |||
byte[] enc = new byte[group_len]; | |||
for (int i = 0; i < dlen; i += group_len) { | |||
for (int j = 0; j < group_len; j++) { | |||
//enc[j] = data[i + j + 1]; | |||
enc[j] = data[i + j]; | |||
} | |||
dec = t.decrypt_group(enc); | |||
for (int k = 0; k < group_len; k++) { | |||
result[i + k] = dec[k]; | |||
} | |||
} | |||
// if (residues > 0) { | |||
// for (int j = 0; j < group_len; j++) { | |||
// enc[j] = data[dlen + j + 1]; | |||
// } | |||
// dec = t.decrypt_group(enc); | |||
// for (int k = 0; k < residues; k++) { | |||
// result[dlen + k] = dec[k]; | |||
// } | |||
// } | |||
return result; | |||
} | |||
/** | |||
* 设置密钥 | |||
* @param k 密钥 | |||
* @return 密钥长度为16个byte时, 设置密钥并返回true,否则返回false | |||
*/ | |||
public boolean setKey(byte[] k) { | |||
if(k==null){ | |||
k = Common.TEA_KEY; | |||
} | |||
if (k.length != 16) { | |||
return false; | |||
} | |||
k0 = bytes_to_uint32(new byte[] {k[0], k[1], k[2], k[3]}); | |||
k1 = bytes_to_uint32(new byte[] {k[4], k[5], k[6], k[7]}); | |||
k2 = bytes_to_uint32(new byte[] {k[8], k[9], k[10], k[11]}); | |||
k3 = bytes_to_uint32(new byte[] {k[12], k[13], k[14], k[15]}); | |||
return true; | |||
} | |||
/** | |||
* 设置加密的轮数,默认为32轮 | |||
* @param loops 加密轮数 | |||
* @return 轮数为16、32、64时,返回true,否则返回false | |||
*/ | |||
public boolean setLoops(int loops) { | |||
switch (loops) { | |||
case 16: | |||
case 32: | |||
case 64: | |||
this.loops = loops; | |||
return true; | |||
} | |||
return false; | |||
} | |||
private static long UINT32_MAX = 0xFFFFFFFFL; | |||
private static long BYTE_1 = 0xFFL; | |||
private static long BYTE_2 = 0xFF00L; | |||
private static long BYTE_3 = 0xFF0000L; | |||
private static long BYTE_4 = 0xFF000000L; | |||
private static long delta = 0x9E3779B9L; | |||
private static long k0; | |||
private static long k1; | |||
private static long k2; | |||
private static long k3; | |||
private static int loops = 32; | |||
/** | |||
* 加密一组明文 | |||
* @param v 需要加密的明文 | |||
* @return 返回密文 | |||
*/ | |||
public static byte[] encrypt_group(byte[] v) { | |||
long v0 = bytes_to_uint32(new byte[] {v[0], v[1], v[2], v[3]}); | |||
long v1 = bytes_to_uint32(new byte[] {v[4], v[5], v[6], v[7]}); | |||
long sum = 0L; | |||
long v0_xor_1 = 0L, v0_xor_2 = 0L, v0_xor_3 = 0L; | |||
long v1_xor_1 = 0L, v1_xor_2 = 0L, v1_xor_3 = 0L; | |||
for (int i = 0; i < loops; i++) { | |||
sum = toUInt32(sum + delta); | |||
v0_xor_1 = toUInt32(toUInt32(v1 << 4) + k0); | |||
v0_xor_2 = toUInt32(v1 + sum); | |||
v0_xor_3 = toUInt32((v1 >> 5) + k1); | |||
v0 = toUInt32( v0 + toUInt32(v0_xor_1 ^ v0_xor_2 ^ v0_xor_3) ); | |||
v1_xor_1 = toUInt32(toUInt32(v0 << 4) + k2); | |||
v1_xor_2 = toUInt32(v0 + sum); | |||
v1_xor_3 = toUInt32((v0 >> 5) + k3); | |||
//System.out.printf("%08X\t%08X\t%08X\t%08X\n", i, v0, v0 >> 5, k3); | |||
v1 = toUInt32( v1 + toUInt32(v1_xor_1 ^ v1_xor_2 ^ v1_xor_3) ); | |||
} | |||
byte[] b0 = long_to_bytes(v0, 4); | |||
byte[] b1 = long_to_bytes(v1, 4); | |||
return new byte[] {b0[0], b0[1], b0[2], b0[3], b1[0], b1[1], b1[2], b1[3]}; | |||
} | |||
/** | |||
* 解密一组密文 | |||
* @param v 要解密的密文 | |||
* @return 返回明文 | |||
*/ | |||
public static byte[] decrypt_group(byte[] v) { | |||
long v0 = bytes_to_uint32(new byte[] {v[0], v[1], v[2], v[3]}); | |||
long v1 = bytes_to_uint32(new byte[] {v[4], v[5], v[6], v[7]}); | |||
long sum = 0xC6EF3720L, tmp = 0L; | |||
for (int i = 0; i < loops; i++) { | |||
tmp = toUInt32(toUInt32(v0 << 4) + k2); | |||
v1 = toUInt32( v1 - toUInt32(tmp ^ toUInt32(v0 + sum) ^ toUInt32((v0 >> 5) + k3)) ); | |||
tmp = toUInt32(toUInt32(v1 << 4) + k0); | |||
v0 = toUInt32( v0 - toUInt32(tmp ^ toUInt32(v1 + sum) ^ toUInt32((v1 >> 5) + k1)) ); | |||
sum = toUInt32(sum - delta); | |||
} | |||
byte[] b0 = long_to_bytes(v0, 4); | |||
byte[] b1 = long_to_bytes(v1, 4); | |||
return new byte[] {b0[0], b0[1], b0[2], b0[3], b1[0], b1[1], b1[2], b1[3]}; | |||
} | |||
/** | |||
* 将 long 类型的 n 转为 byte 数组,如果 len 为 4,则只返回低32位的4个byte | |||
* @param n 需要转换的long | |||
* @param len 若为4,则只返回低32位的4个byte,否则返回8个byte | |||
* @return 转换后byte数组 | |||
*/ | |||
private static byte[] long_to_bytes(long n, int len) { | |||
byte a = (byte)((n & BYTE_4) >> 24); | |||
byte b = (byte)((n & BYTE_3) >> 16); | |||
byte c = (byte)((n & BYTE_2) >> 8); | |||
byte d = (byte)(n & BYTE_1); | |||
if (len == 4) { | |||
return new byte[] {a, b, c, d}; | |||
} | |||
byte ha = (byte)(n >> 56); | |||
byte hb = (byte)((n >> 48) & BYTE_1); | |||
byte hc = (byte)((n >> 40) & BYTE_1); | |||
byte hd = (byte)((n >> 32) & BYTE_1); | |||
return new byte[] {ha, hb, hc, hd, a, b, c, d}; | |||
} | |||
/** | |||
* 将4个byte转为 Unsigned Integer 32,以 long 形式返回 | |||
* @param bs 需要转换的字节 | |||
* @return 返回 long,高32位为0,低32位视为Unsigned Integer | |||
*/ | |||
private static long bytes_to_uint32(byte[] bs) { | |||
return ((bs[0]<<24) & BYTE_4) + | |||
((bs[1]<<16) & BYTE_3) + | |||
((bs[2]<<8) & BYTE_2) + | |||
(bs[3] & BYTE_1); | |||
} | |||
/** | |||
* 将long的高32位清除,只保留低32位,低32位视为Unsigned Integer | |||
* @param n 需要清除的long | |||
* @return 返回高32位全为0的long | |||
*/ | |||
private static long toUInt32(long n) { | |||
return n & UINT32_MAX; | |||
} | |||
public static void main(String args[]) throws UnsupportedEncodingException | |||
{ | |||
TeaUtils t = new TeaUtils(); | |||
t.setKey(Common.TEA_KEY); | |||
byte[] old = new byte[]{(byte)0x01,(byte)0x16,(byte)0xA4,(byte)0x28, | |||
(byte)0x32,(byte)0x18,(byte)0x4A,(byte)0x88, | |||
(byte)0x00,(byte)0x00 ,(byte)0x00 ,(byte)0x00, | |||
(byte)0x00 ,(byte)0x00 ,(byte)0x42 ,(byte)0x4D, | |||
(byte)0x10 ,(byte)0x01,(byte)0x0A ,(byte)0x00, | |||
(byte)0x13 ,(byte)0x05 ,(byte)0x07 ,(byte)0xC8}; | |||
/*byte[] old = new byte[] { | |||
0x00, 0x00, 0x00, 0x20, | |||
0x00, 0x00, 0x00, 0x10 | |||
};*/ | |||
byte[] enc = t.encrypt(old,Common.TEA_KEY); | |||
System.out.println( "tea加密:"); | |||
for(byte i : enc) | |||
System.out.print(i + " "); | |||
System.out.println(); | |||
byte[] dec = t.decrypt(enc,Common.TEA_KEY); | |||
System.out.println( "tea解密:"); | |||
for(byte i : dec) | |||
System.out.print(i + " "); | |||
System.out.println(); | |||
} | |||
} |
@@ -0,0 +1,80 @@ | |||
package com.inet.ailink.receiver.common.utils; | |||
import java.io.IOException; | |||
import java.math.BigDecimal; | |||
public class WeightUnitUtils { | |||
public static void main(String arg[]) throws IOException{ | |||
// System.out.println("100kg="+getKg(100,0,0)+"kg");//100kg | |||
// System.out.println("10kg="+getKg(100,0,1)+"kg");//10kg | |||
// System.out.println("1kg="+getKg(100,0,2)+"kg");//1kg | |||
// System.out.println("100.1kg="+getKg(1001,0,1)+"kg");//1kg | |||
// System.out.println("100.5kg="+getKg(1005,0,1)+"kg");//1kg | |||
// System.out.println("100.6kg="+getKg(1006,0,1)+"kg");//1kg | |||
// System.out.println("100.8kg="+getKg(1008,0,1)+"kg");//1kg | |||
// System.out.println("100.11kg="+getKg(10011,0,2)+"kg");//1kg | |||
// System.out.println("100.55kg="+getKg(10055,0,2)+"kg");//1kg | |||
// System.out.println("100.66kg="+getKg(10066,0,2)+"kg");//1kg | |||
// System.out.println("100.88kg="+getKg(10088,0,2)+"kg");//1kg | |||
// System.out.println("100lb="+getKg(100,6,0)+"kg");//100kg | |||
// System.out.println("10lb="+getKg(100,6,1)+"kg");//10kg | |||
// System.out.println("1lb="+getKg(100,6,2)+"kg");//1kg | |||
// System.out.println("100.1lb="+getKg(1001,6,1)+"kg");//1kg | |||
// System.out.println("100.5lb="+getKg(1005,6,1)+"kg");//1kg | |||
// System.out.println("100.6lb="+getKg(1006,6,1)+"kg");//1kg | |||
// System.out.println("100.8lb="+getKg(1008,6,1)+"kg");//1kg | |||
// System.out.println("100.11lb="+getKg(10011,6,2)+"kg");//1kg | |||
// System.out.println("100.55lb="+getKg(10055,6,2)+"kg");//1kg | |||
// System.out.println("100.66lb="+getKg(10066,6,2)+"kg");//1kg | |||
// System.out.println("100.88lb="+getKg(10088,6,2)+"kg");//1kg | |||
// System.out.println("100st="+getKg(100,4,0)+"kg");//100kg | |||
// System.out.println("10st="+getKg(100,4,1)+"kg");//10kg | |||
// System.out.println("1st="+getKg(100,4,2)+"kg");//1kg | |||
// System.out.println("100.1st="+getKg(1001,4,1)+"kg");//1kg | |||
// System.out.println("100.5st="+getKg(1005,4,1)+"kg");//1kg | |||
// System.out.println("100.6st="+getKg(1006,4,1)+"kg");//1kg | |||
// System.out.println("100.8st="+getKg(1008,4,1)+"kg");//1kg | |||
// System.out.println("100.11st="+getKg(10011,4,2)+"kg");//1kg | |||
// System.out.println("100.55st="+getKg(10055,4,2)+"kg");//1kg | |||
// System.out.println("100.66st="+getKg(10066,4,2)+"kg");//1kg | |||
// System.out.println("100.88st="+getKg(10088,4,2)+"kg");//1kg | |||
} | |||
public static BigDecimal getKg(BigDecimal weight, int weightUnit,int weightPoint){ | |||
BigDecimal result = BigDecimal.ZERO; | |||
//小数位转换 | |||
if(weightPoint == 0){ | |||
result = weight; | |||
}else{ | |||
result = weight; | |||
for(int i=0;i<weightPoint;i++){ | |||
result = result.divide(new BigDecimal(10)); | |||
} | |||
} | |||
//单位转化为千克 | |||
switch (weightUnit) { | |||
case 0://千克,不需要转换 | |||
break; | |||
case 1://斤->千克 | |||
result = result.multiply(new BigDecimal(2)); | |||
break; | |||
case 4://st->千克 | |||
//st先转成lb,在转成千克 | |||
result = result.multiply(new BigDecimal(14.0f));//st->lb | |||
result = result.divide(new BigDecimal(2.2046226f),7, BigDecimal.ROUND_HALF_UP);//lb->kg | |||
break; | |||
case 6://lb->kg | |||
result = result.divide(new BigDecimal(2.2046226f),7, BigDecimal.ROUND_HALF_UP); | |||
break; | |||
default: | |||
break; | |||
} | |||
//保留2位小数 | |||
result = result.setScale(2, BigDecimal.ROUND_HALF_UP); | |||
return result; | |||
} | |||
} |