Commit 8b373441 authored by zengtianlai3's avatar zengtianlai3

日志打印格式化和项目代码优化

parent bce0537f
......@@ -14,55 +14,28 @@ import java.util.List;
*/
@Slf4j
public class DeviceDecoder extends ByteToMessageDecoder {
public final int BASE_LENGTH = 2 + 2 + 1+1+1;
public final int BASE_LENGTH = 2 + 2 + 1 + 1 + 1;
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
byte[] packet=new byte[buffer.readableBytes()];
byte[] packet = new byte[buffer.readableBytes()];
buffer.readBytes(packet);
buffer.resetReaderIndex();
Util.DEBUG_HEX("SERVER -> IN",packet,packet.length);
Util.DEBUG_HEX("SERVER -> IN", packet, packet.length);
try {
if (buffer.readableBytes() < BASE_LENGTH) {
return;
}
buffer.markReaderIndex();
short stx = buffer.readShort();//55AA->21930
short stx = buffer.readShort();
short len = buffer.readShortLE();
// char cmd = buffer.readChar();
// char ack = buffer.readChar();//stx:21930,len:52,cmd:退,ack:ꭵ
// short cmd = buffer.readUnsignedByte();
// short ack = buffer.readUnsignedByte();//stx:21930,len:52,cmd:144,ack:0
// byte cmd = buffer.readByte();
// byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0
byte cmd = buffer.readByte();
byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0
// int cmd2 = cmd & 0xFF;
// int ack2 = ack & 0xFF;//stx:21930,len:52,cmd:144,ack:0
// byte[] cmd_bytes = new byte[1];
// buffer.readBytes(cmd_bytes);
// String cmd = new String(cmd_bytes, 0, cmd_bytes.length);
//
// byte[] ack_bytes = new byte[1];
// buffer.readBytes(ack_bytes);
// String ack = new String(ack_bytes, 0, ack_bytes.length);//: stx:21930,len:52,cmd:�,ack:
byte ack = buffer.readByte();
log.debug("stx:" + stx + ",len:" + len + ",cmd:" + cmd + ",ack:" + ack);//stx:21930,len:52,cmd:-112,ack:0
int real_len = len ;
int real_len = len;
int cmd_ack_len = 2;
if (buffer.readableBytes() < real_len - cmd_ack_len+1) {
if (buffer.readableBytes() < real_len - cmd_ack_len + 1) {
buffer.resetReaderIndex();
return;
}
......@@ -74,7 +47,7 @@ public class DeviceDecoder extends ByteToMessageDecoder {
byte end = buffer.readByte();
DeviceProtocol protocol = new DeviceProtocol(stx, len, cmd, ack, content,end);
DeviceProtocol protocol = new DeviceProtocol(stx, len, cmd, ack, content, end);
out.add(protocol);
} catch (Exception e) {
......
......@@ -43,7 +43,6 @@ public class DeviceManager {
}
private void startTcpService() {
log.debug("tcp server start......,prot:" + port);
sessionContexts = new HashMap<String, SessionContext>();
channelInitializer = new DeviceChannelInitializer(handler);
server = new TcpServer(port, channelInitializer);
......
......@@ -22,7 +22,6 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
import java.util.Date;
@Component
@ChannelHandler.Sharable
......@@ -48,7 +47,8 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
String remoteIp = socketAddr.getHostString();
int remotePort = socketAddr.getPort();
DeviceProtocol protocol = (DeviceProtocol) msg;
String channelId = channel.id().asLongText();
log.debug("设备服务器,channelRead0:{},{}", channelId, HexUtil.bytes2hex(protocol.getContent()));
/*
TODO:
1.透传前先进行鉴权
......@@ -57,7 +57,6 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
*/
byte cmd = protocol.getCmd();
int cmdInt = cmd & 0xFF;
log.debug("recev msg " + HexUtil.bytes2hex(protocol.getContent()));
boolean auth = false;
if (cmdInt == Consts.CMD_LICENSE) {
......@@ -80,8 +79,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelRegistered(ctx);
log.debug("client channelRegistered");
log.debug("channel.id().asLongText():" + ctx.channel().id().asLongText());
log.debug("设备服务器,channelRegistered:{}", ctx.channel().id().asLongText());
}
@Override
......@@ -91,8 +89,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
log.debug("client connected,ip:" + clientIp + ",port:" + port);
log.debug("channel.id().asLongText():" + ctx.channel().id().asLongText());
log.debug("设备服务器,channelActive:{}", ctx.channel().id().asLongText());
// TODO 以下为模拟的测试代码
......@@ -129,6 +126,8 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
super.channelInactive(ctx);
SocketChannel channel = (SocketChannel) ctx.channel();
String channelId = channel.id().asLongText();
log.debug("设备服务器,channelInactive:{}", channelId);
DeviceClientInactiveEvent deviceClientInactiveEvent = new DeviceClientInactiveEvent();
deviceClientInactiveEvent.setChannelId(channelId);
eventPublisher.publishEvent(deviceClientInactiveEvent);
......@@ -139,20 +138,16 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelReadComplete(ctx);
log.debug("client channelReadComplete");
log.debug("channel.id().asLongText():" + ctx.channel().id().asLongText());
log.debug("设备服务器,channelReadComplete:{}", ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
super.exceptionCaught(ctx, cause);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
log.debug("设备服务器,exceptionCaught:{}", ctx.channel().id().asLongText());
cause.printStackTrace();
ctx.close();
log.error("client has error,ip:" + clientIp + ",port:" + port);
}
private boolean handlerCheckAuth(SocketChannel channel, String remoteIp, int remotePort, DeviceProtocol protocol) {
......@@ -173,7 +168,7 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
AuthManager authManager = SpringUtil.getBean(AuthManager.class);
boolean license = authManager.auth(appId, sn, sign);
log.debug("auth result " + license + "," + appId + "," + sn + "," + sign);
log.info("设备鉴权信息和结果,{},{},{},{} ", appId, sn, sign, license);
String channelId = channel.id().asLongText();
if (license) {
SessionContext session = new SessionContext();
......@@ -191,7 +186,6 @@ public class DeviceServerHandler extends SimpleChannelInboundHandler<Object> {
deviceManager.putSession(appId, session);
//TODO 创建透传的客户端
log.info("forward client begin start ..." + appId);
CreateForwarClientEvent event = new CreateForwarClientEvent();
event.setAppId(appId);
eventPublisher.publishEvent(event);
......
......@@ -2,8 +2,6 @@ package iot.sixiang.license.event;
import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.forward.ForwardManager;
import iot.sixiang.license.model.SessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -20,7 +18,6 @@ public class DeviceClientBeForcedOfflineEventHandler {
}
// @Async("asyncExecutor")
@EventListener
public void handlerEvent(DeviceClientBeForcedOfflineEvent event) {
String appId = event.getAppId();
......@@ -30,10 +27,10 @@ public class DeviceClientBeForcedOfflineEventHandler {
SocketChannel deviceClientChannel = deviceSessionContext.getClientChannel();
if (deviceClientChannel != null) {
deviceClientChannel.close();
log.info("device client be forced offline success ..." + appId);
log.debug("device client be forced offline success ..." + appId);
}
} else {
log.info("device client be forced offline undo ..." + appId);
log.debug("device client be forced offline undo ..." + appId);
}
}
......
package iot.sixiang.license.event;
import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.model.SessionContext;
import iot.sixiang.license.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
......@@ -21,14 +19,13 @@ public class DeviceClientInactiveEventHandler {
}
// @Async("asyncExecutor")
@EventListener
public void handlerEvent(DeviceClientInactiveEvent event) {
String channelId = event.getChannelId();
SessionContext session = deviceManager.getSessionByChannelId(channelId);
if (session == null) {
log.debug("device client inactive undo ..." );
log.debug("device client inactive undo ...");
return;
} else {
String appId = session.getAppId();
......
......@@ -21,7 +21,6 @@ public class DeviceClientLicenseEventHandler {
}
// @Async("asyncExecutor")
@EventListener
public void handlerEvent(DeviceClientLicenseEvent event) {
String appId = event.getAppId();
......
......@@ -20,7 +20,6 @@ public class ForwardClientBeForcedOfflineEventHandler {
}
// @Async("asyncExecutor")
@EventListener
public void handlerEvent(ForwardClientBeForcedOfflineEvent event) {
String appId = event.getAppId();
......@@ -29,10 +28,10 @@ public class ForwardClientBeForcedOfflineEventHandler {
SocketChannel forwardClientChannel = forwardSessionContext.getClientChannel();
if (forwardClientChannel != null) {
forwardClientChannel.close();
log.info("forward client be forced offline success ..." + appId);
log.debug("forward client be forced offline success ..." + appId);
}
}else {
log.info("forward client be forced offline undo ..." + appId);
} else {
log.debug("forward client be forced offline undo ..." + appId);
}
......
......@@ -3,7 +3,6 @@ package iot.sixiang.license.event;
import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.forward.ForwardManager;
import iot.sixiang.license.model.SessionContext;
import iot.sixiang.license.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
......@@ -22,7 +21,6 @@ public class ForwardClientConnectEventHandler {
}
// @Async("asyncExecutor")
@EventListener
public void handlerEvent(ForwardClientConnectEvent event) {
......@@ -41,11 +39,9 @@ public class ForwardClientConnectEventHandler {
session.setClientChannel(channel);
forwardManager.putSession(appId, session);
forwardManager.putSession(appId,session);
log.debug("forward client connect:"+event);
log.debug("forward client connect:" + event);
}
......
......@@ -23,16 +23,15 @@ public class ForwardClientInactiveEventHandler {
}
// @Async("asyncExecutor")
@EventListener
public void handlerEvent(ForwardClientInactiveEvent event) {
String channelId = event.getChannelId();
SessionContext session = forwardManager.getSessionByChannelId(channelId);
if (session == null) {
log.debug("forward client inactive undo ..." );
log.debug("forward client inactive undo ...");
return;
}else{
} else {
String appId = session.getAppId();
boolean result = forwardManager.removeSessionByChannelId(channelId);
if (result) {
......@@ -40,7 +39,7 @@ public class ForwardClientInactiveEventHandler {
DeviceClientBeForcedOfflineEvent deviceClientBeForcedOfflineEvent = new DeviceClientBeForcedOfflineEvent();
deviceClientBeForcedOfflineEvent.setAppId(appId);
eventPublisher.publishEvent(deviceClientBeForcedOfflineEvent);
log.debug("forward client inactive success ..." );
log.debug("forward client inactive success ...");
}
}
......
......@@ -25,7 +25,6 @@ public class ForwardClientRequestEventHandler {
}
// @Async("asyncExecutor")
@EventListener
public void handlerEvent(ForwardClientRequestEvent event) {
String deviceChannelId = event.getDeviceChannelId();
......@@ -35,7 +34,7 @@ public class ForwardClientRequestEventHandler {
String appId = deviceSessionContext.getAppId();
SessionContext forwardSessionContext = forwardManager.getSessionContextByAppId(appId);
log.info("forward client request:" + appId+","+forwardSessionContext);
log.debug("forward client request:" + appId + "," + forwardSessionContext);
SocketChannel clientChannel = forwardSessionContext.getClientChannel();
clientChannel.writeAndFlush(protocol);
......
......@@ -25,7 +25,6 @@ public class ForwardMessageResponseEventHandler {
}
// @Async("asyncExecutor")
@EventListener
public void handlerEvent(ForwardMessageResponseEvent event) {
String channelId = event.getChannelId();
......@@ -36,17 +35,15 @@ public class ForwardMessageResponseEventHandler {
String appId = forwardSessionContext.getAppId();
SessionContext deviceSessionContext = deviceManager.getSessionContextByAppId(appId);
if(deviceSessionContext!=null){
if (deviceSessionContext != null) {
SocketChannel deviceClientChannel = deviceSessionContext.getClientChannel();
log.info("forward client response..." + appId+",forward session:"+deviceSessionContext);
log.debug("forward client response..." + appId + ",forward session:" + deviceSessionContext);
deviceClientChannel.writeAndFlush(protocol);
}else{
log.info("forward client response undo ..." + appId);
} else {
log.debug("forward client response undo ..." + appId);
}
}
......
......@@ -17,12 +17,11 @@ public class ForwardClient {
ForwardClientHandler handler;
public ForwardClient() {
log.debug("ProxyNodeClient ProxyNodeClientHandler*****" + handler);
}
public void startTcp(String host, int port,String appId) {
log.debug("begin connect the server " + host + ",port " + port);
}
public void startTcp(String host, int port, String appId) {
log.debug("桥接客户端,开始连接桥接服务:{},{},{}", host, port, appId);
ForwardConnectionListener listener = new ForwardConnectionListener();
listener.setAppId(appId);
listener.setHost(host);
......
......@@ -4,15 +4,11 @@ import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceManager;
import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.event.DeviceClientInactiveEvent;
import iot.sixiang.license.event.EventPublisher;
import iot.sixiang.license.event.ForwardClientInactiveEvent;
import iot.sixiang.license.event.ForwardMessageResponseEvent;
import iot.sixiang.license.model.SessionContext;
import iot.sixiang.license.util.HexUtil;
import iot.sixiang.license.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
......@@ -29,7 +25,6 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
public ForwardClientHandler() {
super();
log.debug("ProxyNodeClientHandler ****");
}
@Override
......@@ -41,11 +36,9 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String serverIp = socketAddr.getHostString();
int serverPort = socketAddr.getPort();
log.debug("channelRead0...");
DeviceProtocol protocol = (DeviceProtocol) msg;
log.info("桥接服务器响应:"+ HexUtil.bytes2hex(protocol.getContent()));
String channelId = channel.id().asLongText();
log.debug("桥接客户端,channelRead0:{},{}", channelId, HexUtil.bytes2hex(protocol.getContent()));
ForwardMessageResponseEvent forwardMessageResponseEvent = new ForwardMessageResponseEvent();
forwardMessageResponseEvent.setChannelId(channelId);
......@@ -57,30 +50,17 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
try {
super.channelRegistered(ctx);
log.debug("channelRegistered----------->");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.channelRegistered(ctx);
log.debug("桥接客户端,channelRegistered:{}", ctx.channel().id().asLongText());
}
@Override
public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelActive(ctx);
try {
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("channelActive********"+ctx.channel().id().asLongText());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.debug("桥接客户端,channelActive:{}", ctx.channel().id().asLongText());
}
@Override
......@@ -89,6 +69,8 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
super.channelInactive(ctx);
SocketChannel channel = (SocketChannel) ctx.channel();
String channelId = channel.id().asLongText();
log.debug("桥接客户端,channelInactive:{}", channelId);
ForwardClientInactiveEvent forwardClientInactiveEvent = new ForwardClientInactiveEvent();
forwardClientInactiveEvent.setChannelId(channelId);
eventPublisher.publishEvent(forwardClientInactiveEvent);
......@@ -99,31 +81,22 @@ public class ForwardClientHandler extends SimpleChannelInboundHandler<Object> {
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelReadComplete(ctx);
log.debug("channelReadComplete");
log.debug("桥接客户端,channelReadComplete:{}", ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
super.exceptionCaught(ctx, cause);
InetSocketAddress socketAddr = (InetSocketAddress) ctx.channel().remoteAddress();
String clientIp = socketAddr.getHostString();
int port = socketAddr.getPort();
log.debug("桥接客户端,exceptionCaught:{}", ctx.channel().id().asLongText());
cause.printStackTrace();
ctx.close();
log.error("client has error,ip:" + clientIp + ",port:" + port);
}
@Override
public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
try {
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("userEventTriggered");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.debug("桥接客户端,userEventTriggered:{}", ctx.channel().id().asLongText());
}
}
......@@ -20,14 +20,13 @@ public class ForwardConnectionListener extends BaseConnectionListener {
public void operationComplete(ChannelFuture channelFuture) throws Exception {
AlarmService alarmService = SpringUtil.getBean(AlarmService.class);
if (!channelFuture.isSuccess()) {
//TODO 失败进行告警
//TODO 失败进行告警
log.debug("桥接客户端,连接服务器失败:{},{},{}", this.host, this.port, this.appId);
String remoteIp = this.host;
String remotePort = String.valueOf(this.port);
int typeId = 1;
String title = "连接服器失败";
String content = "连接服务器:" + remoteIp + ":"+ remotePort +"失败";
alarmService.addAlarm(typeId,title,content);
String content = "连接服务器:" + this.host + ":" + this.port + "失败";
alarmService.addAlarm(typeId, title, content);
//TODO forward client连接失败,则强制踢掉设备客户端
......@@ -36,7 +35,7 @@ public class ForwardConnectionListener extends BaseConnectionListener {
EventPublisher eventPublisher = SpringUtil.getBean(EventPublisher.class);
eventPublisher.publishEvent(deviceClientBeForcedOfflineEvent);
} else {
log.debug("桥接客户端,连接服务器成功:{},{},{}", this.host, this.port, this.appId);
OperateManager operateManager = SpringUtil.getBean(OperateManager.class);
operateManager.autoIncrement();
SocketChannel channel = (SocketChannel) channelFuture.channel();
......@@ -50,25 +49,17 @@ public class ForwardConnectionListener extends BaseConnectionListener {
EventPublisher eventPublisher = SpringUtil.getBean(EventPublisher.class);
eventPublisher.publishEvent(forwardClientConnectEvent);
log.debug("Successful connection to the server");
log.info("forward client connect success ..." + appId);
// byte ack2 = 0x01;
short stx = 21930;
byte ack = 0x0;
int len = 3;
byte cmd = 0x1;
byte[] content = new byte[1];
byte[] content = new byte[1];
content[0] = 0x7e;
byte end = 0x1;
// stx:21930,len:76,cmd:1,ack:0
DeviceProtocol protocol = new DeviceProtocol( stx, len, cmd, ack, content,end);
DeviceProtocol protocol = new DeviceProtocol(stx, len, cmd, ack, content, end);
DeviceClientLicenseEvent deviceClientLicenseEvent = new DeviceClientLicenseEvent();
......
......@@ -18,10 +18,10 @@ public class ForwardDecoder extends ByteToMessageDecoder {
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) {
// 可读长度必须大于等于基本长度
try {
byte[] packet=new byte[buffer.readableBytes()];
byte[] packet = new byte[buffer.readableBytes()];
buffer.readBytes(packet);
buffer.resetReaderIndex();
Util.DEBUG_HEX("SERVER -> IN",packet,packet.length);
Util.DEBUG_HEX("SERVER -> IN", packet, packet.length);
if (buffer.readableBytes() < BASE_LENGTH) {
return;
......@@ -36,13 +36,10 @@ public class ForwardDecoder extends ByteToMessageDecoder {
byte cmd = buffer.readByte();
byte ack = buffer.readByte();////stx:21930,len:52,cmd:-112,ack:0
log.debug("stx:" + stx + ",len:" + len);
int real_len = len;//注意,透传前已经去掉了END一个字符
int cmd_ack_len = 2;
if (buffer.readableBytes() < real_len - cmd_ack_len+1) {
if (buffer.readableBytes() < real_len - cmd_ack_len + 1) {
buffer.resetReaderIndex();
return;
}
......@@ -55,14 +52,13 @@ public class ForwardDecoder extends ByteToMessageDecoder {
byte end = buffer.readByte();
log.debug("ForwardDecoder.msg.getLen()...." + real_len);
DeviceProtocol protocol = new DeviceProtocol(stx, real_len, cmd, ack, content,end);
DeviceProtocol protocol = new DeviceProtocol(stx, real_len, cmd, ack, content, end);
out.add(protocol);
} catch (Exception e) {
// TODO Auto-generated catch block
log.error("DeviceDecoder error!");
log.error("Decoder error");
}
}
......
......@@ -13,19 +13,13 @@ public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> {
protected void encode(ChannelHandlerContext tcx, DeviceProtocol msg, ByteBuf out) throws Exception {
try {
// short stx = in.readShort();//55AA->21930
// short len = in.readShortLE();
out.writeShort(msg.getStx());
// out.writeShort(msg.getLen());
out.writeShortLE(msg.getLen());
out.writeByte(msg.getCmd());
out.writeByte(msg.getAck());
log.debug("ForwardEncoder.msg.getLen()...." + msg.getLen());
if (msg.getContent() == null) {
// logger.debug("body数据为空");
// log.debug("body数据为空");
} else {
out.writeBytes(msg.getContent());
}
......@@ -33,7 +27,7 @@ public class ForwardEncoder extends MessageToByteEncoder<DeviceProtocol> {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error("DeviceEncoder error---->");
log.error("Encoder error");
}
}
}
package iot.sixiang.license.net;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
public class MySSLContext {
static Logger logger = LoggerFactory.getLogger(MySSLContext.class.getName());
private static SSLContext sslContext;
public static SSLContext getSSLContext(String serverKeystorePath, String serverKeystorePwd,
String tserverKeystorePath, String serverTrustKeystorePwd) {
try {
KeyStore keyStore = KeyStore.getInstance("JKS");
KeyStore trustKeyStore = KeyStore.getInstance("JKS");
try {
keyStore.load(ClassUtils.getDefaultClassLoader().getResourceAsStream("static/kserver.keystore"),
serverKeystorePwd.toCharArray());
trustKeyStore.load(ClassUtils.getDefaultClassLoader().getResourceAsStream("static/tserver.keystore"),
serverTrustKeystorePwd.toCharArray());
/*
* keyStore.load(new FileInputStream(serverKeystorePath),
* serverKeystorePwd.toCharArray()); trustKeyStore.load(new
* FileInputStream(tserverKeystorePath),
* serverTrustKeystorePwd.toCharArray());
*/
} catch (CertificateException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
try {
keyManagerFactory.init(keyStore, serverKeystorePwd.toCharArray());
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
}
trustManagerFactory.init(trustKeyStore);
sslContext = SSLContext.getInstance("TLS");
try {
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
// sslContext.init(keyManagerFactory.getKeyManagers(),null,
// null);
logger.debug("SSLContext init success");
} catch (KeyManagementException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return sslContext;
}
}
package iot.sixiang.license.net;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;
import java.net.Socket;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
public class MyX509TrustManager extends X509ExtendedTrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1, Socket arg2) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1, SSLEngine arg2) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1, Socket arg2) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1, SSLEngine arg2) throws CertificateException {
// TODO Auto-generated method stub
}
}
package iot.sixiang.license.net;
public class NetMsgSeq {
private static short seq = 1;
public static synchronized short getSeq() {
if (seq > 65535) {
seq = 1;
}
seq++;
return seq;
}
}
......@@ -6,16 +6,11 @@ import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import com.xiezuo.rsretail.node.ConnectionListener;
public class TcpClient {
static Logger logger = LoggerFactory.getLogger(TcpClient.class);
private int port;
private String host;
private int index;
private BaseChannelInitializer channelInitializer;
private BaseConnectionListener connectionListener;
......
......@@ -2,24 +2,17 @@ package iot.sixiang.license.net;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.LinkedHashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TcpServer {
static Logger logger = LoggerFactory.getLogger(TcpServer.class.getName());
private int port;
private BaseChannelInitializer channelInitializer;
public static Map<ChannelId, SocketChannel> clients = new LinkedHashMap<ChannelId, SocketChannel>();
public TcpServer(int port, BaseChannelInitializer channelInitializer) {
this.port = port;
......@@ -33,7 +26,7 @@ public class TcpServer {
//创建两个线程组 bossGroup、workerGroup
EventLoopGroup bossGroup = new NioEventLoopGroup(4);
EventLoopGroup workerGroup = new NioEventLoopGroup(4);
logger.debug("begin open the port:" + port);
log.debug("Tcp服务,开始监听端口:{}",port);
try {
//创建服务端的启动对象,设置参数
ServerBootstrap b = new ServerBootstrap();
......@@ -57,7 +50,7 @@ public class TcpServer {
}
} finally {
logger.debug("close the server");
log.debug("Tcp服务,停止退出");
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
......
......@@ -4,9 +4,6 @@ import io.netty.channel.socket.SocketChannel;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import iot.sixiang.license.consts.Consts;
import iot.sixiang.license.forward.ForwardClientHandler;
import iot.sixiang.license.forward.ForwardDecoder;
import iot.sixiang.license.forward.ForwardEncoder;
import iot.sixiang.license.net.BaseChannelInitializer;
public class OperateChannelInitializer extends BaseChannelInitializer {
......
......@@ -3,7 +3,6 @@ package iot.sixiang.license.operate;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.event.EventPublisher;
import iot.sixiang.license.event.OperateSAMStatusResponseEvent;
......@@ -39,38 +38,24 @@ public class OperateClientHandler extends SimpleChannelInboundHandler<Object> {
@Override
public void channelRegistered(ChannelHandlerContext ctx) {
public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
try {
super.channelRegistered(ctx);
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("channelRegistered "+ctx.channel().id().asLongText());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.channelRegistered(ctx);
log.debug("运维客户端,channelRegistered:{}", ctx.channel().id().asLongText());
}
@Override
public synchronized void channelActive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelActive(ctx);
try {
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("channelActive "+ctx.channel().id().asLongText());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.debug("运维客户端,channelActive:{}", ctx.channel().id().asLongText());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelInactive(ctx);
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("channelInactive "+ctx.channel().id().asLongText());
log.debug("运维客户端,channelInactive:{}", ctx.channel().id().asLongText());
ctx.close();
}
......@@ -78,30 +63,21 @@ public class OperateClientHandler extends SimpleChannelInboundHandler<Object> {
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
// TODO Auto-generated method stub
super.channelReadComplete(ctx);
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("channelReadComplete "+ctx.channel().id().asLongText());
log.debug("运维客户端,channelReadComplete:{}", ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
// TODO Auto-generated method stub
super.exceptionCaught(ctx, cause);
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("exceptionCaught "+ctx.channel().id().asLongText());
log.debug("运维客户端,exceptionCaught:{}", ctx.channel().id().asLongText());
cause.printStackTrace();
ctx.close();
}
@Override
public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
try {
SocketChannel channel = (SocketChannel) ctx.channel();
log.debug("userEventTriggered");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public synchronized void userEventTriggered(ChannelHandlerContext ctx, Object obj) {
log.debug("运维客户端,userEventTriggered:{}", ctx.channel().id().asLongText());
}
}
......@@ -14,17 +14,19 @@ import lombok.extern.slf4j.Slf4j;
public class OperateConnectionListener extends BaseConnectionListener {
@Override
public void operationComplete(ChannelFuture channelFuture) throws Exception {
public void operationComplete(ChannelFuture channelFuture) {
if (!channelFuture.isSuccess()) {
//TODO 失败进行告警
log.info("运维客户端,连接服务器失败:{},{}", this.host, this.port);
AlarmService alarmService = SpringUtil.getBean(AlarmService.class);
String remoteIp = this.host;
String remotePort = String.valueOf(this.port);
int typeId = 1;
String title = "连接服器失败";
String content = "连接服务器:" + remoteIp + ":"+ remotePort +"失败";
alarmService.addAlarm(typeId,title,content);
String content = "连接服务器:" + this.host + ":" + this.port + "失败";
alarmService.addAlarm(typeId, title, content);
} else {
log.info("运维客户端,连接服务器成功:{},{}", this.host, this.port);
//TODO 查询SAM状态
OperateSAMStatusRequestEvent operateSAMStatusQueryEvent = new OperateSAMStatusRequestEvent();
short stx = 21930;
......
......@@ -4,7 +4,6 @@ import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import iot.sixiang.license.device.DeviceProtocol;
import iot.sixiang.license.util.Util;
import lombok.extern.slf4j.Slf4j;
import java.util.List;
......@@ -53,7 +52,7 @@ public class OperateDecoder extends ByteToMessageDecoder {
} catch (Exception e) {
// TODO Auto-generated catch block
log.error(e.getMessage());
log.error("Decoder error");
}
}
......
......@@ -28,7 +28,7 @@ public class OperateEncoder extends MessageToByteEncoder<DeviceProtocol> {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error(e.getMessage());
log.error("Encoder error");
}
}
}
package iot.sixiang.license.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
......@@ -9,37 +7,25 @@ import org.springframework.stereotype.Component;
@Component
public class SpringUtil implements ApplicationContextAware {
static Logger logger = LoggerFactory.getLogger(SpringUtil.class.getName());
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
logger.info(
"========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="
+ SpringUtil.applicationContext + "========");
}
// 获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// // 通过name获取 Bean.
// public static Object getBean(String name) {
// return getApplicationContext().getBean(name);
// }
//
// 通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
//
// // 通过name,以及Clazz返回指定的Bean
// public static <T> T getBean(String name, Class<T> clazz) {
// return getApplicationContext().getBean(name, clazz);
// }
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringUtil.applicationContext == null) {
SpringUtil.applicationContext = applicationContext;
}
}
// 获取applicationContext
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
// 通过class获取Bean.
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
}
\ No newline at end of file
......@@ -2,11 +2,6 @@ package iot.sixiang.license.util;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.InetAddress;
......@@ -19,215 +14,211 @@ import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
@Slf4j
public class Util {
public static boolean Debug=false;
public static void logInit(String path){
}
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){
String hexStr="";
int i=0;
for( i=0;i<datalen;i++){
if((i%16)==0){
log.info(hexStr);
hexStr="";
}
if(Integer.toHexString(data[i]&0xff).length()==1){
hexStr+="0";
}
hexStr+=Integer.toHexString(data[i]&0xff).toUpperCase()+" ";
if((i%16)==15){
for(int j=(i-15);j<=i;j++){
if(data[j]>0x20&&data[j]<=0x7e){
hexStr+=String.valueOf((char)(data[j]&0xff));
}else{
hexStr+='.';
}
}
}
}
if((i%16)!=0){
for(int j=0;j<16;j++){
if(j<(16-(i%16))){
hexStr+="-- ";
}
}
for(int j=(i-(i%16));j<i;j++){
if(data[j]>0x20&&data[j]<=0x7e){
hexStr+=String.valueOf((char)(data[j]&0xff));
}else{
hexStr+='.';
}
}
}
log.info(hexStr);
}
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 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) {
String hexStr = "";
int i = 0;
for (i = 0; i < datalen; i++) {
if ((i % 16) == 0) {
log.debug(hexStr);
hexStr = "";
}
if (Integer.toHexString(data[i] & 0xff).length() == 1) {
hexStr += "0";
}
hexStr += Integer.toHexString(data[i] & 0xff).toUpperCase() + " ";
if ((i % 16) == 15) {
for (int j = (i - 15); j <= i; j++) {
if (data[j] > 0x20 && data[j] <= 0x7e) {
hexStr += String.valueOf((char) (data[j] & 0xff));
} else {
hexStr += '.';
}
}
}
}
if ((i % 16) != 0) {
for (int j = 0; j < 16; j++) {
if (j < (16 - (i % 16))) {
hexStr += "-- ";
}
}
for (int j = (i - (i % 16)); j < i; j++) {
if (data[j] > 0x20 && data[j] <= 0x7e) {
hexStr += String.valueOf((char) (data[j] & 0xff));
} else {
hexStr += '.';
}
}
}
log.debug(hexStr);
}
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 {
......@@ -252,67 +243,66 @@ public class Util {
}
return ipList;
}
public static int CRC16(byte[] p,int offer,int len)
{
//Ԥ�� 1 �� 16 λ�ļĴ���Ϊʮ������FFFF, �ƴ˼Ĵ���Ϊ CRC�Ĵ�����
int crc = 0xFFFF;
int i, j;
for (i = 0; i < len; i++) {
//�ѵ�һ�� 8 λ���������� �� 16 λ�� CRC�Ĵ����ĵ� 8 λ�����, �ѽ������ CRC�Ĵ���
crc = ((crc & 0xFF00) | (crc & 0x00FF) ^ (p[i+offer] & 0xFF));
for (j = 0; j < 8; j++) {
//�� CRC �Ĵ�������������һλ( ����λ)�� 0 ����λ, ��������ƺ���Ƴ�λ
if ((crc & 0x0001) > 0) {
//����Ƴ�λΪ 1, CRC�Ĵ��������ʽA001�������
crc = crc >> 1;
crc = crc ^ 0xA001;
} else
//����Ƴ�λΪ 0,�ٴ�����һλ
crc = crc >> 1;
}
}
return crc;
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 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 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;
}
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