Commit 81f2091a by tiger

ocpp16

1 parent 3d31b918
Showing 79 changed files with 4788 additions and 90 deletions
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.com.glsx.charging</groupId>
<artifactId>platform-charging-server</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<description>Microservice Scaffolding Project Base on Spring Cloud</description>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>cn.com.glsx.charging</groupId>
<artifactId>platform-charging-server</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<description>Microservice Scaffolding Project Base on Spring Cloud</description>
<artifactId>platform-charging</artifactId>
<artifactId>platform-charging</artifactId>
<dependencies>
<!-- 运行环境上下文 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
</dependency>
<dependencies>
<!-- 运行环境上下文 -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-context</artifactId>
</dependency>
<!-- 接入微服务组件联盟 配置、注册、网关、链路、监控等 ,单体应用无需引入(logback-spring.xml与logstash相关内容需要注释掉)-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-swagger3</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-dubbo</artifactId>
</dependency>
<!-- 接入微服务组件联盟 配置、注册、网关、链路、监控等
,单体应用无需引入(logback-spring.xml与logstash相关内容需要注释掉)-->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-alliance</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-swagger3</artifactId>
</dependency>
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-admin-dubbo</artifactId>
</dependency>
<!-- local api -->
<dependency>
<groupId>cn.com.glsx.charging</groupId>
<artifactId>platform-charging-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- rest api -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-service-echocenter-api</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
<!-- dubbo api -->
<dependency>
<groupId>cn.com.glsx.scrm</groupId>
<artifactId>rpc-scrm-proxy-api</artifactId>
<version>3.7.0-SNAPSHOT</version>
</dependency>
</dependencies>
<!-- local api -->
<dependency>
<groupId>cn.com.glsx.charging</groupId>
<artifactId>platform-charging-api</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- rest api -->
<dependency>
<groupId>com.glsx</groupId>
<artifactId>rest-service-echocenter-api</artifactId>
<version>2.0.0-SNAPSHOT</version>
</dependency>
<!-- dubbo api -->
<dependency>
<groupId>cn.com.glsx.scrm</groupId>
<artifactId>rpc-scrm-proxy-api</artifactId>
<version>3.7.0-SNAPSHOT</version>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0-M2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
<!-- https://mvnrepository.com/artifact/io.netty/netty-all -->
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</dependency>
<!-- apache commons start -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- apache commons end -->
<!-- swagger start -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!-- swagger end -->
<dependency>
<groupId>cn.com.glsx</groupId>
<artifactId>platform-process</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>${org.mapstruct.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0-M2</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</project>
package cn.com.glsx.charging;
import com.glsx.plat.context.EnableRestAdmin;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
import java.util.TimeZone;
import javax.annotation.PostConstruct;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.EnableMBeanExport;
import org.springframework.jmx.support.RegistrationPolicy;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.annotation.PostConstruct;
import java.util.TimeZone;
import org.springframework.context.annotation.PropertySource;
import static java.time.ZoneId.of;
import static java.util.TimeZone.getTimeZone;
import com.glsx.plat.context.EnableRestAdmin;
/**
* @author payu
......@@ -23,6 +22,7 @@ import static java.util.TimeZone.getTimeZone;
@EnableDiscoveryClient
@EnableFeignClients(basePackages = {"cn.com.glsx.charging.*.api"})
@SpringBootApplication
@PropertySource("application.properties_standalone")
public class Application {
public static void main(String[] args) {
......
package cn.com.glsx.charging.modules.ocpp.ocpp16;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.client.TcpClient;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.client.TcpHandlerHelper;
public class ClientMain {
private static TcpClient instance;
public static TcpClient getInstance() {
if (instance == null) {
System.setProperty("file.encoding", "UTF-8");
TcpHandlerHelper.scan();
String host = "localhost";
int port = 8888;
host = Ocpp16Constants.getTcpHost();
port = Ocpp16Constants.getTcpPort();
TcpClient p = new TcpClient(host, port);
p.start();
instance = p;
}
return instance;
}
public static void main(String[] args) {
getInstance();
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16;
import java.io.File;
import java.util.Date;
import java.util.Properties;
import cn.com.glsx.charging.util.DateUtils;
import cn.com.glsx.charging.util.PropertiesUtils;
import cn.com.glsx.charging.util.SnowFlakeIdUtils;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
public final class Ocpp16Constants {
public static final String PROPERTY_FILE = "application.properties_standalone";
public static final String TCP_HOST_KEY = "ocpp16.server.host";
public static final String TCP_PORT_KEY = "ocpp16.server.port";
/**
* 一个包最多200字节
*/
public static final int TCP_MAX_LENGTH = 200;
// 配置
public static final Properties properties = PropertiesUtils.loadProperties(PROPERTY_FILE);
// 临时目录
public static final String FRAMEWORK_DOWNLOAD_TMPDIR = "framework.download.tmp_dir";
// 获得临时目录
public static File generateTmpDir() {
String dir = properties.getProperty(FRAMEWORK_DOWNLOAD_TMPDIR, "d:/tmp_dir/");
String date = DateUtils.dateToStr(new Date(), "yyyyMMdd");
File path = new File(dir + File.separator + date + File.separator);
if (!path.exists()) {
path.mkdirs();
}
return path;
}
public static String getTcpHost() {
String host = PropertiesUtils.getProperty(PROPERTY_FILE, TCP_HOST_KEY);
return ObjectUtil.defaultIfNull(host, "localhost");
}
public static int getTcpPort() {
String port = PropertiesUtils.getProperty(PROPERTY_FILE, TCP_PORT_KEY);
return NumberUtil.isNumber(port) ? Integer.valueOf(port) : 8888;
}
public static void main(String[] args) {
// Properties properties = PropertiesUtils.loadProperties("application.properties");
String file = "application.properties*";
String key = "wxwork.history.accounts";
System.err.println(PropertiesUtils.getProperty(file, key));
System.err.println(PropertiesUtils.getProperty(file, "swagger.enabled"));
PropertiesUtils.updateProperty(file, key, SnowFlakeIdUtils.generateStr());
System.err.println(PropertiesUtils.getProperty(file, key));
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Maps;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpBase;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpData;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.data.LoginReqData;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.impl.LoginReq;
import cn.com.glsx.charging.util.ByteUtils;
import cn.com.glsx.charging.util.ClassUtil;
import cn.com.glsx.charging.util.ClassUtils;
import cn.com.glsx.charging.util.CrcUtils;
import cn.com.glsx.charging.util.Pair;
import cn.com.glsx.charging.util.PluralCache;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@SuppressWarnings("rawtypes")
public class Ocpp16Helper {
/**
* 序列号生成器:每个连接一个,当连接断开或者序列号溢出则重置
*/
private static PluralCache<String, AtomicInteger> seqFactorys = new PluralCache<>(100);
// 所有的dll协议均扫描进来
private static Map<Byte, Pair<Class<? extends TcpBase>, Class<? extends TcpData>>> protocols = Maps.newHashMap();
public static void scan() {
try {
String[] path = { "cn.com.glsx.charging.modules.ocpp.ocpp16.tcp" };
{
Class pClass = TcpBase.class;
List<Class<?>> ps = ClassUtil.getAllAssignedClass(pClass, path);
log.info("scan:{} from:{}", pClass, path);
for (Class<?> c : ps) {
if (Modifier.isAbstract(c.getModifiers()) || c == pClass) {
continue;
}
Class type = ClassUtils.getSuperClassGenricType(c);
Pair<Class<? extends TcpBase>, Class<? extends TcpData>> pair = new Pair<>();
pair.setKey((Class<? extends TcpBase>) c);
pair.setValue(type);
TcpBase pb = (TcpBase) c.newInstance();
Pair<Class<? extends TcpBase>, Class<? extends TcpData>> put = protocols.put(pb.getType(), pair);
log.info("注册协议: {} -> {}<{}>", pb.getType(), c.getName(), type.getSimpleName());
if (put != null) {
log.warn("重复注册协议: {} -> {} exists:{}", pb.getType(), c, put);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static short generateSeq(String channelId) {
AtomicInteger ai = seqFactorys.get(channelId);
if (ai == null) {
ai = new AtomicInteger();
}
int rs = ai.incrementAndGet();
return (short) rs; // 溢出自动清零
}
public static <D extends TcpData, P extends TcpBase<D>> void fillLen(P b) {
byte[] bs = build(b);
b.setLen((byte) (bs.length - 4));
}
public static <D extends TcpData, P extends TcpBase<D>> short calculateCrc(P b) {
byte[] bs = build(b);
byte[] data = ByteUtils.getBytes(bs, 2, bs.length - 4);
short crc = (short) CrcUtils.calculateCRC(data);
return crc;
}
public static <D extends TcpData, P extends TcpBase<D>> boolean verifyCrc(P b) {
short crc = calculateCrc(b);
return crc == b.getCrc();
}
public static byte[] build(Object d) {
// 创建一个 ByteBuf 对象
ByteBuf byteBuf = Unpooled.buffer(Ocpp16Constants.TCP_MAX_LENGTH);
List<Field> fields = ClassUtils.getAllFields(d.getClass());
for (Field f : fields) {
try {
if (f.getAnnotation(JsonIgnore.class) != null) {
continue;
}
f.setAccessible(true);
Object v = f.get(d);
if (v instanceof byte[]) {
byteBuf.writeBytes((byte[]) v);
} else if (v instanceof Byte) {
byteBuf.writeByte((byte) v);
} else if (v instanceof Short) {
byteBuf.writeByte((short) v);
} else if (v instanceof Integer) {
byteBuf.writeByte((int) v);
} else if (v instanceof String) {
// byteBuf.writeCharSequence((CharSequence) v, Charset.forName("UTF-8")); //TODO 字符串暂时按byte[]来定义,以方便确定长度
} else if (v instanceof TcpData) {
byte[] bs = build(v);
byteBuf.writeBytes(bs);
}
log.debug("build:{} field:{} value:{}", d.getClass().getSimpleName(), f.getName(), v);
} catch (Exception e) {
e.printStackTrace();
}
}
// 读取数据
byte[] data = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(data);
// 释放 ByteBuf
byteBuf.release();
return data;
}
public static <D extends TcpData, P extends TcpBase<D>> P parse(byte[] bs) {
byte type = ByteUtils.getByte(bs);
Pair<Class<? extends TcpBase>, Class<? extends TcpData>> pair = protocols.get(type);
try {
P p = (P) pair.getKey().newInstance();
int offset = 0;
List<Field> fields = ClassUtils.getAllFields(pair.getKey());
for (Field f : fields) {
try {
if (f.getAnnotation(JsonIgnore.class) != null) {
continue;
}
f.setAccessible(true);
Object v = f.get(p);
if (v instanceof byte[]) {
byte[] vs = ByteUtils.getBytes(bs, offset, ((byte[]) v).length);
offset += vs.length;
f.set(p, vs);
} else if (v instanceof Byte) {
byte vs = ByteUtils.getByte(bs, offset);
offset += 1;
f.set(p, vs);
} else if (v instanceof Short) {
short vs = ByteUtils.getShort(bs, offset);
offset += 2;
f.set(p, vs);
} else if (v instanceof Integer) {
int vs = ByteUtils.getInt(bs, offset);
offset += 4;
f.set(p, vs);
} else if (v instanceof TcpData) {
byte vs = ByteUtils.getByte(bs, offset);
offset += 1;
f.set(p, vs);
}
log.debug("build:{} field:{} value:{}", p.getClass().getSimpleName(), f.getName(), v);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
}
return null;
}
public static void main(String[] args) {
LoginReq req = new LoginReq();
List<Field> fields = ClassUtils.getAllFields(req.getClass());
for (Field f : fields) {
if (f.getName().equals("data")) {
try {
f.setAccessible(true);
Object v = f.get(req);
System.out.println(v);
System.out.println(v instanceof TcpData);
} catch (IllegalArgumentException | IllegalAccessException e) {
e.printStackTrace();
}
}
}
req.setData(new LoginReqData());
fillLen(req);
req.setCrc(calculateCrc(req));
verifyCrc(req);
System.out.println(req);
System.out.println(build(req).length);
scan();
}
}
\ No newline at end of file
package cn.com.glsx.charging.modules.ocpp.ocpp16;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.client.TcpHandlerHelper;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server.ProxyHelper;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server.TcpServer;
public class ServerMain {
private static Boolean lock = false;
private static TcpServer server;
public static TcpServer start(String host, int port) {
System.setProperty("file.encoding", "UTF-8");
if (server == null && !lock) {
TcpHandlerHelper.scan();
// DefaultTcpNotifyHandler.startKafaka();
ProxyHelper.startManager();
synchronized (lock) {
server = new TcpServer(host, port);
server.start();
lock = true;
}
}
return server;
}
public static TcpServer start() {
String host = Ocpp16Constants.getTcpHost();
int port = Ocpp16Constants.getTcpPort();
return start(host, port);
}
public static void main(String[] args) {
String host = "localhost";
int port = 8888;
start(host, port);
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
import cn.com.glsx.charging.util.JacksonUtils;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TcpBase<D extends TcpData> {
@JsonIgnore
protected transient final Logger log = LoggerFactory.getLogger(getClass());
/**
* 起始标识符代表一帧数据的开始,固定为 0x68
*/
protected byte type = 0x68;
/**
* 数据域字节数,数据域长度不超过 200 字节。不加密时为原数据长度,加密时,为加密后数据长度。其值为“序列号域+加密标志+帧类型标志+消息体”字节数之和。
* 由于Java的byte是有符号-128~127范围,取值时使用 int l = len & 0xFF 来获取无符号值;
*/
protected byte len = 0;
/**
* 序列号域即为数据包的发送顺序号,从 0 开始顺序增加,如是应答数据包,则与询问数据包序号保持一致,当桩与平台网络断开重新建立连接或者溢出后归 0。
*/
protected short seq = 0;
/**
* 加密标志只针对消息体(数据单元)。0x00:不加密,0x01:3DES
*/
protected byte encrypt = 0;
/**
*  帧类型标志定义了上下行数据帧。
*/
protected byte direction = 0;
private D data;
/**
* 帧校验域:从序列号域到数据域的 CRC 校验,校验多项式为 0x180D,低字节在前,高字节在后,计算方式见附录。
*/
protected short crc = 0;
public TcpBase(byte type) {
this.type = type;
}
public TcpBase() {
this(TcpMapper.CMD_BLANK.getType());
}
@Override
public String toString() {
return JacksonUtils.toJson(this);
}
public static void main(String[] args) {
byte len = (byte) 198;
System.out.println(len);
System.out.println(len & 0xFF);
System.out.println(0x8CB);
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.google.common.collect.Lists;
import cn.hutool.core.collection.CollectionUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
@SuppressWarnings("rawtypes")
@Slf4j
@Getter
public class TcpCallback<Rsp extends TcpRsp> {
private CountDownLatch latch = new CountDownLatch(1);
private final Class<Rsp> rspClass;
private List<Rsp> results = Lists.newArrayList();
private long timeout = 1200;
public TcpCallback(Class<Rsp> rspClass) {
super();
this.rspClass = rspClass;
}
/**
* @param rsp
* 单条返回信息的
*/
public void callback(Rsp rsp) {
if (rsp != null) {
this.results.add(rsp);
latch.countDown();
}
}
public void callback(String ip, Rsp rsp) {
if (rsp != null) {
// log.info("【{}】3.收到Tcp回调:{} -> {}", ip, rsp.getMapper().getRemark(), rsp);
}
callback(rsp);
}
/**
* @param rsp
* 多条返回信息
*/
public void callbacks(Rsp rsp) {
if (rsp != null) {
this.results.add(rsp);
latch.countDown();
log.info("callback:" + rsp + " countdown:" + latch.getCount());
}
}
public Rsp get() {
return get(timeout);
}
public Rsp get(long timeout) {
List<Rsp> rs = gets(timeout);
return CollectionUtil.isEmpty(rs) ? null : rs.get(0);
}
public List<Rsp> gets(long timeout) {
try {
if (!isDone()) {
latch.await(timeout, TimeUnit.MILLISECONDS);
}
return results;
} catch (InterruptedException e) {
throw new RuntimeException("结果集异常:" + timeout + "ms", e);
}
}
public List<Rsp> gets() {
return gets(timeout);
}
public boolean isDone() {
return latch.getCount() <= 0;
}
public boolean isSuccess() {
return isDone() && CollectionUtil.isNotEmpty(results);
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
import cn.com.glsx.charging.util.JacksonUtils;
/**
* 与tcp-server交互的data
*
* @author kome.jiang
* @date 2022年9月27日 下午8:27:20
*/
public abstract class TcpData {
@JsonIgnore
protected transient final Logger log = LoggerFactory.getLogger(getClass());
@Override
public String toString() {
return JacksonUtils.toJson(this);
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
@Getter
@AllArgsConstructor
@ToString
public enum TcpErrorEnum {
SUCCESS(0, "Success"),
ERROR_OPERATION_FAILED(999, "操作失败"),
ERROR_USERID_NOT_LOGIN(1000, "账号未登录"),
;
private int error;
private String remark;
public static TcpErrorEnum fromError(int error2) {
for (TcpErrorEnum e : values()) {
if (e.getError() == error2) {
return e;
}
}
return null;
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base;
import org.slf4j.LoggerFactory;
import io.netty.channel.Channel;
@SuppressWarnings("rawtypes")
public interface TcpHandler<Req extends TcpBase, Rsp extends TcpBase> {
org.slf4j.Logger log = LoggerFactory.getLogger(TcpHandler.class);
Rsp handle(Channel channel, Req req);
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
/**
* 管理与server的交互
*
* @author kome.jiang
* @date 2022年9月27日 下午8:22:01
*/
@Slf4j
@Getter
@AllArgsConstructor
public final class TcpMapper {
private static Map<Byte, TcpMapper> mappers = Maps.newHashMap();
public static TcpMapper CMD_BLANK = regist(0x00, "空白协议", null);
public static TcpMapper CMD_REQ_LOGIN = regist(0x01, "充电桩登录认证", null);
public static TcpMapper CMD_RSP_LOGIN = regist(0x02, "登录认证应答", null);
public static TcpMapper CMD_REQ_HEARTBEAT = regist(0x03, "充电桩心跳包", null);
public static TcpMapper CMD_RSP_HEARTBEAT = regist(0x04, "心跳包应答", null);
// TODO 补充完整所有协议
public static TcpMapper fromType(byte type) {
TcpMapper c = mappers.get(type);
if (c == null) {
log.warn("TcpMapper not found for : {}", type);
}
return c;
}
@SuppressWarnings("rawtypes")
private static TcpMapper regist(int type, String remark, Class<? extends TcpHandler> handlerClass) {
TcpMapper cmd = new TcpMapper((byte) type, remark, handlerClass);
TcpMapper put = mappers.put((byte) type, cmd);
if (put != null) {
log.warn("重复TcpMapper:{} {} - {}", type, remark, put);
}
return cmd;
}
@JsonIgnore
private final byte type;
private final String remark;
@SuppressWarnings("rawtypes")
@JsonIgnore
private Class<? extends TcpHandler> handlerClass;
@Override
public String toString() {
return "Mapper{" + type + " - " + remark + " - " + (handlerClass == null ? null : handlerClass.getSimpleName()) + "}";
}
public static void print() {
for (TcpMapper m : mappers.values()) {
log.info("{}", m);
}
}
public static void main(String[] args) {
print();
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base;
public interface TcpReq<D extends TcpData> {
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TcpRsp<D extends TcpData> extends TcpBase<D> {
protected int error;
public TcpRsp(byte type) {
super(type);
}
public TcpRsp() {
this(TcpMapper.CMD_BLANK.getType());
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.client;
import java.net.InetSocketAddress;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server.TcpServer;
import cn.com.glsx.charging.util.JacksonUtils;
import cn.com.glsx.charging.util.Task;
import cn.com.glsx.charging.util.TaskExecutor;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Getter
@Setter
public class TcpClient {
public static Integer PROTOCOL_MAX_LENGTH = TcpServer.PROTOCOL_MAX_LENGTH;
private String host = "localhost";
private int port;
private Bootstrap bootstrap;
private ChannelFuture future;
public TcpClient(String host, int port) {
this.host = host;
this.port = port;
EventLoopGroup group = new NioEventLoopGroup();
bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("lengthEncoder", new LengthFieldPrepender(4));
pipeline.addLast("lengthDecoder", new LengthFieldBasedFrameDecoder(PROTOCOL_MAX_LENGTH, 0, 4, 0, 4));
pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
pipeline.addLast("handler", new TcpClientHandler());
}
});
}
public boolean isActive() {
return future != null && future.channel() != null && future.channel().isActive();
}
public void connect() {
try {
if (isActive()) {
return;
}
if (future == null) {
log.debug("【{}】start new connection to: {}:{}", host, host, port);
} else {
log.info("【{}】reconnect to: {}:{}", host, host, port);
}
future = bootstrap.connect(host, port).sync();
} catch (Exception e) {
log.error("connect -> {}", e.getMessage());
}
}
public void disconnect() {
if (this.future == null || this.future.channel() == null) {
return;
}
this.future.channel().close();
this.future.cancel(true);
this.future.awaitUninterruptibly();
}
public void start() {
TaskExecutor.addTask(new Task() {
@Override
public void execute() throws Exception {
connect();
}
}, 10 * 1000);
}
public <T> void sendSync(T data) {
String json = JacksonUtils.nodefaultMapper.toJson(data);
sendSync(json);
// if (!(data instanceof HeartbeatDllNotify)) {
String ip = getIp(future.channel());
log.info("【{}】send: {}", ip, json);
// }
}
public void sendSync(String json) {
try {
if (future == null || future.channel() == null) {
return;
}
future.channel().writeAndFlush(json);
} catch (Exception e) {
log.error(json, e);
}
}
public static String getIp(ChannelHandlerContext ctx) {
return getIp(ctx.channel());
}
public static String getIp(Channel channel) {
String ip = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
return ip;
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.client;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpBase;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpHandler;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpMapper;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpReq;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpRsp;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.impl.LoginReq;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server.TcpServer;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server.handler.DefaultTcpRspHandler;
import cn.com.glsx.charging.util.ClassUtils;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TcpClientHandler extends SimpleChannelInboundHandler<String> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String ip = TcpClient.getIp(ctx);
log.info("【{}】conn: 连接成功... {}", ip, ctx.channel().remoteAddress().toString());
log.info("**************************************************************");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
String ip = TcpClient.getIp(ctx);
log.info("【{}】disc: 连接断开!!! {}", ip, ctx.channel().remoteAddress().toString());
log.info("##############################################################");
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
protected void channelRead0(ChannelHandlerContext ctx, String json) throws Exception {
String ip = TcpServer.getIp(ctx);
log.debug("【{}】recv: {}", ip, StrUtil.sub(json, 0, 600));
// 收到的rsp或者notify
try {
JSON parse = JSONUtil.parse(json);
int type = Integer.valueOf(ObjectUtil.defaultIfNull(parse.getByPath("type"), "0").toString());
int subtype = Integer.valueOf(ObjectUtil.defaultIfNull(parse.getByPath("data.msgtype"), "-1").toString());
TcpBase up = TcpHandlerHelper.parse(type, subtype, json);
if (up == null) {
log.warn("【{}】空Json:{}", ip, json);
return;
}
log.info("【{}】解析: {} {}:{} ", ip, StrUtil.sub(up.build(), 0, 600), up.getClass().getSimpleName(),
up.getData() == null ? "" : up.getData().getClass().getSimpleName());
TcpMapper mapper = TcpMapper.fromType(up.getType());
if (mapper == null) {
log.warn("【{}】TcpMapper不存在: {}", ip, up.getType());
return;
}
Class<? extends TcpHandler> handlerClass = mapper.getHandlerClass();
if (handlerClass == null && up instanceof TcpRsp) {
handlerClass = DefaultTcpRspHandler.class;
}
if (handlerClass == null) {
log.info("【{}】TcpMapper没有配置handler: {} - {} {}", ip, mapper.getType(), mapper.getRemark(), up.getClass().getSimpleName());
return;
}
TcpHandler handler = handlerClass.newInstance();
TcpBase rsp = handler.handle(ctx.channel(), up);
if (rsp != null) {
String rspJson = rsp.build();
ctx.channel().writeAndFlush(rspJson);
log.info("【{}】send: {}", ip, StrUtil.sub(rspJson, 0, 600));
}
} catch (Exception e) {
log.error("【{}】{}", ip, json, e);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
String ip = TcpClient.getIp(ctx);
if (cause instanceof ClosedChannelException || cause instanceof IOException) {
log.warn("【{}】close: remote closed from {}", ip, ctx.channel().remoteAddress().toString());
return;
}
log.warn("【{}】excp: at {} , close channel !!", ip, ctx.channel().remoteAddress().toString(), cause);
ctx.channel().close();
}
public static void main(String[] args) {
TcpHandlerHelper.scan();
int type = new LoginReq().getType();
Class<? extends TcpReq> reqClass = (Class<? extends TcpReq>) TcpHandlerHelper.getTcpProtocolClass(type);
System.out.println(ClassUtils.getSuperClassGenricType(reqClass, 0));
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.client.handler;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpHandler;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.impl.LoginReq;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.impl.LoginRsp;
import cn.hutool.core.codec.Base64;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class LoginReqHandler implements TcpHandler<LoginReq, LoginRsp> {
@Override
public LoginRsp handle(Channel channel, LoginReq req) {
LoginRsp trsp = new LoginRsp();
// trsp.setReqKey(req.getReqKey());
// LoginQrcodeTcpData tdata = new LoginQrcodeTcpData();
// trsp.setData(tdata);
//
// try {
// DllClient client = DllFacade.openNewWxwork(req.getData().getUserId(), 0, "TcpReq");
//
// if (client == null) {
// trsp.setError(TcpErrorEnum.ERROR_OPERATION_FAILED.getError());
// return trsp;
// }
//
// SelfInfoDllData userInfo = client.getUserInfo();
// if (userInfo == null || userInfo.getUserId() == null) {
// int i = 50;
// while (client.getQrcodeData() == null && i-- > 0) {
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// LoginQrcodeDllData data = client.getQrcodeData();
// if (data == null || data.getBase64EncodePath() == null) {
// trsp.setError(TcpErrorEnum.ERROR_OPERATION_FAILED.getError());
// return trsp;
// }
// String imagePath = data.getBase64EncodePath();
// log.info("loginQrcodePath:{}", imagePath);
// byte[] bytes = FileUtil.readBytes(new File(imagePath));
// tdata.setBase64EncodeQrcode(Base64.encode(bytes));
// tdata.setLoginQrcodeKey(data.getLoginQrcodeKey());
// } else {
// BeanUtils.copyProperties(userInfo, tdata);
// }
// } catch (Exception e) {
// e.printStackTrace();
// //
// trsp.setError(TcpErrorEnum.ERROR_USERID_NOT_LOGIN.getError());
// }
return trsp;
}
public static void main(String[] args) throws Exception {
String s = "{RDpc08O7p8S/wrxcztK1xM7EtbVcV1hXb3JrXHg1NDFpOG1rRzAzcUFWakxcSW1hZ2VcNTg4MjNhYzItNmVhNi00ZDJjLWE0OWUtNDZjZWM2ZTMzNzZhLmpwZw==}";
System.out.println(Base64.decodeStr(s));
System.out.println(new String(Base64.decode(s.getBytes("GBK")), "GBK"));
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.data;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpData;
import lombok.Getter;
import lombok.Setter;
/**
* 68(起始标志)22(数据长度)0000(序列号域)00(加密标志)01(类型)55031412782305
* (桩编码)00(桩类型)02(充电枪数量)0F(通信协议版本:V1.5)56342E312E353000(程
* 序版本:v4.1.50)01(网络链接类型)01010101010101010101(sim 卡)04(运营商)675A(帧
* 校验域
*
* @author kome
* @date 2023年11月1日 下午6:00:39
*/
@Getter
@Setter
public class LoginReqData extends TcpData {
/**
* 充电桩id: BCD 码 ,不足 7 位补 0
*/
private byte[] pointId = new byte[7];
/**
* 0 表示直流桩,1 表示交流桩
*/
private byte pointType;
/**
* 充电枪数量
*/
private byte gunCount;
/**
* 通信协议版本 BIN 码 1 版本号乘 10,v1.0 表示 0x0A
*/
private byte protocolVersion;
/**
* 程序版本 ASCII 码 8 不足 8 位补零
*/
@JsonSerialize
private byte[] softVersion = new byte[8];
/**
* 网络链接类型
* 0x00 SIM 卡
* 0x01 LAN
* 0x02 WAN
* 0x03 其他
*/
private byte network;
/**
* Sim 卡 BCD 码 10 不足 10 位补零,取不到置零
*/
private byte[] sim = new byte[10];
/**
* 运营商 BIN 码
* 0x00 移动
* 0x02 电信
* 0x03 联通
* 0x04 其他
*/
private byte operator;
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.data;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpData;
import lombok.Getter;
import lombok.Setter;
/**
* 68(起始标志)22(数据长度)0000(序列号域)00(加密标志)01(类型)55031412782305
* (桩编码)00(桩类型)02(充电枪数量)0F(通信协议版本:V1.5)56342E312E353000(程
* 序版本:v4.1.50)01(网络链接类型)01010101010101010101(sim 卡)04(运营商)675A(帧
* 校验域
*
* @author kome
* @date 2023年11月1日 下午6:00:39
*/
@Getter
@Setter
public class LoginRspData extends TcpData {
/**
* 充电桩id: BCD 码 ,不足 7 位补 0
*/
private byte[] pointId = new byte[7];
/**
* 0 表示直流桩,1 表示交流桩
*/
private byte pointType;
/**
* 充电枪数量
*/
private byte gunCount;
/**
* 通信协议版本 BIN 码 1 版本号乘 10,v1.0 表示 0x0A
*/
private byte protocolVersion;
/**
* 程序版本 ASCII 码 8 不足 8 位补零
*/
@JsonSerialize
private byte[] softVersion = new byte[8];
/**
* 网络链接类型
* 0x00 SIM 卡
* 0x01 LAN
* 0x02 WAN
* 0x03 其他
*/
private byte network;
/**
* Sim 卡 BCD 码 10 不足 10 位补零,取不到置零
*/
private byte[] sim = new byte[10];
/**
* 运营商 BIN 码
* 0x00 移动
* 0x02 电信
* 0x03 联通
* 0x04 其他
*/
private byte operator;
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.impl;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpBase;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpMapper;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpReq;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.data.LoginReqData;
/**
* @author kome.jiang
* @date 2022年9月28日 下午2:48:32
*/
public class LoginReq extends TcpBase<LoginReqData> implements TcpReq<LoginReqData> {
public LoginReq() {
super(TcpMapper.CMD_REQ_LOGIN.getType());
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.impl;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpMapper;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpRsp;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.data.LoginRspData;
/**
* 获取登录二维码(请求data为空)
*
* @author kome.jiang
* @date 2022年9月28日 下午2:48:32
*/
public class LoginRsp extends TcpRsp<LoginRspData> {
public LoginRsp() {
super(TcpMapper.CMD_RSP_LOGIN.getType());
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server;
import java.net.InetSocketAddress;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpCallback;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpHandler;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpReq;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpRsp;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.data.LogoutTcpData;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.data.SelfInfoTcpData;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.notify.LogoutTcpNotify;
import cn.com.glsx.charging.util.JacksonUtils;
import cn.com.glsx.charging.util.TaskExecutor;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@SuppressWarnings("rawtypes")
public class ProxyHelper {
// ip -> proxyInfo
private static Map<String, ProxyInfo> proxys = Maps.newConcurrentMap();
// userId -> proxyUser
public static Map<String, ProxyUser> users = Maps.newConcurrentMap();
// key -> TcpCallback
private static Map<String, TcpCallback<? extends TcpRsp>> callbacks = Maps.newConcurrentMap();
// notifyClass --> data-queue
// private static final Map<String, Queue<TcpNotify>> notifys = Maps.newHashMap();
public static String getIp(ChannelHandlerContext ctx) {
return getIp(ctx.channel());
}
public static String getIp(Channel channel) {
String ip = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
return ip;
}
public static int getPort(Channel channel) {
int port = ((InetSocketAddress) channel.remoteAddress()).getPort();
return port;
}
public static ProxyInfo addProxyInfo(Channel channel) {
String ip = getIp(channel);
ProxyInfo proxyInfo = proxys.get(ip);
if (proxyInfo == null) {
proxyInfo = new ProxyInfo(channel);
proxys.put(ip, proxyInfo);
log.info("【{}】Proxy连接建立...", ip);
}
proxyInfo.setChannel(channel);
proxyInfo.setLastTime(new Date());
return proxyInfo;
}
// 连接断开,暂时不移除连接
public static void removeProxyInfo(Channel channel) {
String ip = getIp(channel);
removeProxyInfo(ip);
}
private synchronized static void removeProxyInfo(String ip) {
ProxyInfo proxyInfo = proxys.get(ip);
if (proxyInfo != null && proxyInfo.getChannel().isActive()) {
return;
}
// 所有人都踢掉线
for (ProxyUser u : users.values()) {
if (StrUtil.equals(u.getIp(), ip)) {
removeProxyUser(u.getUserId(), u, "Proxy超时-自动退出");
}
}
log.warn("Proxy:" + ip + "断联中。。。");
proxys.remove(ip); // 连接断开,暂时不移除连接
}
public static ProxyInfo getProxyInfo(Channel channel) {
String ip = getIp(channel);
return getProxyInfo(ip);
}
public static ProxyInfo getProxyInfo(String ip) {
ProxyInfo proxyInfo = proxys.get(ip);
if (proxyInfo == null) {
throw new ProxyException("【" + ip + "】Proxy连接不存在!!!");
}
return proxyInfo;
}
public static ProxyInfo getProxyByUser(String userId, boolean randomIfNull) {
ProxyUser proxyUser = getProxyUserSilence(userId);
if (proxyUser == null) {
// TODO 随机选择一个
if (proxys.size() == 1 && randomIfNull) {
return randomProxyInfo();
}
throw new ProxyException("ProxyUser心跳超时:" + userId);
}
return getProxyInfo(proxyUser.getIp());
}
public static class ProxyException extends RuntimeException {
public ProxyException() {
super();
}
public ProxyException(String message) {
super(message);
}
public ProxyException(Throwable cause) {
super(cause);
}
}
public static ProxyInfo randomProxyInfo() {
if (proxys.isEmpty()) {
throw new RuntimeException("Proxy连接池为空!!!");
}
List<ProxyInfo> list = Lists.newArrayList(proxys.values());
Collections.shuffle(list);
for (ProxyInfo p : list) {
if (p.getChannel().isActive()) {
return p;
}
}
throw new RuntimeException("Proxy连接池为空!!!");
}
public static void addProxyUser(Channel channel, SelfInfoTcpData data) {
addProxyInfo(channel);
if (data == null || StrUtil.isEmpty(data.getUserId())) {
return;
}
String ip = getIp(channel);
ProxyUser proxyUser = users.get(data.getUserId());
if (proxyUser == null) {
proxyUser = new ProxyUser(channel, data);
users.put(data.getUserId(), proxyUser);
log.info("【{}】Proxy用户映射:{}", ip, data);
}
proxyUser.setLastTime(new Date());
}
public static ProxyUser getProxyUserSilence(String userId) {
if (userId == null) {
return null;
}
ProxyUser proxyUser = users.get(userId);
if (proxyUser == null || proxyUser.isHeartbeatTimeout()) {
removeProxyUser(userId, proxyUser, "心跳超时-自动退出");
}
return proxyUser;
}
private static void removeProxyUser(String userId, ProxyUser proxyUser, String reason) {
LogoutTcpData data = new LogoutTcpData();
data.setUserId(userId);
data.setQuitReason(88);
data.setQuitReasonDesc(reason);
if (proxyUser != null && proxyUser.getData() != null) {
data.setCorpShortName(proxyUser.getData().getCorpShortName());
data.setCorpFullName(proxyUser.getData().getCorpFullName());
data.setCorpId(proxyUser.getData().getCorpId());
}
LogoutTcpNotify notify = new LogoutTcpNotify();
notify.setData(data);
TcpHandler.notifys.add(notify);
}
// TODO 心跳机制
// TODO 错误反馈机制
// web_req -> web_req_handler -> tcp_req -> tcp_req_handler -> dll_req -> dll_handler -> dll_rsp -> tcp_rsp -> tcp_rsp_handler -> web_rsp
public static void addCallback(String reqKey, TcpCallback<? extends TcpRsp> callback) {
callbacks.put(reqKey, callback);
}
@SuppressWarnings("unchecked")
public static <Rsp extends TcpRsp> void callback(Rsp rsp) {
TcpCallback<Rsp> callback = (TcpCallback<Rsp>) callbacks.get(rsp.getReqKey());
if (callback != null) {
callback.callback(rsp);
}
}
public static <Req extends TcpReq, Rsp extends TcpRsp> TcpCallback<Rsp> sendAsync(ProxyInfo client, Req req, Class<Rsp> rspClass) {
TcpCallback<Rsp> callback = new TcpCallback<>(rspClass);
addCallback(req.getReqKey(), callback);
String json = req.build();
client.getChannel().writeAndFlush(json);
log.info("【{}】send: {}", client.getIp(), json);
return callback;
}
public static void startManager() {
// 5秒钟执行一次
TaskExecutor.addTask(() -> {
Map<String, ProxyInfo> map = Maps.newHashMap();
map.putAll(proxys);
if (map.isEmpty()) {
return;
}
//
log.info("【自检】-------------------------------------------------------------------------------");
log.info("【自检托管】{}", users);
for (ProxyInfo proxy : map.values()) {
log.info("【自检】{}", JacksonUtils.nodefaultMapper.toJson(proxy));
// 1.移除断开连接
if (!proxy.getChannel().isActive()) {
proxy.getChannel().close();
ProxyHelper.removeProxyInfo(proxy.getChannel());
continue;
}
}
}, 45 * 1000, 20 * 1000);
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server;
import java.util.Date;
import cn.com.glsx.charging.util.DateUtils;
import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;
/**
* 连接上来的客户端信息
*
* @author kome.jiang
* @date 2022年9月27日 下午7:36:02
*/
@Getter
@Setter
public class ProxyInfo {
private String ip;
private int port;
private Channel channel;
// 时间
private Date connectTime = new Date();
private Date lastTime = new Date();
public ProxyInfo(Channel channel) {
super();
this.channel = channel;
this.ip = ProxyHelper.getIp(channel);
this.port = ProxyHelper.getPort(channel);
}
private static int HEARTBEAT_TIMEOUT_SECONDS = 2 * 60; // 心跳过期时间(8秒每次,3次没心跳则过期)
// 四次心跳缺失,认为断联
public boolean isLastTimeout() {
return lastTime.before(DateUtils.addSecond(new Date(), -HEARTBEAT_TIMEOUT_SECONDS));
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server;
import java.util.Date;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.data.SelfInfoTcpData;
import cn.com.glsx.charging.util.DateUtils;
import cn.com.glsx.charging.util.JacksonUtils;
import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;
/**
* 连接上来的客户端包含的用户信息
*
* @author kome.jiang
* @date 2022年9月27日 下午7:36:02
*/
@Getter
@Setter
public class ProxyUser {
private String ip;
// 时间
private Date loginTime = new Date();
private Date lastTime = new Date();
// 用户基本资料
private String userId;
private SelfInfoTcpData data;
public ProxyUser(Channel channel, SelfInfoTcpData data2) {
this.ip = ProxyHelper.getIp(channel);
this.userId = data2.getUserId();
this.data = data2;
}
private static final int HEARTBEAT_TIMEOUT_SECONDS = 5 * 8;
public boolean isHeartbeatTimeout() {
return lastTime.before(DateUtils.addSecond(new Date(), -HEARTBEAT_TIMEOUT_SECONDS));
}
@Override
public String toString() {
return JacksonUtils.toJson(this);
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server;
import java.net.InetSocketAddress;
import java.util.concurrent.ScheduledFuture;
import cn.com.glsx.charging.util.Task;
import cn.com.glsx.charging.util.TaskExecutor;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
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 io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Getter
@Setter
public class TcpServer {
public static Integer PROTOCOL_MAX_LENGTH = 200;
/** 用于分配处理业务线程的线程组个数 */
protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors(); // 默认
/** 业务线程大小 */
protected static final int BIZTHREADSIZE = Math.max(Runtime.getRuntime().availableProcessors() * 2, 16);
private final String host;
private final int port;
private final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
private ServerBootstrap b;
private ChannelFuture future;
private ScheduledFuture<?> startFuture;
public TcpServer(String host, int port) {
this.host = host;
this.port = port;
b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("lengthEncoder", new LengthFieldPrepender(4));
pipeline.addLast("lengthDecoder", new LengthFieldBasedFrameDecoder(PROTOCOL_MAX_LENGTH, 1, 1, 4, 0));
pipeline.addLast("decoder", new ByteArrayDecoder());
pipeline.addLast("encoder", new ByteArrayEncoder());
pipeline.addLast("handler", new TcpServerHandler());
}
});
}
public boolean isActive() {
return future != null && future.channel() != null && future.channel().isActive();
}
public void start() {
startFuture = TaskExecutor.addTask(new Task() {
@Override
public void execute() throws Exception {
try {
if (isActive()) {
return;
}
Thread.sleep(3000);
if (future == null) {
log.info("【{}】开始启动TCP服务器......", port);
} else {
log.info("【{}】重启TCP服务器......", port);
}
future = b.bind(port).sync();
log.info("【{}】成功启动TCP服务器......", port);
} catch (Exception e) {
log.info("{}:{}", host, port, e);
}
}
}, 3 * 1000, 20 * 1000);
}
public void shutdown() throws Exception {
if (startFuture != null) {
startFuture.cancel(true);
}
workerGroup.shutdownGracefully().sync();
bossGroup.shutdownGracefully().sync();
if (future != null) {
future.channel().parent().close().sync();
}
log.info("【{}】关闭TCP服务器!!!!!!", port);
}
public void sendSync(String json) {
try {
future.channel().writeAndFlush(json);
String ip = getIp(future.channel());
log.info("【{}】send: {}", ip, json);
} catch (Exception e) {
log.error(json, e);
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
shutdown();
}
public static String getIp(ChannelHandlerContext ctx) {
return getIp(ctx.channel());
}
public static String getIp(Channel channel) {
String ip = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
return ip;
}
// public static Queue<TcpNotify> notifys = new LinkedBlockingQueue<>(1000);
// private static boolean notifyLock = false;
//
// public static void startNotify() {
// if (notifyLock) {
// return;
// }
// org.glsx.wxwork.task.TaskExecutor.addTask(new Task() {
//
// @Override
// public void execute() throws Exception {
// notifyLock = true;
//
// try {
// KafkaTemplate<String, String> kafkaTemplate = ApplicationContextHolder.popBean(KafkaTemplate.class);
// if (kafkaTemplate == null) {
// return;
// }
//
// while (!notifys.isEmpty() && ClientMain.getInstance().isActive()) {
// try {
// TcpNotify notify = notifys.poll();
// log.info("【{}】{} doNotify remain:{}", notify.getClass().getSimpleName(), notify.getData().getClass().getSimpleName(),
// notifys.size());
//
// if (notify != null && notify.getNotifyKey() != null) {
// kafkaTemplate.send(notify.getNotifyKey(), JacksonUtils.toJson(notify));
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// } finally {
// notifyLock = false;
// }
// }
// }, 3 * 1000);
// }
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server;
import java.io.IOException;
import java.nio.channels.ClosedChannelException;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpBase;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpHandler;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpMapper;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpRsp;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.client.TcpHandlerHelper;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.notify.HeartbeatTcpNotify;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server.handler.DefaultTcpRspHandler;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TcpServerHandler extends SimpleChannelInboundHandler<byte[]> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
String ip = TcpServer.getIp(ctx);
log.info("【{}】conn: 连接成功... {}", ip, ctx.channel().remoteAddress().toString());
log.info("**************************************************************");
ProxyHelper.addProxyInfo(ctx.channel());
// String json = new LoginQrcodeTcpReq().build();
// log.info("【{}】send: {}", ip, json);
// ctx.channel().writeAndFlush(json);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
String ip = TcpServer.getIp(ctx);
log.info("【{}】disc: 连接断开!!! {}", ip, ctx.channel().remoteAddress().toString());
log.info("##############################################################");
ProxyHelper.removeProxyInfo(ctx.channel());
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, byte[] bytes) throws Exception {
String ip = TcpServer.getIp(ctx);
// 收到的rsp或者notify
try {
JSON parse = JSONUtil.parse(json);
int type = Integer.valueOf(ObjectUtil.defaultIfNull(parse.getByPath("type"), "0").toString());
int subtype = Integer.valueOf(ObjectUtil.defaultIfNull(parse.getByPath("data.msgtype"), "-1").toString());
TcpBase up = TcpHandlerHelper.parse(type, subtype, json);
if (up == null) {
log.warn("【{}】空Json:{}", ip, json);
return;
}
if (up instanceof HeartbeatTcpNotify) {
log.debug("【{}】recv: {} | {}", ip, StrUtil.sub(json, 0, 600), up.getClass().getSimpleName());
} else {
log.info("-------------------------------------");
log.info("【{}】recv: {} | {}", ip, StrUtil.sub(json, 0, 600), up.getClass().getSimpleName());
log.debug("【{}】解析: {} {}:{} ", ip, StrUtil.sub(up.build(), 0, 600), up.getClass().getSimpleName(),
up.getData() == null ? "" : up.getData().getClass().getSimpleName());
}
TcpMapper mapper = TcpMapper.fromType(up.getType());
if (mapper == null) {
log.warn("【{}】TcpMapper不存在: {}", ip, up.getType());
return;
}
Class<? extends TcpHandler> handlerClass = mapper.getHandlerClass();
if (handlerClass == null && up instanceof TcpRsp) {
handlerClass = DefaultTcpRspHandler.class;
}
if (handlerClass == null) {
log.info("【{}】TcpMapper没有配置handler: {} - {}", ip, mapper.getType(), mapper.getRemark());
return;
}
TcpHandler handler = handlerClass.newInstance();
TcpBase rsp = handler.handle(ctx.channel(), up);
if (rsp != null) {
String rspJson = rsp.build();
ctx.channel().writeAndFlush(rspJson);
log.info("【{}】send: {}", ip, StrUtil.sub(json, 0, 600));
}
} catch (Exception e) {
log.error("【{}】{}", ip, json, e);
} finally {
ProxyHelper.addProxyInfo(ctx.channel());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
String ip = TcpServer.getIp(ctx);
if (cause instanceof ClosedChannelException || cause instanceof IOException) {
log.warn("【{}】clos: remote closed from {}", ip, ctx.channel().remoteAddress().toString());
return;
}
log.warn("【{}】excp: at {}, close channel!!", ip, ctx.channel().remoteAddress().toString(), cause);
ctx.channel().close();
}
}
package cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.server.handler;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.base.TcpHandler;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.impl.LoginReq;
import cn.com.glsx.charging.modules.ocpp.ocpp16.tcp.impl.LoginRsp;
import cn.hutool.core.codec.Base64;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class LoginReqHandler implements TcpHandler<LoginReq, LoginRsp> {
@Override
public LoginRsp handle(Channel channel, LoginReq req) {
LoginRsp trsp = new LoginRsp();
// trsp.setReqKey(req.getReqKey());
// LoginQrcodeTcpData tdata = new LoginQrcodeTcpData();
// trsp.setData(tdata);
//
// try {
// DllClient client = DllFacade.openNewWxwork(req.getData().getUserId(), 0, "TcpReq");
//
// if (client == null) {
// trsp.setError(TcpErrorEnum.ERROR_OPERATION_FAILED.getError());
// return trsp;
// }
//
// SelfInfoDllData userInfo = client.getUserInfo();
// if (userInfo == null || userInfo.getUserId() == null) {
// int i = 50;
// while (client.getQrcodeData() == null && i-- > 0) {
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// LoginQrcodeDllData data = client.getQrcodeData();
// if (data == null || data.getBase64EncodePath() == null) {
// trsp.setError(TcpErrorEnum.ERROR_OPERATION_FAILED.getError());
// return trsp;
// }
// String imagePath = data.getBase64EncodePath();
// log.info("loginQrcodePath:{}", imagePath);
// byte[] bytes = FileUtil.readBytes(new File(imagePath));
// tdata.setBase64EncodeQrcode(Base64.encode(bytes));
// tdata.setLoginQrcodeKey(data.getLoginQrcodeKey());
// } else {
// BeanUtils.copyProperties(userInfo, tdata);
// }
// } catch (Exception e) {
// e.printStackTrace();
// //
// trsp.setError(TcpErrorEnum.ERROR_USERID_NOT_LOGIN.getError());
// }
return trsp;
}
public static void main(String[] args) throws Exception {
String s = "{RDpc08O7p8S/wrxcztK1xM7EtbVcV1hXb3JrXHg1NDFpOG1rRzAzcUFWakxcSW1hZ2VcNTg4MjNhYzItNmVhNi00ZDJjLWE0OWUtNDZjZWM2ZTMzNzZhLmpwZw==}";
System.out.println(Base64.decodeStr(s));
System.out.println(new String(Base64.decode(s.getBytes("GBK")), "GBK"));
}
}
/*
* @Copyright: 2014~2018 www.yyfax.com Inc. All rights reserved.
*/
package cn.com.glsx.charging.util;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.beans.Transient;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
/**
* Bean操作
*
* @author jiangmy
* @date 2018年1月15日 下午4:50:52
* @since 1.0.0
*/
@Slf4j
@SuppressWarnings("rawtypes")
public class BeanUtils {
static final Map<Class, LinkedHashMap<String, Field>> _fieldMaps = new LinkedHashMap<>();
static final Map<Class, List<Field>> _fields = new LinkedHashMap<>();
static final Map<Class, List<Method>> _methods = new LinkedHashMap<>();
/**
* @param clz
* @return 所有属性(包括父类,去掉Transient的)
*/
public static List<Field> getFields(Class<?> clz) {
if (clz == null) {
return null;
}
List<Field> list = _fields.get(clz);
if (list == null) {
list = new ArrayList<>();
Field[] fields;
try {
while (!clz.equals(Object.class)) {
fields = clz.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
continue;
}
if (field.getAnnotation(Transient.class) != null) {
continue;
}
list.add(field);
}
clz = clz.getSuperclass();
}
_fields.put(clz, list);
} catch (Exception e) {
log.error(clz.getName(), e);
}
}
return list;
}
public static List<String> getAnnotationFields(Class<?> entityClass, Class<? extends Annotation> annotationClass) {
List<String> list = new ArrayList<String>();
List<Field> fields = getFields(entityClass);
for (Field f : fields) {
if (f.isAnnotationPresent(annotationClass)) {
list.add(f.getName());
}
}
return list;
}
/**
* 获取值
*
* @param obj
* @param propertyName
* @return
* @author jiangmy
* @date 2018年1月17日 下午4:24:06
* @since 1.0.0
*/
public static Object invokeGetter(Object obj, String propertyName) {
try {
BeanInfo bi = Introspector.getBeanInfo(obj.getClass(), Object.class);
PropertyDescriptor[] pd = bi.getPropertyDescriptors();
for (PropertyDescriptor p : pd) {
if (StringUtils.equalsIgnoreCase(p.getName(), propertyName)) {
Object value = p.getReadMethod().invoke(obj, (Object[]) null);
return value;
}
}
throw new RuntimeException(obj.getClass() + "没有包含属性:" + propertyName);
} catch (Exception e) {
throw new RuntimeException("从:" + obj.getClass().getName() + "读取属性:" + propertyName + "失败!", e);
}
}
public static Object invokeMethod(Object obj, String methodName) {
try {
BeanInfo bi = Introspector.getBeanInfo(obj.getClass(), Object.class);
MethodDescriptor[] md = bi.getMethodDescriptors();
for (MethodDescriptor m : md) {
if (StringUtils.equalsIgnoreCase(m.getName(), methodName)) {
Object value = m.getMethod().invoke(obj, (Object[]) null);
return value;
}
}
throw new RuntimeException(obj.getClass() + "没有包含方法:" + methodName);
} catch (Exception e) {
throw new RuntimeException("从:" + obj.getClass().getName() + "读取方法:" + methodName + "失败!", e);
}
}
/**
* 设置值
*
* @param obj
* @param propertyName
* @param value
* @author jiangmy
* @date 2018年1月17日 下午4:23:52
* @since 1.0.0
*/
public static void invokeSetter(Object obj, String propertyName, Object value) {
try {
BeanInfo bi = Introspector.getBeanInfo(obj.getClass(), Object.class);
PropertyDescriptor[] pd = bi.getPropertyDescriptors();
for (PropertyDescriptor p : pd) {
if (StringUtils.equalsIgnoreCase(p.getName(), propertyName)) {
p.getWriteMethod().invoke(obj, value);
return;
}
}
throw new RuntimeException(obj.getClass() + "没有包含属性:" + propertyName);
} catch (Exception e) {
throw new RuntimeException("从:" + obj.getClass().getName() + "修改属性:" + propertyName + "为:" + value + "失败!", e);
}
}
/**
* 静态方法
*
* @param ownerClass
* @param methodName
* @param args
* @return
* @author jiangmy
* @date 2018年1月17日 下午5:13:34
* @since 1.0.0
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object invokeStaticMethod(Class ownerClass, String methodName, Object... args) {
Class[] argsClass = null;
if (args != null && args.length > 0) {
argsClass = new Class[args.length];
for (int i = 0, j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
}
try {
Method method = ownerClass.getMethod(methodName, argsClass);
return method.invoke(null, args);
} catch (Exception e) {
// e.printStackTrace();
throw new RuntimeException(ownerClass.getName() + "没有找到" + methodName + "方法");
}
}
private BeanUtils() {
}
}
package cn.com.glsx.charging.util;
import javax.servlet.http.HttpServletRequest;
/**
* <code>
* 浏览器工具类<br/>
* 1.获取当前浏览器名称
* 2.判断当前用户的浏览器
* </code>
*
* @author liujixiang
* @since 2018-11-08
*/
public final class BrowserUtil {
public static final String IE = "msie";
public static final String FIREFOX = "firefox";
public static final String CHROME = "chrome";
private BrowserUtil() {
throw new AssertionError();
}
/**
* 获取当前浏览器名称
*
* @param request
* @return 返回浏览器名称
*/
public static String getCurrent(HttpServletRequest request) {
String userAgent = request.getHeader("USER-AGENT").toLowerCase();
if (userAgent != null && !userAgent.trim().equals("")) {
if (userAgent.indexOf(CHROME) >= 0) {
return CHROME;
} else if (userAgent.indexOf(FIREFOX) >= 0) {
return FIREFOX;
} else if (userAgent.indexOf(IE) >= 0) {
return IE;
}
}
return null;
}
/**
* 是否是IE浏览器
*
* @param request
* @return
*/
public static boolean isIE(HttpServletRequest request) {
return IE.equals(getCurrent(request));
}
/**
* 是否是Firefox浏览器
*
* @param request
* @return
*/
public static boolean isFirefox(HttpServletRequest request) {
return FIREFOX.equals(getCurrent(request));
}
/**
* 是否是Chrome浏览器
*
* @param request
* @return
*/
public static boolean isChrome(HttpServletRequest request) {
return CHROME.equals(getCurrent(request));
}
}
package cn.com.glsx.charging.util;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonIgnore;
import cn.hutool.core.collection.CollectionUtil;
public abstract class CallbackTask<T> implements Task {
@JsonIgnore
protected final Logger log = LoggerFactory.getLogger(getClass());
private CountDownLatch latch;
private final long start = System.currentTimeMillis();
private volatile long end = 0;
private List<T> results;
private long millis;
private int total = 0;
private int callback = 0;
private LinkedBlockingQueue<Future<?>> futures;
public CallbackTask(int results, long millis) {
this.latch = new CountDownLatch(results);
this.results = new ArrayList<>();
this.millis = millis;
this.futures = new LinkedBlockingQueue<>();
log.info("指纹匹配开始...");
}
public List<T> getResults() {
try {
if (!isDone()) {
latch.await(millis, TimeUnit.MILLISECONDS);
log.info("指纹匹配结束, total:{} callback:{}", total, callback);
}
return results;
} catch (InterruptedException e) {
throw new RuntimeException("callback timeout:" + millis + "ms", e);
}
}
public T getResult() {
List<T> list = getResults();
if (list != null && list.size() > 0) {
return list.get(0);
}
return null;
}
public void callback(T rs) {
callback++;
if (rs != null) {
this.results.add(rs);
latch.countDown();
log.info("match callback:" + rs + " countdown:" + latch.getCount());
}
if (!isDone()) {
this.futures.poll();
if (this.futures.isEmpty()) {
while (latch.getCount() > 0) {
latch.countDown();
}
}
}
if (isDone()) {
if (!this.futures.isEmpty()) {
stopTasks();
}
}
}
public void callback() {
callback(null);
}
public Future<?> addTask(Task task) {
if (isDone()) {
throw new RuntimeException("isDone!");
}
total++;
Future<?> future = TaskExecutor.addTask(task);
futures.add(future);
log.debug("add future! size:" + this.futures.size());
return future;
}
private synchronized void stopTasks() {
int i = 0;
for (Future<?> f : futures) {
if (!f.isDone()) {
f.cancel(true);
i++;
}
}
futures.clear();
if (i > 0) {
log.info("指纹匹配结束, stop tasks:" + i + " time:" + (System.currentTimeMillis() - start) + "ms");
}
}
public boolean isDone() {
boolean done = latch.getCount() <= 0;
if (done && end == 0) {
end = System.currentTimeMillis();
log.info("指纹匹配结束... size:" + this.results.size() + ",time:" + (end - start) + "ms");
}
return done;
}
public boolean isSuccess() {
return isDone() && CollectionUtil.isNotEmpty(results);
}
public static void main(String[] args) {
final List<Integer> list = new ArrayList<>();
for (int i = 0; i < 30000; i++) {
list.add(i);
}
// 一个个比较
final int search = 1142;
long begin = System.currentTimeMillis();
CallbackTask<Integer> callback = TaskExecutor.addCallback(new CallbackTask<Integer>(1, 5000) {
@Override
public void execute() throws Exception {
for (int i = 0; i < list.size(); i++) {
final int o = list.get(i);
addTask(new Task() {
@Override
public void execute() throws Exception {
Thread.sleep(30);
if (o == search) {
callback(o);
}
}
});
}
}
});
callback.getResult();
long cost = System.currentTimeMillis() - begin;
System.out.println("result:" + callback.getResult() + " cost:" + cost + "ms");
System.exit(0);
}
}
package cn.com.glsx.charging.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.springframework.aop.framework.AdvisedSupport;
import org.springframework.aop.framework.AopProxy;
import org.springframework.aop.support.AopUtils;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import cn.hutool.core.collection.CollectionUtil;
public class ClassUtils {
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
*
* @param clazz
* The class to introspect
* @return the first generic declaration, or <code>Object.class</code> if cannot be determined
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(Class clazz) {
return ClassUtils.getSuperClassGenricType(clazz, 0);
}
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
*
* @param clazz
* clazz The class to introspect
* @param index
* the Index of the generic ddeclaration,start from 0.
*/
@SuppressWarnings("rawtypes")
public static Class getSuperClassGenricType(Class clazz, int index) throws IndexOutOfBoundsException {
// 泛型参数: 先查看父类的泛型参数; 再查看接口的泛型参数
Type genType = clazz.getGenericSuperclass();
if (genType == null) {
return null;
}
if (!(genType instanceof ParameterizedType)) {
if (genType instanceof Object) {
return Object.class;
}
return ClassUtils.getSuperClassGenricType(clazz.getSuperclass(), index);
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return Object.class;
}
if ((params[index] instanceof ParameterizedType)) {
return (Class) ((ParameterizedType) params[index]).getRawType();
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
/**
* 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
*
* @param clazz
* clazz The class to introspect
* @param index
* the Index of the generic ddeclaration,start from 0.
*/
@SuppressWarnings("rawtypes")
public static Object generateInstanceByGenricType(Class clazz, int index) throws IndexOutOfBoundsException {
// 泛型参数: 先查看父类的泛型参数; 再查看接口的泛型参数
Type genType = clazz.getGenericSuperclass();
if (genType == null) {
return null;
}
if (!(genType instanceof ParameterizedType)) {
if (genType instanceof Object) {
return null;
}
return generateInstanceByGenricType(clazz.getSuperclass(), index);
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return null;
}
if ((params[index] instanceof ParameterizedType)) {
ParameterizedType type = ((ParameterizedType) params[index]);
// 创建参数类型数组
Class[] parameterTypes = new Class[type.getActualTypeArguments().length];
Object[] parameters = new Object[type.getActualTypeArguments().length];
try {
// 获取各参数类型
for (int i = 0; i < parameterTypes.length; i++) {
Class<?> aClass = (Class<?>) type.getActualTypeArguments()[i];
parameterTypes[i] = aClass;
parameters[i] = aClass.newInstance();
}
Constructor<?> constructor = ((Class) type.getRawType()).getConstructor(parameterTypes);
// 返回实例对象
return constructor.newInstance(parameters);
// return ((ParameterizedType) params[index]).getRawType();
} catch (Exception e) {
e.printStackTrace();
return null;
}
// 根据参数类型获取相应的构造函数
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return params[index];
}
// 泛型参数: 先查看父类的泛型参数; 再查看接口的泛型参数
@SuppressWarnings("rawtypes")
public static Class getInterfaceGenricType(Class clazz, int index) throws IndexOutOfBoundsException {
Type[] types = clazz.getGenericInterfaces();
if (types == null) {
return Object.class;
}
for (Type genType : types) {
if (!(genType instanceof ParameterizedType)) {
if (genType instanceof Object) {
continue;
}
return ClassUtils.getInterfaceGenricType(clazz.getSuperclass(), index);
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
continue;
}
if (!(params[index] instanceof Class)) {
continue;
}
return (Class) params[index];
}
return Object.class;
}
@SuppressWarnings("rawtypes")
public static Class getGenricType(Class clazz, int index) {
Class c = ClassUtils.getSuperClassGenricType(clazz, index);
if (c == null || c == Object.class) {
c = ClassUtils.getInterfaceGenricType(clazz, index);
}
return c;
}
@SuppressWarnings("rawtypes")
public static Class getGenricTypeArguments(Class clazz, int index, int argIndex) {
// 泛型参数: 先查看父类的泛型参数; 再查看接口的泛型参数
Type genType = clazz.getGenericSuperclass();
if (genType == null) {
return null;
}
if (!(genType instanceof ParameterizedType)) {
if (genType instanceof Object) {
return null;
}
return ClassUtils.getGenricTypeArguments(clazz.getSuperclass(), index, argIndex);
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
return null;
}
if ((params[index] instanceof ParameterizedType)) {
return (Class) ((ParameterizedType) params[index]).getActualTypeArguments()[argIndex];
}
if (!(params[index] instanceof Class)) {
return null;
}
return null;
}
public static Class getFieldGenericType(Field curField, int index) {
// 当前集合的泛型类型
Type genericType = curField.getGenericType();
if (null == genericType) {
return null;
}
if (genericType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) genericType;
// 得到泛型里的class类型对象
Class<?> actualTypeArgument = (Class<?>) pt.getActualTypeArguments()[index];
return actualTypeArgument;
}
return null;
}
/**
* 获取 目标对象
*
* @param proxy
* 代理对象
* @return
* @throws Exception
*/
public static Object getTarget(Object proxy) {
if (!AopUtils.isAopProxy(proxy)) {
return proxy;// 不是代理对象
}
if (AopUtils.isJdkDynamicProxy(proxy)) {
return getJdkDynamicProxyTargetObject(proxy);
} else { // cglib
return getCglibProxyTargetObject(proxy);
}
}
private static Object getCglibProxyTargetObject(Object proxy) {
try {
Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");
h.setAccessible(true);
Object dynamicAdvisedInterceptor = h.get(proxy);
Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
return target;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static Object getJdkDynamicProxyTargetObject(Object proxy) {
try {
Field h = proxy.getClass().getSuperclass().getDeclaredField("h");
h.setAccessible(true);
AopProxy aopProxy = (AopProxy) h.get(proxy);
Field advised = aopProxy.getClass().getDeclaredField("advised");
advised.setAccessible(true);
Object target = ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget();
return target;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static List<Field> getAllFields(Class<?> clazz) {
List<Field> set = Lists.newArrayList();
Field[] fields = clazz.getDeclaredFields();
if (fields != null) {
CollectionUtil.addAll(set, fields);
}
if (clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class) {
List<Field> list = getAllFields(clazz.getSuperclass());
CollectionUtil.addAll(set, list);
}
return new ArrayList<>(set);
}
}
/*
* @Copyright: 2014~2018 www.yyfax.com Inc. All rights reserved.
*/
package cn.com.glsx.charging.util;
import java.io.Closeable;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
/**
* 可关闭的对象
*
* @author jiangmy
* @date 2018年1月15日 下午4:52:54
* @since 1.0.0
*/
@Slf4j
public class CloseableUtils {
/**
* 关闭一个可关闭对象
*
* @param closeables 可关闭对象
* @return 是否成功关闭
*/
public static boolean safeClose(Closeable... closeables) {
boolean success = true;
for (Closeable closeable : closeables) {
if (null != closeable) {
try {
closeable.close();
} catch (IOException e) {
log.error("close " + closeable + " failed !!!", e);
success = false;
}
}
}
return success;
}
private CloseableUtils() {
log.info("");
}
}
package cn.com.glsx.charging.util;
public class CrcUtils {
private static final int[] gabyCRCHi = { 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01,
0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40,
0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81,
0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0,
0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00,
0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41,
0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80,
0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0,
0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x01,
0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41,
0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40, 0x01, 0xc0, 0x80,
0x41, 0x01, 0xc0, 0x80, 0x41, 0x00, 0xc1, 0x81, 0x40 };
private static final int[] gabyCRCLo = { 0x00, 0xc0, 0xc1, 0x01, 0xc3, 0x03, 0x02, 0xc2, 0xc6, 0x06, 0x07, 0xc7, 0x05, 0xc5, 0xc4, 0x04, 0xcc,
0x0c, 0x0d, 0xcd, 0x0f, 0xcf, 0xce, 0x0e, 0x0a, 0xca, 0xcb, 0x0b, 0xc9, 0x09, 0x08, 0xc8, 0xd8, 0x18, 0x19, 0xd9, 0x1b, 0xdb, 0xda, 0x1a,
0x1e, 0xde, 0xdf, 0x1f, 0xdd, 0x1d, 0x1c, 0xdc, 0x14, 0xd4, 0xd5, 0x15, 0xd7, 0x17, 0x16, 0xd6, 0xd2, 0x12, 0x13, 0xd3, 0x11, 0xd1, 0xd0,
0x10, 0xf0, 0x30, 0x31, 0xf1, 0x33, 0xf3, 0xf2, 0x32, 0x36, 0xf6, 0xf7, 0x37, 0xf5, 0x35, 0x34, 0xf4, 0x3c, 0xfc, 0xfd, 0x3d, 0xff, 0x3f,
0x3e, 0xfe, 0xfa, 0x3a, 0x3b, 0xfb, 0x39, 0xf9, 0xf8, 0x40, 0x28, 0xe8, 0xe9, 0x29, 0xeb, 0x2b, 0x2a, 0xea, 0xee, 0x2e, 0x2f, 0xef, 0x2d,
0xed, 0xec, 0x2c, 0xe4, 0x24, 0x25, 0xe5, 0x27, 0xe7, 0xe6, 0x26, 0x22, 0xe2, 0xe3, 0x23, 0xe1, 0x21, 0x20, 0xe0, 0xa0, 0x60, 0x61, 0xa1,
0x63, 0xa3, 0xa2, 0x62, 0x66, 0xa6, 0xa7, 0x67, 0xa5, 0x65, 0x64, 0xa4, 0x6c, 0xac, 0xad, 0x6d, 0xaf, 0x6f, 0x6e, 0xae, 0xaa, 0x6a, 0x6b,
0xab, 0x69, 0xa9, 0xa8, 0x68, 0x78, 0xb8, 0xb9, 0x79, 0xbb, 0x7b, 0x7a, 0xba, 0xbe, 0x7e, 0x7f, 0xbf, 0x7d, 0xbd, 0xbc, 0x7c, 0xb4, 0x74,
0x75, 0xb5, 0x77, 0xb7, 0xb6, 0x76, 0x72, 0xb2, 0xb3, 0x73, 0xb1, 0x71, 0x70, 0xb0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96,
0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9c, 0x5c, 0x5d, 0x9d, 0x5f, 0x9f, 0x9e, 0x5e, 0x5a, 0x9a, 0x9b, 0x5b, 0x99, 0x59, 0x58, 0x98,
0x88, 0x48, 0x49, 0x89, 0x4b, 0x8b, 0x8a, 0x4a, 0x4e, 0x8e, 0x8f, 0x4f, 0x8d, 0x4d, 0x4c, 0x8c, 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46,
0x86, 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40 };
public static int calculateCRC(byte[] pData) {
return calculateCRC(pData, pData.length);
}
public static int calculateCRC(byte[] pData, int len) {
int byCRCHi = 0xff;
int byCRCLo = 0xff;
int byIdx;
int crc;
while (len-- > 0) {
byIdx = byCRCHi ^ pData[pData.length - len - 1] & 0xFF;
byCRCHi = byCRCLo ^ gabyCRCHi[byIdx];
byCRCLo = gabyCRCLo[byIdx];
}
crc = byCRCHi << 8 | byCRCLo;
return crc;
}
public static void main(String[] args) {
byte[] data = { 0x01, 0x02, 0x03 }; // Example data
int crc = calculateCRC(data, data.length);
System.out.printf("CRC: 0x%04X\n", crc);
}
}
package cn.com.glsx.charging.util;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author liujixiang
* @date 2018-11-08
*/
public class DateUtil {
public static final String formatStr_yyyyMMddHHmmssS_ = "yyyyMMddHHmmss";
public static final String formatStr_yyyyMMddHHmmssS = "yyyy-MM-dd HH:mm:ss.S";
public static final String formatStr_yyyyMMddHHmmss = "yyyy-MM-dd HH:mm:ss";
public static final String formatStr_yyyyMMddHHmm = "yyyy-MM-dd HH:mm";
public static final String formatStr_yyyyMMddHH = "yyyy-MM-dd HH";
public static final String formatStr_yyyyMMdd = "yyyy-MM-dd";
public static final String formatStr_yyyy = "yyyy";
public static final String formatStr_yyyy_MM_dd = "yyyyMMdd";
public static final String formatStr_yyyyMMddDelimiter = "-";
public static String getYYYYMMDDHHMMSS(Date date) {
if (date == null) {
return null;
}
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = simpleDateFormat.format(date);
return dateString;
}
}
package cn.com.glsx.charging.util;
import java.lang.reflect.Method;
import org.apache.commons.lang3.StringUtils;
/**
* 枚举工具类
*
* @author liujixiang
* @date 2018-11-08
*/
public class EnumUtil {
/**
* 通过key获取name
*
* @param clazz
* @param key
* @return
*/
public static String getEnum(Class<?> clazz, Integer key) {
try {
Object[] objects = clazz.getEnumConstants();
Method keyMethod = clazz.getDeclaredMethod("getKey");
Method valueMethod = clazz.getDeclaredMethod("getValue");
for (Object object : objects) {
Integer k = (Integer) keyMethod.invoke(object);
if (k.equals(key)) {
String value = (String) valueMethod.invoke(object);
return value;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 判断key在枚举中是否存在
*
* @param clazz
* @param key
* @return
*/
public static boolean exists(Class<?> clazz, Integer key) {
String name = getEnum(clazz, key);
if (StringUtils.isBlank(name)) {
return false;
}
return true;
}
/**
* 判断key在枚举中是否不存在
*
* @param clazz
* @param key
* @return
*/
public static boolean notExists(Class<?> clazz, Integer key) {
return !exists(clazz, key);
}
}
package cn.com.glsx.charging.util;
import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import cn.hutool.core.util.StrUtil;
/**
* 判断一个文件地址是什么格式
*
* @author kome.jiang
* @date 2022年9月27日 下午3:23:09
*/
public class FileFormatUtils {
private static final String VIDEO_FROMATS = "mp4|mov";
private static final String AUDIO_FROMATS = "mp3|m4a";
private static final String IMAGE_FROMATS = "jpg|jpeg|png|gif";
public static enum FileFormatEnum {
VIDEO, IMAGE, AUDIO;
}
/**
* @param fileUrl 根据本地文件或者网络地址猜测文件格式
* @return
*/
public static String guestFormatFromUrl(String fileUrl) {
String format = null;
// 本地地址
format = StrUtil.subAfter(fileUrl, '.', true);
// 网络地址
if (format == null && StrUtil.startWith(fileUrl, "http")) {
format = HttpURLConnection.guessContentTypeFromName(fileUrl);
if (format == null) {
try {
URL url = new URL(fileUrl);
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
urlconnection.connect();
try (BufferedInputStream bis = new BufferedInputStream(urlconnection.getInputStream())) {
format = HttpURLConnection.guessContentTypeFromStream(bis);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return format;
}
return format;
}
public static FileFormatEnum guestFormatType(String url) {
String format = guestFormatFromUrl(url);
if (StrUtil.startWith(format, "image") || StrUtil.endWithAny(format, IMAGE_FROMATS.split("\\|"))) {
return FileFormatEnum.IMAGE;
}
if (StrUtil.startWith(format, "audio") || StrUtil.endWithAny(format, AUDIO_FROMATS.split("\\|"))) {
return FileFormatEnum.AUDIO;
}
if (StrUtil.endWithAny(format, VIDEO_FROMATS.split("\\|"))) {
return FileFormatEnum.VIDEO;
}
return null;
}
public static boolean isImage(String url) {
FileFormatEnum type = guestFormatType(url);
return type == FileFormatEnum.IMAGE;
}
public static boolean isAudio(String url) {
FileFormatEnum type = guestFormatType(url);
return type == FileFormatEnum.AUDIO;
}
public static boolean isVideo(String url) {
FileFormatEnum type = guestFormatType(url);
return type == FileFormatEnum.VIDEO;
}
public static void main(String[] args) throws Exception {
String fileUrl = "https://mmbiz.qpic.cn/mmbiz_png/N5niatN9B18yXyOmUlxSribF73IJA9afJQicxQebxXQlsXcicYZfmthfxYGPyv15q8Czkzwk3ia150J4LIzX3YI3b0w/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1";
System.out.println(guestFormatType(fileUrl));
System.out.println(guestFormatType("D:/wechat-data/WeChat Files/fatjohnbull/FileStorage/Video/2022-09/5c89c91e04584f28ee2953c46996eb83.mp4"));
}
}
package cn.com.glsx.charging.util;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* 获取当前请求的HttpServletRequest对象
*
* @author liujixiang
* @date 2018-11-08
*/
public class HttpServletRequestUtil {
public static HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
package cn.com.glsx.charging.util;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.json.JSONUtil;
/**
* @author liujixiang
* @date 2018-11-08
*/
public final class HttpServletResponseUtil {
private static String UTF8 = "UTF-8";
// TODO
// private static String CONTENT_TYPE = "application/json;charset=UTF-8";
private static String CONTENT_TYPE = "application/json";
private HttpServletResponseUtil() {
throw new AssertionError();
}
public static void printJSON(HttpServletResponse response, Object object) throws Exception {
response.setCharacterEncoding(UTF8);
response.setContentType(CONTENT_TYPE);
PrintWriter printWriter = response.getWriter();
printWriter.write(JSONUtil.toJsonStr(object));
printWriter.flush();
printWriter.close();
}
}
/**
*
*/
package cn.com.glsx.charging.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Label;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class ImageUtils {
/**
* 转换BufferedImage 数据为byte数组
*
* @param image
* Image对象
* @param format
* image格式字符串.如"gif","png"
* @return byte数组
*/
public static byte[] imageToBytes(BufferedImage bImage, String format) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ImageIO.write(bImage, format, out);
} catch (IOException e) {
log.warn("format:" + format, e);
}
return out.toByteArray();
}
/**
* 转换byte数组为Image
*
* @param bytes
* @return Image
*/
public static Image bytesToImage(byte[] bytes) {
Image image = Toolkit.getDefaultToolkit().createImage(bytes);
try {
MediaTracker mt = new MediaTracker(new Label());
mt.addImage(image, 0);
mt.waitForAll();
} catch (InterruptedException e) {
log.warn("", e);
}
return image;
}
public static void compressPictureByQality(File file, String outputPath, float qality) throws IOException {
BufferedImage src = null;
ImageWriter imgWrier;
ImageWriteParam imgWriteParams;
// System.out.println("开始设定压缩图片参数");
// 指定写图片的方式为 jpg
imgWrier = ImageIO.getImageWritersByFormatName("jpg").next();
imgWriteParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
// 要使用压缩,必须指定压缩方式为MODE_EXPLICIT
imgWriteParams.setCompressionMode(imgWriteParams.MODE_EXPLICIT);
// 这里指定压缩的程度,参数qality是取值0~1范围内,
imgWriteParams.setCompressionQuality(qality);
imgWriteParams.setProgressiveMode(imgWriteParams.MODE_DISABLED);
ColorModel colorModel = ImageIO.read(file).getColorModel();// ColorModel.getRGBdefault();
// 指定压缩时使用的色彩模式
// imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(
// colorModel, colorModel.createCompatibleSampleModel(16, 16)));
imgWriteParams.setDestinationType(new javax.imageio.ImageTypeSpecifier(colorModel, colorModel.createCompatibleSampleModel(16, 16)));
// System.out.println("结束设定压缩图片参数");
if (!file.exists()) {
// System.out.println("Not Found Img File,文件不存在");
throw new FileNotFoundException("Not Found Img File,文件不存在");
}
// System.out.println("图片转换前大小" + file.length() + "字节");
src = ImageIO.read(file);
try (FileOutputStream out = new FileOutputStream(new File(outputPath))) {
imgWrier.reset();
// 必须先指定 out值,才能调用write方法, ImageOutputStream可以通过任何
// OutputStream构造
imgWrier.setOutput(ImageIO.createImageOutputStream(out));
// 调用write方法,就可以向输入流写图片
imgWrier.write(null, new IIOImage(src, null, null), imgWriteParams);
out.flush();
log.info("图片压缩Fr:{} {}", file.length(), file.getPath());
log.info("图片压缩To:{} {}", new File(outputPath).length(), outputPath);
}
}
public static String addWatermark2(String imageUrl, String watermarkText) throws IOException {
// Load the original image from the URL
URL url = new URL(imageUrl);
BufferedImage originalImage = ImageIO.read(url);
// Create a new image with the same dimensions as the original
BufferedImage newImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_RGB);
// Create a graphics object to draw on the new image
Graphics2D graphics = newImage.createGraphics();
graphics.drawImage(originalImage, 0, 0, null);
// Set the font and color for the watermark text
Font font = new Font("微软雅黑", Font.BOLD, originalImage.getWidth() / 12);
graphics.setFont(font);
graphics.setColor(Color.WHITE);
// Calculate the position of the watermark text
FontMetrics fontMetrics = graphics.getFontMetrics(font);
int x = (originalImage.getWidth() - fontMetrics.stringWidth(watermarkText)) / 2;
int y = originalImage.getHeight() - fontMetrics.getHeight();
// Add the watermark text to the image
graphics.drawString(watermarkText, x, y);
// Save the new image with the watermark
File outputFile = new File("watermarked_image.jpg");
ImageIO.write(newImage, "jpg", outputFile);
// Clean up
graphics.dispose();
System.out.println("Watermark added to image: " + imageUrl);
return outputFile.getCanonicalPath();
}
public static String addWatermark(String imageUrl, String watermarkText) throws IOException {
BufferedImage newImage = addWatermarkToImage(imageUrl, watermarkText);
// Save the new image with the watermark
File outputFile = new File("watermarked_image.jpg");
ImageIO.write(newImage, "jpg", outputFile);
log.info("Watermark added to image: " + imageUrl);
return outputFile.getCanonicalPath();
}
public static BufferedImage addWatermarkToImage(String imageUrl, String watermarkText) throws IOException {
// Load the original image from the URL
URL url = new URL(imageUrl);
BufferedImage originalImage = ImageIO.read(url);
// Create a new image with the same dimensions as the original
BufferedImage newImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_RGB);
// Create a graphics object to draw on the new image
Graphics2D graphics = newImage.createGraphics();
graphics.drawImage(originalImage, 0, 0, null);
// Determine the optimal font size for the watermark text
Font font = getOptimalFont(graphics, watermarkText, originalImage.getWidth(), originalImage.getHeight());
// Set the font and color for the watermark text
graphics.setFont(font);
graphics.setColor(Color.WHITE);
// Calculate the position of the watermark text
List<String> lines = splitTextIntoLines(watermarkText, graphics, originalImage.getWidth() * 0.9);
int lineHeight = graphics.getFontMetrics().getHeight();
int x = (int) (originalImage.getWidth() - getMaxLineWidth(lines, graphics)) / 2;
int y = (int) ((originalImage.getHeight() - (lines.size() * lineHeight * 0.5)) / 2);
// Add the watermark text to the image
for (String line : lines) {
graphics.drawString(line, x, y);
y += lineHeight;
}
// Clean up
graphics.dispose();
// // Convert the new image to a byte array
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// ImageIO.write(newImage, "jpg", baos);
// byte[] imageData = baos.toByteArray();
// return imageData;
return newImage;
}
private static Font getOptimalFont(Graphics2D graphics, String text, int maxWidth, int maxHeight) {
Font font = new Font("微软雅黑", Font.BOLD, 1);
Rectangle2D bounds = null;
while (bounds == null || bounds.getWidth() < maxWidth * 0.95) {
font = font.deriveFont(font.getSize() + 2f);
bounds = graphics.getFontMetrics(font).getStringBounds(text, graphics);
}
return font.deriveFont(font.getSize() - 1f);
}
private static List<String> splitTextIntoLines(String text, Graphics2D graphics, double maxWidth) {
List<String> lines = new ArrayList<>();
String[] words1 = text.split("\r\n");
for (String txt : words1) {
String[] words = txt.split("\\s+");
StringBuilder currentLine = new StringBuilder();
for (String word : words) {
if (graphics.getFontMetrics().getStringBounds(currentLine.toString() + " " + word, graphics).getWidth() <= maxWidth) {
currentLine.append(word).append(" ");
} else {
lines.add(currentLine.toString().trim());
currentLine = new StringBuilder(word + " ");
}
}
lines.add(currentLine.toString().trim());
}
return lines;
}
private static double getMaxLineWidth(List<String> lines, Graphics2D graphics) {
double maxWidth = 0;
for (String line : lines) {
double lineWidth = graphics.getFontMetrics().getStringBounds(line, graphics).getWidth();
if (lineWidth > maxWidth) {
maxWidth = lineWidth;
}
}
return maxWidth;
}
public static void main(String[] args) throws Exception {
String t = addWatermark("https://scrm.test.glsx.com.cn/group1/M00/05/1B/wKgD3mSQDHuAZlKuAAAG4brfhz8623.png",
"群名:自动化测试区\r\n批次:20230620-1122\r\n序号:1234\r\n群序号:232");
log.info(t);
}
}
\ No newline at end of file
package cn.com.glsx.charging.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* 获取IP地址工具类
*
* @author liujixiang
* @date 2018-11-08
*/
public final class IpUtil {
private IpUtil() {
throw new AssertionError();
}
/**
* 获取请求用户的IP地址
*
* @return
*/
public static String getRequestIp() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
return getRequestIp(request);
}
/**
* 获取请求用户的IP地址
*
* @param request
* @return
*/
public static String getRequestIp(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip = getLocalhostIp();
}
return ip;
}
public static String getLocalhostIp() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
}
return null;
}
}
package cn.com.glsx.charging.util;
import org.springframework.core.env.Environment;
import lombok.extern.slf4j.Slf4j;
/**
* @author liujixiang
* @date 2018-11-08
*/
@Slf4j
public class LoginUtil {
/**
* TOKEN有效时间,单位分钟
*/
public static Integer TOKEN_VALID_TIME_MINUTE;
static {
Environment environment = SpringContextUtil.getBean(Environment.class);
String time = environment.getProperty("fastspringboot.login.token.valid.time.minute");
TOKEN_VALID_TIME_MINUTE = Integer.valueOf(time);
log.info("TOKEN_VALID_TIME_MINUTE:{}", TOKEN_VALID_TIME_MINUTE);
}
// /**
// * 获取当前登陆用户对象
// * @return
// */
// public static LoginSysUserVo getLoginSysUser(){
// LoginSysUserVo loginSysUserVo = (LoginSysUserVo) HttpServletRequestUtil.getRequest().getAttribute(CommonConstant.LOGIN_SYS_USER);
// return loginSysUserVo;
// }
//
// /**
// * 获取当前登陆用户的ID
// * @return
// */
// public static String getUserId(){
// LoginSysUserVo loginSysUserVo = getLoginSysUser();
// if (loginSysUserVo !=null){
// return loginSysUserVo.getUserId();
// }
// return null;
// }
//
// /**
// * 获取当前登陆用户的账号
// * @return
// */
// public static String getAccount(){
// LoginSysUserVo loginSysUserVo = getLoginSysUser();
// if (loginSysUserVo !=null){
// return loginSysUserVo.getAccount();
// }
// return null;
// }
//
// /**
// * 获取当前登陆用户的名称
// * @return
// */
// public static String getUserName(){
// LoginSysUserVo loginSysUserVo = getLoginSysUser();
// if (loginSysUserVo !=null){
// return loginSysUserVo.getUserName();
// }
// return null;
// }
//
// /**
// * 判断是否是管理员,true:是,false:否
// * @return
// */
// public static Boolean isAdmin() {
// LoginSysUserVo loginSysUserVo = getLoginSysUser();
// if (loginSysUserVo !=null){
// return loginSysUserVo.getAdmin();
// }
// return null;
// }
}
package cn.com.glsx.charging.util;
import java.util.Map;
import com.google.common.collect.Maps;
public class MapUtils {
public static <K, V> Map<K, V> asMap(K k, V v) {
Map<K, V> m = Maps.newHashMap();
m.put(k, v);
return m;
}
}
/*
* @Copyright: 2014~2018 www.yyfax.com Inc. All rights reserved.
*/
package cn.com.glsx.charging.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* md5算法
*
* @author jiangmy
* @date 2018年1月15日 下午4:53:41
* @since 1.0.0
*/
public class Md5Utils {
/**
* 小写md5
*
* @param s
* @return
* @author jiangmy
* @date 2018年1月19日 上午10:02:29
* @since 1.0.0
*/
public final static String md5(String s) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
try {
byte[] btInput = s.getBytes(StandardCharsets.UTF_8.name());
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
byte[] md = mdInst.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 短md5,摘取第9至24位字符
*
* @param s
* @return
* @author jiangmy
* @date 2016-11-28 16:45:10
* @since v1.0.0
*/
public final static String smd5(String s) {
if (s == null) {
return null;
}
try {
return md5(s).substring(8, 24);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String md5Hex(String str) {
return DigestUtils.md5Hex(str);
}
public static String md5Hex(String str, String salt) throws Exception {
salt = new String(Base64.decodeBase64(salt), StandardCharsets.UTF_8);
return DigestUtils.md5Hex(str + salt);
}
private Md5Utils() {
}
/**
* 生成签名
*
* @param key 固定值672e10b319f8975e043b7a96d6f5298d
* @param n 固定值1
* @return
*/
public static String generateMD5(String key, int n) {
if (n == 0) {
return key.substring(4);
} else {
String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
return generateMD5("MD5:" + DigestUtils.md5Hex(key + date), n - 1);
}
}
}
package cn.com.glsx.charging.util;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Pair<K, V> implements Serializable {
private K key;
private V value;
public Pair() {
}
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
/**
* @return the key
*/
public final K getKey() {
return key;
}
/**
* @param key the key to set
*/
public final void setKey(K key) {
this.key = key;
}
/**
* @return the value
*/
public final V getValue() {
return value;
}
/**
* @param value the value to set
*/
public final void setValue(V value) {
this.value = value;
}
/**
* @return
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "[" + key + " : " + value + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Pair<?, ?> other = (Pair<?, ?>) obj;
if (key == null) {
if (other.key != null) {
return false;
}
} else if (!key.equals(other.key)) {
return false;
}
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}
public K first() {
return getKey();
}
public V second() {
return getValue();
}
}
\ No newline at end of file
package cn.com.glsx.charging.util;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import lombok.extern.slf4j.Slf4j;
/**
* 密码加密工具类
*
* @author liujixiang
* @date 2018-11-08
*/
@Slf4j
public class PasswordUtil {
private static final String KEY = "cn.com.glsx.charging.fastspringboot.pwd.key";
public static String encrypt(String pwd) {
if (StringUtils.isBlank(pwd)) {
return null;
}
pwd = pwd + KEY;
String newPwd = DigestUtils.sha256Hex(pwd) + DigestUtils.md5Hex(pwd);
return newPwd;
}
public static void main(String[] args) {
log.debug(encrypt("7c4a8d09ca3762af61e59520943dc26494f8941b"));
}
}
/**
*
*/
package cn.com.glsx.charging.util;
import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import cn.hutool.core.lang.Pair;
/**
* LRU缓存池
*
* @author jiangmy
* @date 2012-12-16
* @version 1.0.0
*/
public class PluralCache<K, V> {
private final LruMap<K, Pair<V, Long>> cache;
private final int cacheSeconds;
/**
* 本地缓冲构造函数
*
* @param maxSize
* 最大缓冲量
*/
public PluralCache(int maxSize) {
this.cache = new LruMap<>(maxSize);
this.cacheSeconds = Integer.MAX_VALUE;
}
public PluralCache(int maxSize, int cacheSeconds) {
this.cache = new LruMap<>(maxSize);
this.cacheSeconds = cacheSeconds;
}
/**
* 从本地缓冲获得和key对应的对象
*
* @param key
* @return
*/
public V get(K key) {
Pair<V, Long> pair = this.cache.get(key);
if (pair == null || System.currentTimeMillis() > pair.getValue()) {
return null;
}
return pair.getKey();
}
public Set<K> keySet() {
return this.cache.keySet();
}
/**
* 写入一个对象到本地缓冲
*
* @param key
* @param value
* @param seconds
* @return exists old value
*/
public boolean put(K key, V value, long seconds) {
Pair<V, Long> put = this.cache.put(key, new Pair<>(value, System.currentTimeMillis() + seconds * 1000L));
return put != null;
}
public boolean put(K key, V value, Date expire) {
if (expire == null) {
return put(key, value);
}
this.cache.put(key, new Pair<>(value, expire.getTime()));
return get(key) != null;
}
public boolean put(K key, V value) {
return put(key, value, this.cacheSeconds);
}
/**
* 从本地缓冲中删除和Key值对应的对象并返回
*
* @param key
* @return
*/
public boolean remove(K key) {
this.cache.remove(key);
return true;
}
public boolean containsKey(K key) {
return get(key) != null;
}
/**
* 清空缓存
*
* @return
*/
public boolean clear() {
this.cache.clear();
return true;
}
public int size() {
return this.cache.size();
}
static class LruMap<K, V> {
private Map<K, SoftReference<V>> cache;
/**
* 构造函数
*
* @param initCapacity
* int 此map的初始化大小
* @param maxSize
* int 此map最大容量,如map插入的数值超过此大小,最早被访问的元素将会被抛弃
*/
@SuppressWarnings("serial")
public LruMap(int initCapacity, final int maxSize) {
this.cache = Collections.synchronizedMap(new LinkedHashMap<K, SoftReference<V>>(initCapacity, maxSize) {
@Override
protected boolean removeEldestEntry(Map.Entry<K, SoftReference<V>> eldest) {
return size() >= maxSize;
}
});
}
/**
* @param maxSize
* 此map的最大容量,初始大小为最大容量的1/4
*/
public LruMap(final int maxSize) {
this(maxSize >> 2, maxSize);
}
/**
* 写入key和value
*
* @param key
* @param val
* @return
*/
public V put(K key, V val) {
SoftReference<V> r = new SoftReference<>(val);
SoftReference<V> v = this.cache.put(key, r);
return v == null ? null : v.get();
}
/**
* 根据key获取value
*
* @param key
* @return
*/
public V get(K key) {
SoftReference<V> r = this.cache.get(key);
return r == null ? null : r.get();
}
/**
* 删除缓存中数据
*
* @param key
* @return
*/
public V remove(K key) {
SoftReference<V> r = this.cache.remove(key);
return r == null ? null : r.get();
}
/**
* 清除全部数据
*/
public void clear() {
this.cache.clear();
}
/**
* @return
*/
public Set<K> keySet() {
return this.cache.keySet();
}
/**
* @return
*/
public int size() {
return this.cache.size();
}
}
/**
* cas
*
* @author jiangmy
* @date 2017-05-15 09:33:53
* @since v1.0.0
* @param key
*/
@SuppressWarnings("unchecked")
public int incrAndGet(K key) {
int value = 0;
synchronized (this.cache) {
V v = get(key);
if (v != null && !(v instanceof Integer)) {
throw new RuntimeException("不支持自增!");
}
if (v != null) {
value = (Integer) v;
}
value++;
put(key, (V) Integer.valueOf(value));
}
return value;
}
}
package cn.com.glsx.charging.util;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;
import java.util.Properties;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.PropertiesConfigurationLayout;
import lombok.extern.slf4j.Slf4j;
/**
* @author kome.Jiangmy
* @version 1.0
* @created 2012-9-28 下午2:04:35
*/
@Slf4j
public class PropertiesUtils {
private static PluralCache<String, Properties> cache = new PluralCache<>(200);
/**
* 读取配置: 先从 src/main/resources 目录查找,没有则从classpath查找
*
* @param filePath
* @return
*/
public static Properties loadProperties(String filePath) {
log.info("读取配置文件:{} ", filePath);
Properties properties = cache.get(filePath);
if (properties != null) {
return properties;
}
properties = new Properties();
String projectFile = SystemUtils.getProjectFile(filePath);
if (projectFile != null) {
log.info("读取配置文件:{} -> {}", filePath, projectFile);
try (InputStream inputStream = new FileInputStream(projectFile)) {
properties.load(inputStream);
} catch (IOException e) {
log.warn("Failed load properties file[" + filePath + "], please check it !!!!!!!!!\n");
}
} else {
try (InputStream in = PropertiesUtils.class.getClassLoader().getResourceAsStream(filePath)) { // 默认加载classpath的
properties.load(in);
} catch (IOException es) {
log.error(filePath, es.getMessage());
return null;
}
}
Pattern pattern = Pattern.compile("\\$\\{(.[^\\{\\}]*)\\}");
Matcher matcher;
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String value = (String) entry.getValue();
matcher = pattern.matcher(value);
while (matcher.find()) {
value = value.replace(matcher.group(), (CharSequence) properties.get(matcher.group(1)));
properties.setProperty((String) entry.getKey(), value);
}
}
log.info("--------------------- load properties from " + filePath + " ---------------------");
SortedMap<Object, Object> sortedMap = new TreeMap<>(properties);
for (Map.Entry<Object, Object> entry : sortedMap.entrySet()) {
log.info(entry.getKey() + "=" + entry.getValue());
}
log.info("--------------- finish load properties " + filePath + " sucess !!!! -------------");
if (properties != null && !properties.isEmpty()) {
cache.put(filePath, properties);
}
return properties;
}
public static String getProperty(String file, String key) {
return getProperty(file, key, "");
}
public static String getProperty(String file, String key, String defaultValue) {
Properties properties = loadProperties(file);
return properties.getProperty(key, defaultValue);
}
/**
* @function updateProperty更新配置文件(但是写入value中中文乱码,未解决)
* commons.configuration2 第三方包
*/
public static void updateProperty(String filePath, String key, String newValue) {
PropertiesConfiguration config = new PropertiesConfiguration();
PropertiesConfigurationLayout layout = config.getLayout();
String projectFile = SystemUtils.getProjectFile(filePath);
if (projectFile == null) {
return;
}
try (InputStream inputStream = new FileInputStream(projectFile)) {
layout.load(config, new InputStreamReader(inputStream));
Object old = config.getProperty(key);
config.setProperty(key, newValue);
layout.save(config, new OutputStreamWriter(new FileOutputStream(projectFile, false)));
cache.remove(filePath);
log.debug("【{}】Fr: {} = {}", filePath, key, old);
log.info("【{}】To: {} = {}", filePath, key, newValue);
} catch (Exception e) {
e.printStackTrace();
}
}
private PropertiesUtils() {
}
public static void main(String[] args) {
loadProperties("cfg.properties");
loadProperties("log4j.properties");
loadProperties("*.properties");
}
}
package cn.com.glsx.charging.util;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
/**
* @author liujixiang
* @date 2018-11-08
*/
@Component
@Slf4j
public class RedisCacheUtil {
private static RedisCacheUtil redisCacheUtil;
@Autowired
private RedisTemplate redisTemplate;
/**
* 将当前对象赋值给静态对象,调用spring组件: redisCacheUtil.redisTemplate.xxx()
*/
@PostConstruct
public void init() {
redisCacheUtil = this;
}
}
package cn.com.glsx.charging.util;
/**
* @author liujixiang
* @date 2018-11-08
*/
public interface RedisKey {
/**
* 所有区域List的key
*/
String ALL_AREA_LIST = "all_area_list";
/**
* 所有区域Map的key
*/
String ALL_AREA_MAP = "all_area_map";
}
package cn.com.glsx.charging.util;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
/**
* Twitter_Snowflake<br>
* SnowFlake的结构如下(每部分用-分开):<br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
* 41位时间截(毫秒级),注意,41位时间截不是存储当前时间的时间截,而是存储时间截的差值(当前时间截 - 开始时间截)
* 得到的值),这里的的开始时间截,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间截,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 *
* 365) = 69<br>
* 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
* 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间截)产生4096个ID序号<br>
* 加起来刚好64位,为一个Long型。<br>
* 注意:本id生成算法取ipv4的地址作为worker_index,regin_index默认为0(适用于中型系统,不考虑跨机房情况),
* 方便自动化部署 ,以ip地址做workerid好处,最大为255 + 255 + 255 + 255 =1020 未超出1024 ,方便使用
*
* @author lixin
* @date 2018-03-06 09:02:24
*/
public class SnowFlakeIdUtils {
// ==============================Fields===========================================
/** 开始时间截 (2018-01-01) */
private final static long twepoch = LocalDateTime.parse("2018-03-01T00:00:00").atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli();
/** 机器id所占的位数 */
private final static long workerIdBits = 5L;
/** 数据标识id所占的位数 */
private final static long datacenterIdBits = 5L;
// /** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
// private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
//
// /** 支持的最大数据标识id,结果是31 */
// private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
/** 序列在id中占的位数 */
private final static long sequenceBits = 12L;
/** 机器ID向左移12位 */
private final static long workerIdShift = sequenceBits;
/** 数据标识id向左移17位(12+5) */
private final static long datacenterIdShift = sequenceBits + workerIdBits;
/** 时间截向左移22位(5+5+12) */
private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
/** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
/** 工作机器ID(0~31) */
private long workerId = 0L;
/** 数据中心ID(0~31) */
private long datacenterId = 0L;
/** 毫秒内序列(0~4095) */
private long sequence = 0L;
/** 上次生成ID的时间截 */
private long lastTimestamp = -1L;
public static SnowFlakeIdUtils snowflake = new SnowFlakeIdUtils();
// ==============================Constructors=====================================
/**
* 构造函数
*
* @param workerId 工作ID (0~31)
* @param datacenterId 数据中心ID (0~31)
*/
public SnowFlakeIdUtils() {
this.workerId = getIPAddr();
}
/**
* 获取long性ip地址,以ip地址的四个位数累加求和得出
*
* @author lixin
* @date 2018-03-06 10:51:13
* @since 1.0
* @return
*/
private static long getIPAddr() {
long ipAddr = 0L;
InetAddress address;
try {
address = InetAddress.getLocalHost();
} catch (final UnknownHostException e) {
throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!");
}
byte[] ipAddressByteArray = address.getAddress();
ipAddr = ((ipAddressByteArray[ipAddressByteArray.length - 2] & 0B11) << Byte.SIZE)
+ (ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF);
return ipAddr;
}
public static long generate() {
return snowflake.nextId();
}
public static String generateStr() {
return generate() + "";
}
public static long generate(int bitNum) {
long id = snowflake.nextId();
String ids = String.valueOf(id);
return Long.parseLong(ids.substring(ids.length() - bitNum, ids.length()));
}
// ==============================Methods==========================================
/**
* 获得下一个ID (该方法是线程安全的)
*
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
// 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
// 如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
// 毫秒内序列溢出
if (sequence == 0) {
// 阻塞到下一个毫秒,获得新的时间戳
timestamp = tilNextMillis(lastTimestamp);
}
}
// 时间戳改变,毫秒内序列重置
else {
sequence = 0L;
}
// 上次生成ID的时间截
lastTimestamp = timestamp;
// 移位并通过或运算拼到一起组成64位的ID
return ((timestamp - twepoch) << timestampLeftShift) // 42位
| (datacenterId << datacenterIdShift) // 5位
| (workerId << workerIdShift) // 5位
| sequence; // 12位
}
/**
* 阻塞到下一个毫秒,直到获得新的时间戳
*
* @param lastTimestamp 上次生成ID的时间截
* @return 当前时间戳
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
if (lastTimestamp - timestamp > 3000) {
try {
System.out.println("时钟回拨时间超过3秒!!! last:" + lastTimestamp + " cur:" + timestamp);
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return timestamp;
}
/**
* 返回以毫秒为单位的当前时间
*
* @return 当前时间(毫秒)
*/
protected long timeGen() {
return System.currentTimeMillis();
}
// ==============================Test===========================================
/** 测试 */
public static void main(String[] args) {
/*
* for (int i = 0; i < 1000; i++) {
* long id = SnowFlakeIdUtils.generate();
* String str = StringUtils.leftPad(Long.toBinaryString(id), 64, "0");
* // System.out.println(id + " -> " + str);
* str = str.substring(0, 42) + "-" + str.substring(42, 47) + "-" + str.substring(47, 52) + "-" + str.substring(52, 64);
* System.out.println(id + " -> " + str);
* }
* System.out.println(SnowFlakeIdUtils.getIPAddr());
* System.out.println(IpUtils.getLocalIp());
* System.out.println(IpUtils.getIpInt(IpUtils.getLocalIp()));
*/
int i = 0;
while (i++ < 100) {
System.out.println(System.nanoTime() + "\t" + System.currentTimeMillis() + "\t" + SnowFlakeIdUtils.generate() + "\t"
+ SnowFlakeIdUtils.generate(12));
}
}
}
package cn.com.glsx.charging.util;
import java.text.ParseException;
/**
* Twitter_Snowflake<br>
* SnowFlake的结构如下(每部分用-分开):<br>
* 0 - 0000000000 0000000000 0000000000 0000000000 0 - 00000 - 00000 - 000000000000 <br>
* 1位标识,由于long基本类型在Java中是带符号的,最高位是符号位,正数是0,负数是1,所以id一般是正数,最高位是0<br>
* 41位时间戳(毫秒级),注意,41位时间戳不是存储当前时间的时间戳,而是存储时间戳的差值(当前时间戳 - 开始时间戳)
* 得到的值),这里的的开始时间戳,一般是我们的id生成器开始使用的时间,由我们程序来指定的(如下下面程序IdWorker类的startTime属性)。41位的时间戳,可以使用69年,年T = (1L << 41) / (1000L * 60 * 60 * 24 * 365) = 69<br>
* 10位的数据机器位,可以部署在1024个节点,包括5位datacenterId和5位workerId<br>
* 12位序列,毫秒内的计数,12位的计数顺序号支持每个节点每毫秒(同一机器,同一时间戳)产生4096个ID序号<br>
* 加起来刚好64位,为一个Long型。<br>
* SnowFlake的优点是,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞(由数据中心ID和机器ID作区分),并且效率较高,经测试,SnowFlake每秒能够产生26万ID左右。
*/
public class SnowFlakeUtil {
// ==============================Fields===========================================
/** 开始时间截 (201-01-01) */
private final long twepoch = 1514736000000L;
/** 机器id所占的位数 */
private final long workerIdBits = 5L;
/** 数据标识id所占的位数 */
private final long datacenterIdBits = 5L;
/** 支持的最大机器id,结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数) */
private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
/** 支持的最大数据标识id,结果是31 */
private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
/** 序列在id中占的位数 */
private final long sequenceBits = 12L;
/** 机器ID向左移12位 */
private final long workerIdShift = sequenceBits;
/** 数据标识id向左移17位(12+5) */
private final long datacenterIdShift = sequenceBits + workerIdBits;
/** 时间截向左移22位(5+5+12) */
private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
/** 生成序列的掩码,这里为4095 (0b111111111111=0xfff=4095) */
private final long sequenceMask = -1L ^ (-1L << sequenceBits);
/** 工作机器ID(0~31) */
private long workerId;
/** 数据中心ID(0~31) */
private long datacenterId;
/** 毫秒内序列(0~4095) */
private long sequence = 0L;
/** 上次生成ID的时间截 */
private long lastTimestamp = -1L;
// ==============================Constructors=====================================
/**
* 构造函数
*
* @param workerId 工作ID (0~31)
* @param datacenterId 数据中心ID (0~31)
*/
public SnowFlakeUtil(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
// ==============================Methods==========================================
/**
* 获得下一个ID (该方法是线程安全的)
*
* @return SnowflakeId
*/
public synchronized long nextId() {
long timestamp = timeGen();
// 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过这个时候应当抛出异常
if (timestamp < lastTimestamp) {
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
// 如果是同一时间生成的,则进行毫秒内序列
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
// 毫秒内序列溢出
if (sequence == 0) {
// 阻塞到下一个毫秒,获得新的时间戳
timestamp = tilNextMillis(lastTimestamp);
}
}
// 时间戳改变,毫秒内序列重置
else {
sequence = 0L;
}
// 上次生成ID的时间截
lastTimestamp = timestamp;
// 移位并通过或运算拼到一起组成64位的ID
return ((timestamp - twepoch) << timestampLeftShift) //
| (datacenterId << datacenterIdShift) //
| (workerId << workerIdShift) //
| sequence;
}
/**
* 阻塞到下一个毫秒,直到获得新的时间戳
*
* @param lastTimestamp 上次生成ID的时间截
* @return 当前时间戳
*/
protected long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 返回以毫秒为单位的当前时间
*
* @return 当前时间(毫秒)
*/
protected long timeGen() {
return System.currentTimeMillis();
}
// ==============================Test=============================================
/**
* 测试
*
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
SnowFlakeUtil idWorker = new SnowFlakeUtil(0, 0);
for (int i = 0; i < 10; i++) {
long id = idWorker.nextId();
System.out.println(id + "\t" + Long.toBinaryString(id));
}
// System.out.println(DateUtil.parseDateTime("2020-10-22 12:47:41").getTime());
}
}
\ No newline at end of file
package cn.com.glsx.charging.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* Spring工具类,获取Spring上下文对象等
*
* @author liujixiang
* @date 2018-11-08
*/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringContextUtil.applicationContext == null) {
SpringContextUtil.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
}
\ No newline at end of file
package cn.com.glsx.charging.util;
/**
* @author liujixiang
* @date 2018-11-08
*/
public class StorageDB {
}
/**
*
*/
package cn.com.glsx.charging.util;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import com.google.common.collect.Lists;
import cn.hutool.core.util.StrUtil;
/**
* lc-util
*
* @author kome
* @date 2020年6月23日 上午10:44:14
*/
public class StrUtils {
/**
* 匹配_加任意一个字符
*/
private static final Pattern UNDER_LINE_PATTERN = Pattern.compile("_(\\w)");
/***
* 下划线命名转为驼峰命名
*
* @param source
* 下划线命名的字符串
*/
public static String underlineToHump(String source) {
StringBuffer result = new StringBuffer();
String a[] = source.split("_");
for (String s : a) {
if (result.length() == 0) {
result.append(s.toLowerCase());
} else {
result.append(s.substring(0, 1).toUpperCase());
result.append(s.substring(1).toLowerCase());
}
}
return result.toString();
}
/***
* 驼峰命名转为下划线命名
*
* @param source
* 驼峰命名的字符串
*/
public static String humpToUnderline(String source) {
StringBuffer sb = new StringBuffer(source);
int temp = 0;// 定位
for (int i = 0; i < source.length(); i++) {
if (Character.isUpperCase(source.charAt(i))) {
sb.insert(i + temp, "_");
temp += 1;
}
}
return sb.toString().toUpperCase();
}
/**
* Description: 下划线转为驼峰格式
*
* @param source 原字符串
* @return java.lang.String 返回转换后的驼峰格式字符串
*/
public static String underLineToCamel(String source) {
// 用Pattern类的matcher()方法生成一个Matcher对象
Matcher matcher = UNDER_LINE_PATTERN.matcher(source);
StringBuffer result = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(result, matcher.group(1).toUpperCase());
}
matcher.appendTail(result);
return result.toString();
}
public static String numberFormat(Number n, int scale) {
return new BigDecimal(ObjectUtils.defaultIfNull(n, 0).toString()).setScale(scale, RoundingMode.HALF_UP).toString();
}
public static String percentFormat(Number n, int scale) {
return new BigDecimal(n.toString()).multiply(new BigDecimal(100)).setScale(scale, RoundingMode.HALF_UP).toString().concat("%");
}
public static String defaultIfBlank(String s, String dft) {
return StringUtils.isBlank(s) ? dft : s;
}
public static java.util.List<String> splitToList(String string, String split) {
if (StringUtils.isBlank(string)) {
return Lists.newArrayList();
}
return com.google.common.collect.Lists.newArrayList(org.apache.commons.lang3.StringUtils.split(string, split));
}
public static String subAppend(String json, int len, String string) {
if (StringUtils.isEmpty(json) || json.length() <= len) {
return json;
}
return StringUtils.substring(json, 0, len) + string;
}
public static String ifBlankElse(String v, String defaultV, String str) {
return StringUtils.isBlank(v) ? defaultV : str;
}
public static String isoToUTF(String string) throws Exception {
// 判断是否为空
if (!StrUtil.isNullOrUndefined(string)) {
// 判断是乱码 (GBK包含全部中文字符;UTF-8则包含全世界所有国家需要用到的字符。)
if (!(java.nio.charset.Charset.forName("GBK").newEncoder().canEncode(string))) {
return new String(string.getBytes("ISO-8859-1"), "utf-8"); // 转码UTF8
} else {
return string;
}
} else {
return "";
}
}
/**
* 是否乱码:只要有非乱码的字符就不是乱码
*
* @param strName
* @return
*/
public static boolean isMessyCode(String strName) {
try {
Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
Matcher m = p.matcher(strName);
String after = m.replaceAll("");
String temp = after.replaceAll("\\p{P}", "");
char[] ch = temp.trim().toCharArray();
int length = (ch != null) ? ch.length : 0;
for (int i = 0; i < length; i++) {
String str = "" + ch[i];
if (str.matches("[\u4e00-\u9fa5]+") || Character.isLetterOrDigit(ch[i])) {
// 只要有中文,就不是乱码
return false;
}
}
for (int i = 0; i < length; i++) {
char c = ch[i];
String str = "" + ch[i];
if (!Character.isLetterOrDigit(c)) {
if (!str.matches("[\u4e00-\u9fa5]+")) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 是否包含乱码
*
* @param strName
* @return
*/
public static boolean hasMessyCode(String strName) {
try {
Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
Matcher m = p.matcher(strName);
String after = m.replaceAll("");
String temp = after.replaceAll("\\p{P}", "");
char[] ch = temp.trim().toCharArray();
int length = (ch != null) ? ch.length : 0;
for (int i = 0; i < length; i++) {
char c = ch[i];
String str = "" + ch[i];
if (!Character.isLetterOrDigit(c)) {
if (!str.matches("[\u4e00-\u9fa5]+")) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 是否包含正常字符
*
* @param strName
* @return
*/
public static boolean hasNormalCode(String strName) {
try {
Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
Matcher m = p.matcher(strName);
String after = m.replaceAll("");
String temp = after.replaceAll("\\p{P}", "");
char[] ch = temp.trim().toCharArray();
int length = (ch != null) ? ch.length : 0;
for (int i = 0; i < length; i++) {
char c = ch[i];
if (Character.isLetterOrDigit(c)) {
return true;
}
String str = "" + ch[i];
if (str.matches("[\u4e00-\u9fa5]+")) {
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean containsChinese(String str) {
if (str == null || str.trim().isEmpty()) {
return false;
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 0x4E00 && c <= 0x9FA5) {
return true;
}
}
return false;
}
public static void main(String[] args) {
// System.out.println(numberFormat(10.0456, 3));
// System.out.println(numberFormat(102345d / 10000, 2));
// System.out.println(percentFormat(0.1456, 2));
//
// Map<String, Object> map = Maps.newHashMap();
// map.put("value", 102345);
// map.put("StrUtils", StrUtils.class);
// String v = ExpressionUtils.executeExpression("StrUtils.numberFormat(value / 10000d, 2)", map);
// System.out.println(v);
//
// System.out.println(isMessyCode("test"));
// System.out.println(isMessyCode(Base64.decodeStr("test")));
// System.out.println(isMessyCode(Base64.decodeStr("6YCK8J+kk+WFi++8gQ==")));
// System.out.println(isMessyCode("逊🤓克!"));
// String value = "7aC97bKk";
String value = "7oS8aVRyZWU=";
// String value = "8J+mhvCflkU=";
System.out.println(value);
if (Base64.isBase64(value)) {
// 判断是否切换编码格式
// value = Base64.decodeStr(value);
String decode = new String(org.apache.commons.codec.binary.Base64.decodeBase64(value));
// 解码后不是乱码才解码,对emoji表情单独处理
if (StrUtils.hasNormalCode(decode)) {
value = decode;
}
}
System.out.println(value);
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!