Commit fd93efa6 authored by zengtianlai3's avatar zengtianlai3

代码扫描,部分中低缺陷修改

parent d7a89ecc
...@@ -8,6 +8,7 @@ import iot.sixiang.license.model.vo.AppVo; ...@@ -8,6 +8,7 @@ import iot.sixiang.license.model.vo.AppVo;
import iot.sixiang.license.model.vo.DeviceVo; import iot.sixiang.license.model.vo.DeviceVo;
import iot.sixiang.license.service.ApplyService; import iot.sixiang.license.service.ApplyService;
import iot.sixiang.license.service.DeviceBlackService; import iot.sixiang.license.service.DeviceBlackService;
import iot.sixiang.license.util.CommonUtil;
import iot.sixiang.license.util.HmacUtil; import iot.sixiang.license.util.HmacUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -30,7 +31,7 @@ public class AuthManager { ...@@ -30,7 +31,7 @@ public class AuthManager {
private Map<String, Apply> allApply = null; private Map<String, Apply> allApply = null;
private Map<String, DeviceBlack> deviceBlackMap = null; private Map<Integer, DeviceBlack> deviceBlackMap = null;
public AuthManager() { public AuthManager() {
allApply = new HashMap<>(); allApply = new HashMap<>();
...@@ -48,7 +49,7 @@ public class AuthManager { ...@@ -48,7 +49,7 @@ public class AuthManager {
PageInfoModel<AppVo> records = applyService.getAppList(1, 10000, ""); PageInfoModel<AppVo> records = applyService.getAppList(1, 10000, "");
List<AppVo> appList = records.getResult(); List<AppVo> appList = records.getResult();
for (Apply apply : appList) { for (Apply apply : appList) {
String appId = apply.getAppId().toString(); String appId = apply.getAppId();
allApply.put(appId, apply); allApply.put(appId, apply);
} }
} }
...@@ -58,7 +59,7 @@ public class AuthManager { ...@@ -58,7 +59,7 @@ public class AuthManager {
PageInfoModel<DeviceBlack> records = deviceBlackService.getDeviceBlackList(1, 10000); PageInfoModel<DeviceBlack> records = deviceBlackService.getDeviceBlackList(1, 10000);
List<DeviceBlack> deviceBlackList = records.getResult(); List<DeviceBlack> deviceBlackList = records.getResult();
for (DeviceBlack deviceBlack : deviceBlackList) { for (DeviceBlack deviceBlack : deviceBlackList) {
String deviceId = deviceBlack.getDeviceId().toString(); int deviceId = deviceBlack.getDeviceId();
deviceBlackMap.put(deviceId, deviceBlack); deviceBlackMap.put(deviceId, deviceBlack);
} }
} }
...@@ -81,14 +82,14 @@ public class AuthManager { ...@@ -81,14 +82,14 @@ public class AuthManager {
String appKey = apply.getAppKey(); String appKey = apply.getAppKey();
String input = "app_id=" + appId + "&sn=" + sn; String input = "app_id=" + appId + "&sn=" + sn;
String valSHA1 = HmacUtil.encrypt(input, appKey, HmacUtil.HMAC_SHA1).toUpperCase(); String valSHA1 = HmacUtil.encrypt(input, appKey, HmacUtil.HMAC_SHA1).toUpperCase();
if (sign.equals(valSHA1)) { if (CommonUtil.toUpperCaseByEnglish(sign).equals(CommonUtil.toUpperCaseByEnglish(valSHA1))) {
return true; return true;
} else { } else {
return false; return false;
} }
} }
public synchronized Map<String, DeviceBlack> getDeviceBlack() { public synchronized Map<Integer, DeviceBlack> getDeviceBlack() {
return deviceBlackMap; return deviceBlackMap;
} }
......
...@@ -7,7 +7,12 @@ import org.springframework.beans.factory.annotation.Autowired; ...@@ -7,7 +7,12 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.*; import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component @Component
@Slf4j @Slf4j
...@@ -35,8 +40,13 @@ public class BalanceManager { ...@@ -35,8 +40,13 @@ public class BalanceManager {
if (count == 0) { if (count == 0) {
return null; return null;
} else { } else {
Random random = new Random(); SecureRandom secureRandom = null;
int index = random.nextInt(count); try {
secureRandom = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
log.error("SecureRandom 不可用");
}
int index = secureRandom.nextInt(count);
List<Server> servers = new ArrayList<>(allServers.values()); List<Server> servers = new ArrayList<>(allServers.values());
return servers.get(index); return servers.get(index);
} }
......
...@@ -29,12 +29,7 @@ public class ResourceContrller { ...@@ -29,12 +29,7 @@ public class ResourceContrller {
@MyLog(title = "下载资源", optParam = "#{userId}", businessType = BusinessType.OTHER) @MyLog(title = "下载资源", optParam = "#{userId}", businessType = BusinessType.OTHER)
@ApiImplicitParam(name = "userId",value = "用户Id",required = true, dataType = "int") @ApiImplicitParam(name = "userId",value = "用户Id",required = true, dataType = "int")
public void downloadWorkHourRecordTemplate(HttpServletResponse response, @RequestParam(value = "userId") int userId) { public void downloadWorkHourRecordTemplate(HttpServletResponse response, @RequestParam(value = "userId") int userId) {
resourceManager.downloadDeviceInfoExcle(response, userId);
try {
resourceManager.downloadDeviceInfoExcle(response, userId);
} catch (IOException e) {
e.printStackTrace();
}
} }
} }
...@@ -13,7 +13,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -13,7 +13,7 @@ import lombok.extern.slf4j.Slf4j;
public class DeviceEncoder extends MessageToByteEncoder<DeviceProtocol> { public class DeviceEncoder extends MessageToByteEncoder<DeviceProtocol> {
@Override @Override
protected void encode(ChannelHandlerContext tcx, DeviceProtocol msg, ByteBuf out) throws Exception { protected void encode(ChannelHandlerContext tcx, DeviceProtocol msg, ByteBuf out) {
try { try {
out.writeShort(msg.getStx()); out.writeShort(msg.getStx());
...@@ -22,15 +22,13 @@ public class DeviceEncoder extends MessageToByteEncoder<DeviceProtocol> { ...@@ -22,15 +22,13 @@ public class DeviceEncoder extends MessageToByteEncoder<DeviceProtocol> {
out.writeByte(msg.getCmd()); out.writeByte(msg.getCmd());
out.writeByte(msg.getAck()); out.writeByte(msg.getAck());
if (msg.getContent() == null) { if (msg.getContent() != null) {
// log.debug("body数据为空");
} else {
out.writeBytes(msg.getContent()); out.writeBytes(msg.getContent());
} }
out.writeByte(msg.getEnd()); out.writeByte(msg.getEnd());
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); log.error("解码器异常");
} }
} }
} }
...@@ -25,10 +25,4 @@ public class DeviceProtocol { ...@@ -25,10 +25,4 @@ public class DeviceProtocol {
this.end = end; this.end = end;
} }
@Override
public String toString() {
return "DeviceProtocol [stx=" + stx + ", len=" + len + ",cmd=" + cmd + ",ack=" + ack + ", content="
+ new String(content, 0, content.length) + "]";
}
} }
\ No newline at end of file
...@@ -86,38 +86,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -86,38 +86,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception { public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.channelActive(ctx); super.channelActive(ctx);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
log.debug("设备服务器,channelActive:{}", ctx.channel().id().asLongText()); log.debug("设备服务器,channelActive:{}", ctx.channel().id().asLongText());
// TODO 以下为模拟的测试代码
/*String appId = "123456";
String appKey = "123456";
String token = "123456";
SocketChannel channel = (SocketChannel) ctx.channel();
String channelId = channel.id().asLongText();
boolean license = true;
if (license) {
SessionContext session = new SessionContext();
session.setAppId(appId);
session.setAppKey(appKey);
session.setToken(token);
session.setChannelId(channelId);
session.setClientChannel(channel);
DeviceManager deviceManager = SpringUtil.getBean(DeviceManager.class);
deviceManager.putSession(appId, session);
//TODO 创建透传的客户端
log.info("forward client begin start ..." + appId);
CreateForwarClientEvent event = new CreateForwarClientEvent();
event.setAppId(appId);
eventPublisher.publishEvent(event);
}*/
} }
@Override @Override
...@@ -146,7 +115,6 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -146,7 +115,6 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.exceptionCaught(ctx, cause); super.exceptionCaught(ctx, cause);
log.debug("设备服务器,exceptionCaught:{}", ctx.channel().id().asLongText()); log.debug("设备服务器,exceptionCaught:{}", ctx.channel().id().asLongText());
cause.printStackTrace();
ctx.close(); ctx.close();
} }
...@@ -159,8 +127,10 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> { ...@@ -159,8 +127,10 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
return false; return false;
} }
String decodeInfo = new String(bytes, 0, bytes.length); String decodeInfo = CommonUtil.bytesToStr(bytes);
if (decodeInfo == null) {
return false;
}
JSONObject jsonObject = JSON.parseObject(decodeInfo); JSONObject jsonObject = JSON.parseObject(decodeInfo);
String appId = jsonObject.getString("app_id"); String appId = jsonObject.getString("app_id");
String sn = jsonObject.getString("sn"); String sn = jsonObject.getString("sn");
......
...@@ -6,6 +6,7 @@ import iot.sixiang.license.model.SamInfo; ...@@ -6,6 +6,7 @@ import iot.sixiang.license.model.SamInfo;
import iot.sixiang.license.model.SamMonitor; import iot.sixiang.license.model.SamMonitor;
import iot.sixiang.license.operate.OperateManager; import iot.sixiang.license.operate.OperateManager;
import iot.sixiang.license.service.AlarmService; import iot.sixiang.license.service.AlarmService;
import iot.sixiang.license.util.CommonUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener; import org.springframework.context.event.EventListener;
...@@ -33,7 +34,11 @@ public class OperateSAMStatusResponseEventHandler { ...@@ -33,7 +34,11 @@ public class OperateSAMStatusResponseEventHandler {
public void handlerEvent(OperateSAMStatusResponseEvent event) { public void handlerEvent(OperateSAMStatusResponseEvent event) {
DeviceProtocol protocol = event.getProtocol(); DeviceProtocol protocol = event.getProtocol();
String serverIp = event.getIp(); String serverIp = event.getIp();
String jsonOperateStatus = new String(protocol.getContent(), 0, protocol.getContent().length); String jsonOperateStatus = CommonUtil.bytesToStr(protocol.getContent());
if (jsonOperateStatus == null) {
log.warn("SAM的参数为空或出现异常");
return;
}
List<SamInfo> samInfoList = JSONObject.parseArray(jsonOperateStatus, SamInfo.class); List<SamInfo> samInfoList = JSONObject.parseArray(jsonOperateStatus, SamInfo.class);
int samCount = samInfoList.size(); int samCount = samInfoList.size();
int onlineCount = 0; int onlineCount = 0;
......
...@@ -89,7 +89,6 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> { ...@@ -89,7 +89,6 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.exceptionCaught(ctx, cause); super.exceptionCaught(ctx, cause);
log.debug("桥接客户端,exceptionCaught:{}", ctx.channel().id().asLongText()); log.debug("桥接客户端,exceptionCaught:{}", ctx.channel().id().asLongText());
cause.printStackTrace();
ctx.close(); ctx.close();
} }
......
...@@ -10,7 +10,7 @@ import lombok.extern.slf4j.Slf4j; ...@@ -10,7 +10,7 @@ import lombok.extern.slf4j.Slf4j;
public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> { public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> {
@Override @Override
protected void encode(ChannelHandlerContext tcx, DeviceProtocol msg, ByteBuf out) throws Exception { protected void encode(ChannelHandlerContext tcx, DeviceProtocol msg, ByteBuf out) {
try { try {
out.writeShort(msg.getStx()); out.writeShort(msg.getStx());
...@@ -18,16 +18,13 @@ public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> { ...@@ -18,16 +18,13 @@ public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> {
out.writeByte(msg.getCmd()); out.writeByte(msg.getCmd());
out.writeByte(msg.getAck()); out.writeByte(msg.getAck());
if (msg.getContent() == null) { if (msg.getContent() != null) {
// log.debug("body数据为空");
} else {
out.writeBytes(msg.getContent()); out.writeBytes(msg.getContent());
} }
out.writeByte(msg.getEnd()); out.writeByte(msg.getEnd());
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); log.error("解码器异常");
log.error("Encoder error");
} }
} }
} }
package iot.sixiang.license.handler; package iot.sixiang.license.handler;
import iot.sixiang.license.model.BaseResult; import iot.sixiang.license.model.BaseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
...@@ -9,13 +10,14 @@ import org.springframework.web.bind.annotation.ResponseBody; ...@@ -9,13 +10,14 @@ import org.springframework.web.bind.annotation.ResponseBody;
* Created by m33 on 2022/6/9 11:01 * Created by m33 on 2022/6/9 11:01
*/ */
@ControllerAdvice @ControllerAdvice
@Slf4j
public class GlobalExceptionHandler { public class GlobalExceptionHandler {
//指定出现什么异常执行这个方法 //指定出现什么异常执行这个方法
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)
@ResponseBody //为了返回数据 @ResponseBody //为了返回数据
public BaseResult error(Exception e){ public BaseResult error(Exception e){
e.printStackTrace(); log.error("出现自定义异常,{}" + e.getMessage());
return BaseResult.serverException(); return BaseResult.serverException();
} }
...@@ -23,7 +25,7 @@ public class GlobalExceptionHandler { ...@@ -23,7 +25,7 @@ public class GlobalExceptionHandler {
@ExceptionHandler(IotLicenseException.class) @ExceptionHandler(IotLicenseException.class)
@ResponseBody//为了返回数据 @ResponseBody//为了返回数据
public BaseResult error(IotLicenseException e){ public BaseResult error(IotLicenseException e){
e.printStackTrace(); log.error("出现自定义异常,{}" + e.getMsg());
return BaseResult.failed().msg(e.getMsg()).code(e.getCode()); return BaseResult.failed().msg(e.getMsg()).code(e.getCode());
} }
} }
...@@ -6,8 +6,9 @@ import io.netty.channel.ChannelOption; ...@@ -6,8 +6,9 @@ import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup; import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TcpClient { public class TcpClient {
private int port; private int port;
private String host; private String host;
...@@ -39,7 +40,7 @@ public class TcpClient { ...@@ -39,7 +40,7 @@ public class TcpClient {
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); log.error("Tcp客户端异常,端口:{}",port);
} }
} }
......
...@@ -46,7 +46,7 @@ public class TcpServer { ...@@ -46,7 +46,7 @@ public class TcpServer {
f.channel().closeFuture().sync(); f.channel().closeFuture().sync();
} catch (InterruptedException e) { } catch (InterruptedException e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); log.error("Tcp服务异常,端口:{}",port);
} }
} finally { } finally {
......
...@@ -71,7 +71,6 @@ public class OperateClientHandler extends SimpleChannelInboundHandler<Object> { ...@@ -71,7 +71,6 @@ public class OperateClientHandler extends SimpleChannelInboundHandler<Object> {
// TODO Auto-generated method stub // TODO Auto-generated method stub
super.exceptionCaught(ctx, cause); super.exceptionCaught(ctx, cause);
log.debug("运维客户端,exceptionCaught:{}", ctx.channel().id().asLongText()); log.debug("运维客户端,exceptionCaught:{}", ctx.channel().id().asLongText());
cause.printStackTrace();
ctx.close(); ctx.close();
} }
......
...@@ -19,16 +19,13 @@ public class OperateEncoder extends MessageToByteEncoder<DeviceProtocol> { ...@@ -19,16 +19,13 @@ public class OperateEncoder extends MessageToByteEncoder<DeviceProtocol> {
out.writeByte(msg.getCmd()); out.writeByte(msg.getCmd());
out.writeByte(msg.getAck()); out.writeByte(msg.getAck());
if (msg.getContent() == null) { if (msg.getContent() != null) {
// log.debug("body数据为空");
} else {
out.writeBytes(msg.getContent()); out.writeBytes(msg.getContent());
} }
out.writeByte(msg.getEnd()); out.writeByte(msg.getEnd());
} catch (Exception e) { } catch (Exception e) {
// TODO Auto-generated catch block // TODO Auto-generated catch block
e.printStackTrace(); log.error("解码器异常");
log.error("Encoder error");
} }
} }
} }
...@@ -22,7 +22,7 @@ public class ResourceManager { ...@@ -22,7 +22,7 @@ public class ResourceManager {
@Autowired @Autowired
ResourceService resourceService; ResourceService resourceService;
public void downloadDeviceInfoExcle(HttpServletResponse response, int userId) throws IOException { public void downloadDeviceInfoExcle(HttpServletResponse response, int userId){
OutputStream os = null; OutputStream os = null;
HSSFWorkbook wb = null; HSSFWorkbook wb = null;
try { try {
...@@ -113,13 +113,17 @@ public class ResourceManager { ...@@ -113,13 +113,17 @@ public class ResourceManager {
} }
wb.write(os); wb.write(os);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); log.error("Excel表格信息下载异常,{}",e.getMessage());
} finally { } finally {
if (os != null) { try {
os.close(); if (os != null) {
} os.close();
if (wb != null) { }
wb.close(); if (wb != null) {
wb.close();
}
} catch (IOException e) {
log.error("Excel表格信息下载异常,{}",e.getMessage());
} }
} }
} }
......
...@@ -18,8 +18,8 @@ public class CodeGenerator { ...@@ -18,8 +18,8 @@ public class CodeGenerator {
// 2、全局配置 // 2、全局配置
GlobalConfig gc = new GlobalConfig(); GlobalConfig gc = new GlobalConfig();
// String projectPath = System.getProperty("user.dir"); // String projectPath = System.getProperty("user.dir");
gc.setOutputDir("C:\\Users\\Administrator\\IdeaProjects\\ioc_sixiang_license\\license" + "/src/main/java"); gc.setOutputDir("D:\\zengtianlai\\test2\\ioc_sixiang_license\\license" + "/src/main/java");
gc.setAuthor("m33"); gc.setAuthor("lai");
gc.setOpen(false); //生成后是否打开资源管理器 gc.setOpen(false); //生成后是否打开资源管理器
gc.setFileOverride(false); //重新生成时文件是否覆盖 gc.setFileOverride(false); //重新生成时文件是否覆盖
gc.setServiceName("%sService"); //去掉Service接口的首字母I gc.setServiceName("%sService"); //去掉Service接口的首字母I
...@@ -47,7 +47,7 @@ public class CodeGenerator { ...@@ -47,7 +47,7 @@ public class CodeGenerator {
// 5、策略配置 // 5、策略配置
StrategyConfig strategy = new StrategyConfig(); StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("monitor"); strategy.setInclude("sys_oper_log");
strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略 strategy.setNaming(NamingStrategy.underline_to_camel);//数据库表映射到实体的命名策略
strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀 strategy.setTablePrefix(pc.getModuleName() + "_"); //生成实体时去掉表前缀
......
package iot.sixiang.license.util; package iot.sixiang.license.util;
import java.io.ByteArrayInputStream; import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.io.File; import java.io.*;
import java.io.IOException; import java.security.NoSuchAlgorithmException;
import java.io.ObjectInputStream; import java.security.SecureRandom;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@Slf4j
public class CommonUtil { public class CommonUtil {
/**
* 得到一个字符串形式的格式化UUID
*
* @return
*/
public static String getStrUUID() {
return UUID.randomUUID().toString();
// return UUID.randomUUID().toString().replace("-", "");
}
/** /**
* 随机生成指定长度的字符串 * 随机生成指定长度的字符串
...@@ -39,10 +24,15 @@ public class CommonUtil { ...@@ -39,10 +24,15 @@ public class CommonUtil {
int count = 0; int count = 0;
char[] str = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', char[] str = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
StringBuffer pwd = new StringBuffer(""); StringBuilder pwd = new StringBuilder("");
Random r = new Random(); SecureRandom secureRandom = null;
try {
secureRandom = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
log.error("随机生成字符串失败");
}
while (count < length) { while (count < length) {
i = Math.abs(r.nextInt(maxNum)); i = Math.abs(secureRandom.nextInt(maxNum));
if (i >= 0 && i < str.length) { if (i >= 0 && i < str.length) {
pwd.append(str[i]); pwd.append(str[i]);
count++; count++;
...@@ -51,33 +41,7 @@ public class CommonUtil { ...@@ -51,33 +41,7 @@ public class CommonUtil {
return pwd.toString(); return pwd.toString();
} }
/*
* 获取某路径下所有文件名
*/
public static List<String> getAllFilesName(String directoryPath) {
List<String> list = new ArrayList<String>();
File baseFile = new File(directoryPath);
if (baseFile.isFile() || !baseFile.exists()) {
return list;
}
File[] files = baseFile.listFiles();
for (File file : files) {
if (!file.isDirectory()) {
list.add(file.getName());
}
}
return list;
}
public static boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
} else {
return true;
}
}
public static String getSystemTime() { public static String getSystemTime() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
...@@ -85,158 +49,29 @@ public class CommonUtil { ...@@ -85,158 +49,29 @@ public class CommonUtil {
return time; return time;
} }
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T obj) {
T cloneObj = null;
try {
// 写入字节流
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream obs = new ObjectOutputStream(out);
obs.writeObject(obj);
obs.close();
// 分配内存,写入原始对象,生成新对象 public static boolean regularMessage(String message) {
ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray()); String regex = "^[0-9a-zA-Z_]{1,}$";
ObjectInputStream ois = new ObjectInputStream(ios); return message.matches(regex);
// 返回生成的新对象
cloneObj = (T) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
return cloneObj;
} }
@SuppressWarnings("unchecked") public static String toUpperCaseByEnglish(String message) {
public static <T> List<T> listClone(List<T> obj) {
List<T> cloneObj = null;
ByteArrayOutputStream out = null;
ObjectOutputStream obs = null;
ByteArrayInputStream ios = null;
ObjectInputStream ois = null;
try {
out = new ByteArrayOutputStream();
obs = new ObjectOutputStream(out);
obs.writeObject(obj);
ios = new ByteArrayInputStream(out.toByteArray());
ois = new ObjectInputStream(ios);
cloneObj = (List<T>) ois.readObject(); return message.toUpperCase(Locale.ENGLISH);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ois != null) {
ois.close();
}
if (ios != null) {
ios.close();
}
if (obs != null) {
obs.close();
}
if (out != null) {
out.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return cloneObj;
} }
/** public static String bytesToStr(byte[] bytes) {
* 冒泡排序,从小到大排序 String str = null;
* if (bytes == null) {
* @param nums return str;
* @return } else {
*/ try {
public static double[] bubbleSort(double[] nums) { str = new String(bytes, 0, bytes.length, "utf-8");
} catch (UnsupportedEncodingException e) {
for (int i = 0; i < nums.length; i++) { log.error("数组转换成字符串异常,{}", e.getMessage());
for (int j = 0; j < nums.length - 1 - i; j++) {
if (nums[j] > nums[j + 1]) {
double temp = nums[j + 1];
nums[j + 1] = nums[j];
nums[j] = temp;
}
}
}
return nums;
}
public static int[] bubbleSort(int[] nums) {
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums.length - 1 - i; j++) {
if (nums[j] > nums[j + 1]) {
int temp = nums[j + 1];
nums[j + 1] = nums[j];
nums[j] = temp;
}
}
}
return nums;
}
/**
* 二分查找算法,查找有序数组中与目标值的绝对值是最小的
*
* @param target
* 目标值
* @param order_numbers
* 有序数组
* @return
*/
public static double findLeastABSofNumber(double target, double[] order_numbers) {
int left;
int right;
int mid;
left = 0;
right = order_numbers.length - 1;
while (left < right) {
mid = left + (right - left) / 2;
if (order_numbers[mid] - target == 0)
return order_numbers[mid];
else if (order_numbers[mid] > target) {
right = mid;
} else {
left = mid;
}
if (right - left == 1) {
double subtractAbsleft = Math.abs(order_numbers[left] - target);
double subtractAbsright = Math.abs(order_numbers[right] - target);
return subtractAbsleft < subtractAbsright ? order_numbers[left] : order_numbers[right];
}
}
return 0;
}
/**
* 判断一个int数值是否在List里面
*
* @param targetList
* @param source
* @return
*/
public static boolean findsourceInList(List<Integer> targetList, int source) {
boolean result = false;
for (Integer target : targetList) {
if (target == source) {
result = true;
break;
} }
return str;
} }
return result;
}
public static boolean regularMessage(String message) {
String regex = "^[a-z0-9A-Z]+$";
regex = "^[0-9a-zA-Z_]{1,}$";
return message.matches(regex);
} }
} }
package iot.sixiang.license.util; package iot.sixiang.license.util;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.Mac; import javax.crypto.Mac;
import javax.crypto.SecretKey; import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@Slf4j
public class HmacUtil { public class HmacUtil {
//加密算法 //加密算法
public static final String HMAC_SHA1 = "HmacSHA1"; public static final String HMAC_SHA1 = "HmacSHA1";
...@@ -41,32 +42,11 @@ public class HmacUtil { ...@@ -41,32 +42,11 @@ public class HmacUtil {
byte[] encryptByte = mac.doFinal(text); byte[] encryptByte = mac.doFinal(text);
cipher = bytesToHexStr(encryptByte); cipher = bytesToHexStr(encryptByte);
} catch (NoSuchAlgorithmException | InvalidKeyException e) { } catch (NoSuchAlgorithmException | InvalidKeyException e) {
e.printStackTrace(); log.error("加密算法出现异常,{}", e.getMessage());
} }
return cipher; return cipher;
} }
public static String getSha1(String str) {
char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f'};
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}
/** /**
* byte数组转16进制字符串 * byte数组转16进制字符串
...@@ -85,30 +65,4 @@ public class HmacUtil { ...@@ -85,30 +65,4 @@ public class HmacUtil {
} }
return hexStr.toString(); return hexStr.toString();
} }
public static String getSha1_1(String input) {
String mySignature;
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(input.getBytes());
byte[] digest = md.digest();
StringBuffer hexstr = new StringBuffer();
String shaHex = "";
for (int i = 0; i < digest.length; i++) {
shaHex = Integer.toHexString(digest[i] & 0xFF);
if (shaHex.length() < 2) {
hexstr.append(0);
}
hexstr.append(shaHex);
}
mySignature = hexstr.toString();
} catch (NoSuchAlgorithmException e) {
return "签名验证错误";
}
return mySignature;
}
} }
\ No newline at end of file
...@@ -2,128 +2,32 @@ package iot.sixiang.license.util; ...@@ -2,128 +2,32 @@ package iot.sixiang.license.util;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
@Slf4j @Slf4j
public class Util { public class Util {
public static boolean Debug = false;
public static byte asciiToByte(byte ascii) {
byte ret;
if (ascii >= 'A') {
ret = (byte) ((ascii - 'A') + 0X0A);
ret &= 0x0f;
return ret;
} else {
ret = (byte) (ascii - (byte) 0x30);
ret = (byte) (ret & 0x0f);
return ret;
}
}
public static byte byteToAscii(byte data) {
byte ret = 0x0f;
if (data >= 0X0A) {
ret = (byte) ((data - 0X0A) + 'A');
} else {
ret = (byte) (data + '0');
}
return ret;
}
public static int AsciiToHexByte(byte[] dst, byte[] src) {
if (src.length == 0) {
return 0;
}
if ((src.length % 2) != 0) {
return 0;
}
for (int i = 0; i < src.length; ) {
dst[i / 2] = (byte) (asciiToByte(src[i]) << 4);
dst[i / 2] += asciiToByte(src[i + 1]);
i += 2;
}
return src.length / 2;
}
public static int AsciiToHexByte(byte[] dst, int dstOffset, byte[] src, int srcOffset, int len) {
if (len == 0) {
return 0;
}
if ((len % 2) != 0) {
return 0;
}
for (int i = 0; i < len; ) {
dst[(i / 2) + dstOffset] = (byte) (asciiToByte(src[i + srcOffset]) << 4);
dst[(i / 2) + dstOffset] += asciiToByte(src[i + 1 + srcOffset]);
i += 2;
}
return len / 2;
}
public static int HexToAsciiByte(byte[] dst, byte[] src) {
for (int i = 0; i < src.length; i++) {
dst[i * 2] = byteToAscii((byte) ((src[i] >> 4) & 0x0f));
dst[(i * 2) + 1] = byteToAscii((byte) (src[i] & 0x0f));
}
return src.length * 2;
}
public static int IndexOfByte(byte[] src, int offer, int len, byte data) {
for (int i = offer; i < len; i++) {
if (data == src[i]) {
return i;
}
}
return len;
}
public static void DEBUG_HEX(String tag, byte[] data, int datalen) { public static void DEBUG_HEX(String tag, byte[] data, int datalen) {
String hexStr = ""; StringBuilder hexStr = new StringBuilder();
int i = 0; int i = 0;
for (i = 0; i < datalen; i++) { for (i = 0; i < datalen; i++) {
if ((i % 16) == 0) { if ((i % 16) == 0) {
log.debug(hexStr); hexStr.append("");
hexStr = "";
} }
if (Integer.toHexString(data[i] & 0xff).length() == 1) { if (Integer.toHexString(data[i] & 0xff).length() == 1) {
hexStr += "0";
hexStr.append("0");
} }
hexStr += Integer.toHexString(data[i] & 0xff).toUpperCase() + " "; hexStr.append(Integer.toHexString(data[i] & 0xff).toUpperCase() + " ");
if ((i % 16) == 15) { if ((i % 16) == 15) {
for (int j = (i - 15); j <= i; j++) { for (int j = (i - 15); j <= i; j++) {
if (data[j] > 0x20 && data[j] <= 0x7e) { if (data[j] > 0x20 && data[j] <= 0x7e) {
hexStr += String.valueOf((char) (data[j] & 0xff)); hexStr.append(String.valueOf((char) (data[j] & 0xff)));
} else { } else {
hexStr += '.'; hexStr.append('.');
} }
} }
...@@ -133,176 +37,20 @@ public class Util { ...@@ -133,176 +37,20 @@ public class Util {
for (int j = 0; j < 16; j++) { for (int j = 0; j < 16; j++) {
if (j < (16 - (i % 16))) { if (j < (16 - (i % 16))) {
hexStr += "-- "; hexStr.append("-- ");
} }
} }
for (int j = (i - (i % 16)); j < i; j++) { for (int j = (i - (i % 16)); j < i; j++) {
if (data[j] > 0x20 && data[j] <= 0x7e) { if (data[j] > 0x20 && data[j] <= 0x7e) {
hexStr += String.valueOf((char) (data[j] & 0xff)); hexStr.append(String.valueOf((char) (data[j] & 0xff)));
} else { } else {
hexStr += '.'; hexStr.append('.');
} }
} }
} }
log.debug(hexStr); log.debug(hexStr.toString());
} }
public static void INFO(String tag, String content) {
if (!Debug) {
return;
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("I-[" + df.format(new Date()) + "][" + tag + "]:" + content);
}
public static void DEBUG(String tag, String content) {
if (!Debug) {
return;
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("D-[" + df.format(new Date()) + "][" + tag + "]:" + content);
}
public static void ERROR(String tag, Object content) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println("E-[" + df.format(new Date()) + "][" + tag + "]:" + content);
if (content instanceof Exception) {
StackTraceElement stack[] = ((Exception) content).getStackTrace();
for (int i = 0; i < stack.length; i++) {
StackTraceElement s = stack[i];
System.out.format("Class:%d\t%s\n", i, s.getClass());//������
System.out.format("ClassName:%d\t%s\n", i, s.getClassName());//����
System.out.format("MethodName:%d\t%s\n", i, s.getMethodName());//������
System.out.format("FileName:%d\t%s\n", i, s.getFileName());//�ļ���
System.out.format("LineNumber:%d\t%s\n", i, s.getLineNumber());//����
System.out.println("-------------------------------------------");//����
}
}
}
public static String HexToStr(byte[] data, int offset, int length, boolean space) {
String hexStr = "";
for (int i = offset; i < (length + offset); i++) {
if (Integer.toHexString(data[i] & 0xff).length() == 1) {
hexStr += "0";
}
hexStr += Integer.toHexString(data[i] & 0xff).toUpperCase();
if (space) {
hexStr += " ";
}
}
return hexStr;
}
public static List<String> getLocalIPList() {
List<String> ipList = new ArrayList<String>();
try {
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
NetworkInterface networkInterface;
Enumeration<InetAddress> inetAddresses;
InetAddress inetAddress;
String ip;
while (networkInterfaces.hasMoreElements()) {
networkInterface = networkInterfaces.nextElement();
inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
inetAddress = inetAddresses.nextElement();
if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4
ip = inetAddress.getHostAddress();
ipList.add(ip);
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return ipList;
}
public static int CRC16(byte[] p, int offer, int len) {
int crc = 0xFFFF;
int i, j;
for (i = 0; i < len; i++) {
crc = ((crc & 0xFF00) | (crc & 0x00FF) ^ (p[i + offer] & 0xFF));
for (j = 0; j < 8; j++) {
if ((crc & 0x0001) > 0) {
crc = crc >> 1;
crc = crc ^ 0xA001;
} else
crc = crc >> 1;
}
}
return crc;
}
public static String UnicodeToUTF8(String content) {
try {
return new String(content.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static String splitLineString(String content, int lineLength) {
String tmp = "";
int offset = 0;
int length = content.length();
while (length > 0) {
if (length < lineLength) {
tmp += content.substring(offset) + "\n";
length = 0;
} else {
tmp += content.substring(offset, lineLength + offset) + "\n";
offset += lineLength;
length -= lineLength;
}
}
return tmp;
}
public static byte[] getSHA256(byte[] content) {
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(content);
return messageDigest.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment