Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
platform
/
platform-charging-server
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 81f2091a
authored
Nov 03, 2023
by
tiger
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
ocpp16
1 parent
3d31b918
Show whitespace changes
Inline
Side-by-side
Showing
79 changed files
with
10488 additions
and
168 deletions
platform-charging/pom.xml
platform-charging/src/main/java/cn/com/glsx/charging/Application.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/ClientMain.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/Ocpp16Constants.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/Ocpp16Helper.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/ServerMain.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpBase.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpCallback.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpData.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpErrorEnum.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpHandler.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpMapper.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpReq.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpRsp.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/client/TcpClient.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/client/TcpClientHandler.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/client/handler/LoginReqHandler.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/data/LoginReqData.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/data/LoginRspData.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/impl/LoginReq.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/impl/LoginRsp.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/ProxyHelper.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/ProxyInfo.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/ProxyUser.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/TcpServer.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/TcpServerHandler.java
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/handler/LoginReqHandler.java
platform-charging/src/main/java/cn/com/glsx/charging/util/BeanUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/BrowserUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/ByteUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/CallbackTask.java
platform-charging/src/main/java/cn/com/glsx/charging/util/ClassUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/ClassUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/CloseableUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/CrcUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/DateUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/DateUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/EnumUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/FileFormatUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/HttpServletRequestUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/HttpServletResponseUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/HttpUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/ImageUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/IpUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/JacksonUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/LoginUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/MapUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/Md5Utils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/Pair.java
platform-charging/src/main/java/cn/com/glsx/charging/util/PasswordUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/PluralCache.java
platform-charging/src/main/java/cn/com/glsx/charging/util/PropertiesUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/RedisCacheUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/RedisKey.java
platform-charging/src/main/java/cn/com/glsx/charging/util/SnowFlakeIdUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/SnowFlakeUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/SpringContextUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/StorageDB.java
platform-charging/src/main/java/cn/com/glsx/charging/util/StrUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/SystemUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/Task.java
platform-charging/src/main/java/cn/com/glsx/charging/util/TaskExecutor.java
platform-charging/src/main/java/cn/com/glsx/charging/util/TimeStackUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/TimeUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/TokenUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/TypeConvertUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/UUIDUtil.java
platform-charging/src/main/java/cn/com/glsx/charging/util/VOHelpler.java
platform-charging/src/main/java/cn/com/glsx/charging/util/VerificationCode.java
platform-charging/src/main/java/cn/com/glsx/charging/util/WebUtils.java
platform-charging/src/main/java/cn/com/glsx/charging/util/package-info.java
platform-charging/src/main/resources/application.properties_standalone
platform-charging/src/main/resources/bootstrap.properties
platform-charging/src/main/resources/logback-spring.xml → platform-charging/src/main/resources/logback.xml
platform-charging/src/test/java/cn/com/glsx/charging/ClientTest.java
platform-charging/src/test/java/cn/com/glsx/charging/ServerTest.java
platform-charging/src/test/java/cn/com/glsx/charging/TestApplication.java
platform-charging/src/test/java/cn/com/glsx/charging/cn/com/glsx/TestApplication.java
platform-charging/src/test/java/cn/com/glsx/charging/util/JsonSerializationExample.java
platform-charging/pom.xml
View file @
81f2091
<?xml version="1.0" encoding="UTF-8"?>
<?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"
>
<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>
<parent>
<groupId>
cn.com.glsx.charging
</groupId>
<groupId>
cn.com.glsx.charging
</groupId>
<artifactId>
platform-charging-server
</artifactId>
<artifactId>
platform-charging-server
</artifactId>
...
@@ -18,7 +20,8 @@
...
@@ -18,7 +20,8 @@
<artifactId>
rest-admin-context
</artifactId>
<artifactId>
rest-admin-context
</artifactId>
</dependency>
</dependency>
<!-- 接入微服务组件联盟 配置、注册、网关、链路、监控等 ,单体应用无需引入(logback-spring.xml与logstash相关内容需要注释掉)-->
<!-- 接入微服务组件联盟 配置、注册、网关、链路、监控等
,单体应用无需引入(logback-spring.xml与logstash相关内容需要注释掉)-->
<dependency>
<dependency>
<groupId>
com.glsx
</groupId>
<groupId>
com.glsx
</groupId>
<artifactId>
rest-admin-alliance
</artifactId>
<artifactId>
rest-admin-alliance
</artifactId>
...
@@ -50,6 +53,59 @@
...
@@ -50,6 +53,59 @@
<artifactId>
rpc-scrm-proxy-api
</artifactId>
<artifactId>
rpc-scrm-proxy-api
</artifactId>
<version>
3.7.0-SNAPSHOT
</version>
<version>
3.7.0-SNAPSHOT
</version>
</dependency>
</dependency>
<!-- 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>
</dependencies>
<build>
<build>
...
...
platform-charging/src/main/java/cn/com/glsx/charging/Application.java
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
;
package
cn
.
com
.
glsx
.
charging
;
import
com.glsx.plat.context.EnableRestAdmin
;
import
static
java
.
time
.
ZoneId
.
of
;
import
org.apache.dubbo.config.spring.context.annotation.EnableDubbo
;
import
static
java
.
util
.
TimeZone
.
getTimeZone
;
import
java.util.TimeZone
;
import
javax.annotation.PostConstruct
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
import
org.springframework.boot.autoconfigure.SpringBootApplication
;
import
org.springframework.cloud.client.discovery.EnableDiscoveryClient
;
import
org.springframework.cloud.client.discovery.EnableDiscoveryClient
;
import
org.springframework.cloud.openfeign.EnableFeignClients
;
import
org.springframework.cloud.openfeign.EnableFeignClients
;
import
org.springframework.context.annotation.EnableMBeanExport
;
import
org.springframework.context.annotation.PropertySource
;
import
org.springframework.jmx.support.RegistrationPolicy
;
import
org.springframework.transaction.annotation.EnableTransactionManagement
;
import
javax.annotation.PostConstruct
;
import
java.util.TimeZone
;
import
static
java
.
time
.
ZoneId
.
of
;
import
com.glsx.plat.context.EnableRestAdmin
;
import
static
java
.
util
.
TimeZone
.
getTimeZone
;
/**
/**
* @author payu
* @author payu
...
@@ -23,6 +22,7 @@ import static java.util.TimeZone.getTimeZone;
...
@@ -23,6 +22,7 @@ import static java.util.TimeZone.getTimeZone;
@EnableDiscoveryClient
@EnableDiscoveryClient
@EnableFeignClients
(
basePackages
=
{
"cn.com.glsx.charging.*.api"
})
@EnableFeignClients
(
basePackages
=
{
"cn.com.glsx.charging.*.api"
})
@SpringBootApplication
@SpringBootApplication
@PropertySource
(
"application.properties_standalone"
)
public
class
Application
{
public
class
Application
{
public
static
void
main
(
String
[]
args
)
{
public
static
void
main
(
String
[]
args
)
{
...
...
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/ClientMain.java
0 → 100644
View file @
81f2091
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
();
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/Ocpp16Constants.java
0 → 100644
View file @
81f2091
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
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/Ocpp16Helper.java
0 → 100644
View file @
81f2091
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
\ No newline at end of file
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/ServerMain.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpBase.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpCallback.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpData.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpErrorEnum.java
0 → 100644
View file @
81f2091
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
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpHandler.java
0 → 100644
View file @
81f2091
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
);
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpMapper.java
0 → 100644
View file @
81f2091
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
();
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpReq.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
modules
.
ocpp
.
ocpp16
.
tcp
.
base
;
public
interface
TcpReq
<
D
extends
TcpData
>
{
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/base/TcpRsp.java
0 → 100644
View file @
81f2091
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
());
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/client/TcpClient.java
0 → 100644
View file @
81f2091
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
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/client/TcpClientHandler.java
0 → 100644
View file @
81f2091
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
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/client/handler/LoginReqHandler.java
0 → 100644
View file @
81f2091
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"
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/data/LoginReqData.java
0 → 100644
View file @
81f2091
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
;
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/data/LoginRspData.java
0 → 100644
View file @
81f2091
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
;
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/impl/LoginReq.java
0 → 100644
View file @
81f2091
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
());
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/impl/LoginRsp.java
0 → 100644
View file @
81f2091
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
());
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/ProxyHelper.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/ProxyInfo.java
0 → 100644
View file @
81f2091
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
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/ProxyUser.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/TcpServer.java
0 → 100644
View file @
81f2091
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);
// }
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/TcpServerHandler.java
0 → 100644
View file @
81f2091
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
();
}
}
platform-charging/src/main/java/cn/com/glsx/charging/modules/ocpp/ocpp16/tcp/server/handler/LoginReqHandler.java
0 → 100644
View file @
81f2091
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"
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/BeanUtils.java
0 → 100644
View file @
81f2091
/*
* @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
()
{
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/BrowserUtil.java
0 → 100644
View file @
81f2091
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
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/ByteUtils.java
0 → 100644
View file @
81f2091
/*
* @Copyright: 2014~2018 www.yyfax.com Inc. All rights reserved.
*/
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.nio.ByteBuffer
;
import
java.nio.ByteOrder
;
import
java.util.Arrays
;
import
java.util.Calendar
;
import
java.util.Date
;
import
org.apache.commons.codec.DecoderException
;
import
org.apache.commons.codec.binary.Hex
;
import
cn.hutool.core.util.HexUtil
;
/**
* byte操作
*
* @author jiangmy
* @date 2018年1月17日 上午9:42:24
* @since 1.0.0
*/
public
class
ByteUtils
{
/**
* 转hex串
*
* @param bytes
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:23:28
* @since 1.0.0
*/
public
static
String
toHex
(
byte
[]
bytes
)
{
return
Hex
.
encodeHexString
(
bytes
).
toUpperCase
();
}
/**
* 从hex串转回
*
* @param hex
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:24:22
* @since 1.0.0
*/
public
static
byte
[]
fromHex
(
String
hex
)
{
try
{
return
Hex
.
decodeHex
(
hex
.
toCharArray
());
}
catch
(
DecoderException
e
)
{
throw
new
RuntimeException
();
}
}
/**
* 大小端转换
*
* @param i
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:24:54
* @since 1.0.0
*/
public
static
int
reverse
(
int
i
)
{
ByteBuffer
buffer
=
ByteBuffer
.
allocate
(
4
);
buffer
.
order
(
ByteOrder
.
BIG_ENDIAN
);
buffer
.
asIntBuffer
().
put
(
i
);
buffer
.
order
(
ByteOrder
.
LITTLE_ENDIAN
);
return
buffer
.
getInt
();
}
/**
* 大小端转换
*
* @param i
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:29:27
* @since 1.0.0
*/
public
static
long
reverse
(
long
i
)
{
ByteBuffer
buffer
=
ByteBuffer
.
allocate
(
8
);
buffer
.
order
(
ByteOrder
.
BIG_ENDIAN
);
buffer
.
asLongBuffer
().
put
(
i
);
buffer
.
order
(
ByteOrder
.
LITTLE_ENDIAN
);
return
buffer
.
getLong
();
}
/**
* 大小端转换
*
* @param s
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:41:24
* @since 1.0.0
*/
public
static
short
reverse
(
short
s
)
{
ByteBuffer
buffer
=
ByteBuffer
.
allocate
(
2
);
buffer
.
order
(
ByteOrder
.
BIG_ENDIAN
);
buffer
.
asLongBuffer
().
put
(
s
);
buffer
.
order
(
ByteOrder
.
LITTLE_ENDIAN
);
return
buffer
.
getShort
();
}
/**
* 倒置
*
* @param array
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:35:42
* @since 1.0.0
*/
public
static
byte
[]
reverse
(
byte
[]
array
)
{
if
(
array
==
null
)
{
return
array
;
}
int
i
=
0
;
int
j
=
array
.
length
-
1
;
while
(
j
>
i
)
{
byte
tmp
=
array
[
j
];
array
[
j
]
=
array
[
i
];
array
[
i
]
=
tmp
;
--
j
;
++
i
;
}
return
array
;
}
/**
* 截取数组
*
* @author jiangmy
* @date 2017年7月5日 下午2:43:41
* @since v1.0.0
* @param buff
* @param offset
* @return
*/
public
static
byte
[]
getBytes
(
byte
[]
buff
,
int
offset
)
{
return
ByteUtils
.
getBytes
(
buff
,
offset
,
buff
.
length
-
offset
);
}
/**
* 截取数组
*
* @author jiangmy
* @date 2017年7月5日 下午2:43:53
* @since v1.0.0
* @param buff
* @param offset
* @param length
* @return
*/
public
static
byte
[]
getBytes
(
byte
[]
buff
,
int
offset
,
int
length
)
{
return
Arrays
.
copyOfRange
(
buff
,
offset
,
offset
+
length
);
}
/**
* 转换
*
* @param b
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:36:19
* @since 1.0.0
*/
public
static
byte
[]
putByte
(
byte
b
)
{
byte
[]
buff
=
new
byte
[
1
];
ByteUtils
.
putByte
(
buff
,
0
,
b
);
return
buff
;
}
/**
* 转换
*
* @param buff
* @param offset
* @param b
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:36:28
* @since 1.0.0
*/
public
static
int
putByte
(
byte
[]
buff
,
int
offset
,
byte
b
)
{
buff
[
offset
]
=
b
;
return
1
;
}
/**
* 取位
*
* @param buff
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:36:39
* @since 1.0.0
*/
public
static
byte
getByte
(
byte
[]
buff
)
{
return
ByteUtils
.
getByte
(
buff
,
0
);
}
/**
* 取位
*
* @param buff
* @param offset
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:36:49
* @since 1.0.0
*/
public
static
byte
getByte
(
byte
[]
buff
,
int
offset
)
{
return
buff
[
offset
];
}
/**
* 转换
*
* @param b
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:37:00
* @since 1.0.0
*/
public
static
byte
[]
putBoolean
(
boolean
b
)
{
byte
[]
buff
=
new
byte
[
1
];
ByteUtils
.
putBoolean
(
buff
,
0
,
b
);
return
buff
;
}
/**
* 转换
*
* @param buff
* @param offset
* @param b
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:37:20
* @since 1.0.0
*/
public
static
int
putBoolean
(
byte
[]
buff
,
int
offset
,
boolean
b
)
{
buff
[
offset
]
=
(
byte
)
(
b
?
1
:
0
);
return
1
;
}
/**
* 取位
*
* @param buff
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:37:31
* @since 1.0.0
*/
public
static
boolean
getBoolean
(
byte
[]
buff
)
{
return
ByteUtils
.
getBoolean
(
buff
,
0
);
}
/**
* 取位
*
* @param buff
* @param offset
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:37:42
* @since 1.0.0
*/
public
static
boolean
getBoolean
(
byte
[]
buff
,
int
offset
)
{
return
buff
[
offset
]
>
0
;
}
/**
* 转换
*
* @param c
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:38:18
* @since 1.0.0
*/
public
static
byte
[]
putChar
(
char
c
)
{
byte
[]
buff
=
new
byte
[
1
];
ByteUtils
.
putChar
(
buff
,
0
,
c
);
return
buff
;
}
/**
* 转换
*
* @param buff
* @param offset
* @param c
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:38:35
* @since 1.0.0
*/
public
static
int
putChar
(
byte
[]
buff
,
int
offset
,
char
c
)
{
buff
[
offset
]
=
(
byte
)
c
;
return
1
;
}
/**
* 取位
*
* @param buff
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:38:43
* @since 1.0.0
*/
public
static
char
getChar
(
byte
[]
buff
)
{
return
ByteUtils
.
getChar
(
buff
,
0
);
}
/**
* 取位
*
* @param buff
* @param offset
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:38:51
* @since 1.0.0
*/
public
static
char
getChar
(
byte
[]
buff
,
int
offset
)
{
return
(
char
)
buff
[
offset
];
}
/**
* 转换
*
* @param s
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:38:59
* @since 1.0.0
*/
public
static
byte
[]
putShort
(
short
s
)
{
byte
[]
buff
=
new
byte
[
2
];
ByteUtils
.
putShort
(
buff
,
0
,
s
);
return
buff
;
}
/**
* 转换
*
* @param buff
* @param offset
* @param s
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:39:11
* @since 1.0.0
*/
public
static
int
putShort
(
byte
[]
buff
,
int
offset
,
short
s
)
{
final
int
len
=
2
;
for
(
int
i
=
0
;
i
<
len
;
i
++)
{
buff
[
offset
+
i
]
=
(
byte
)
(
s
>>
8
*
(
len
-
i
-
1
));
}
return
len
;
}
/**
* 转换
*
* @param s
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:39:24
* @since 1.0.0
*/
public
static
byte
[]
putShortReverse
(
short
s
)
{
byte
[]
buff
=
new
byte
[
2
];
ByteUtils
.
putShortReverse
(
buff
,
0
,
s
);
return
buff
;
}
/**
* 转换
*
* @param buff
* @param offset
* @param s
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:40:06
* @since 1.0.0
*/
public
static
int
putShortReverse
(
byte
[]
buff
,
int
offset
,
short
s
)
{
final
int
len
=
2
;
for
(
int
i
=
0
;
i
<
len
;
i
++)
{
buff
[
offset
+
i
]
=
(
byte
)
(
s
>>
8
*
i
);
}
return
len
;
}
/**
* 取值
*
* @param buff
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:40:25
* @since 1.0.0
*/
public
static
short
getShort
(
byte
[]
buff
)
{
return
ByteUtils
.
getShort
(
buff
,
0
);
}
/**
* 取值
*
* @param buff
* @param offset
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:40:34
* @since 1.0.0
*/
public
static
short
getShort
(
byte
[]
buff
,
int
offset
)
{
short
s
=
0
;
int
len
=
2
;
for
(
int
i
=
0
;
i
<
len
;
i
++)
{
s
|=
(
buff
[
offset
+
i
]
&
0xff
)
<<
8
*
(
len
-
i
-
1
);
}
return
s
;
}
/**
* 取值
*
* @param buff
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:40:40
* @since 1.0.0
*/
public
static
short
getShortReverse
(
byte
[]
buff
)
{
return
ByteUtils
.
getShortReverse
(
buff
,
0
);
}
/**
* 取值
*
* @param buff
* @param offset
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:40:47
* @since 1.0.0
*/
public
static
short
getShortReverse
(
byte
[]
buff
,
int
offset
)
{
short
s
=
0
;
int
len
=
2
;
for
(
int
i
=
0
;
i
<
len
;
i
++)
{
s
|=
(
buff
[
offset
+
i
]
&
0xff
)
<<
8
*
i
;
}
return
s
;
}
/**
* 转换
*
* @param s
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:41:34
* @since 1.0.0
*/
public
static
byte
[]
putInt
(
int
s
)
{
byte
[]
buff
=
new
byte
[
4
];
ByteUtils
.
putInt
(
buff
,
0
,
s
);
return
buff
;
}
/**
* 转换
*
* @param buff
* @param offset
* @param s
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:41:42
* @since 1.0.0
*/
public
static
int
putInt
(
byte
[]
buff
,
int
offset
,
int
s
)
{
final
int
len
=
4
;
for
(
int
i
=
0
;
i
<
len
;
i
++)
{
buff
[
offset
+
i
]
=
(
byte
)
(
s
>>
8
*
(
len
-
i
-
1
));
}
return
len
;
}
/**
* 转换
*
* @param s
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:41:47
* @since 1.0.0
*/
public
static
byte
[]
putIntReverse
(
int
s
)
{
byte
[]
buff
=
new
byte
[
4
];
ByteUtils
.
putIntReverse
(
buff
,
0
,
s
);
return
buff
;
}
/**
* 转换
*
* @param buff
* @param offset
* @param s
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:41:52
* @since 1.0.0
*/
public
static
int
putIntReverse
(
byte
[]
buff
,
int
offset
,
int
s
)
{
final
int
len
=
4
;
for
(
int
i
=
0
;
i
<
len
;
i
++)
{
buff
[
offset
+
i
]
=
(
byte
)
(
s
>>
8
*
i
);
}
return
len
;
}
/**
* 取值
*
* @param buff
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:42:08
* @since 1.0.0
*/
public
static
int
getInt
(
byte
[]
buff
)
{
return
ByteUtils
.
getInt
(
buff
,
0
);
}
/**
* 取值
*
* @param buff
* @param offset
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:42:25
* @since 1.0.0
*/
public
static
int
getInt
(
byte
[]
buff
,
int
offset
)
{
int
s
=
0
;
int
len
=
4
;
for
(
int
i
=
0
;
i
<
len
;
i
++)
{
s
|=
(
buff
[
offset
+
i
]
&
0xff
)
<<
8
*
(
len
-
i
-
1
);
}
return
s
;
}
/**
* 取值
*
* @param buff
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:42:31
* @since 1.0.0
*/
public
static
int
getIntReverse
(
byte
[]
buff
)
{
return
ByteUtils
.
getIntReverse
(
buff
,
0
);
}
/**
* 取值
*
* @param buff
* @param offset
* @return
* @author jiangmy
* @date 2018年1月17日 上午9:42:36
* @since 1.0.0
*/
public
static
int
getIntReverse
(
byte
[]
buff
,
int
offset
)
{
int
s
=
0
;
int
len
=
4
;
for
(
int
i
=
0
;
i
<
len
;
i
++)
{
s
|=
(
buff
[
offset
+
i
]
&
0xff
)
<<
8
*
i
;
}
return
s
;
}
public
static
byte
[]
defaultIfNull
(
byte
[]
value
,
byte
[]
bytes
)
{
if
(
value
!=
null
)
{
return
value
;
}
return
bytes
;
}
private
ByteUtils
()
{
}
/**
* Cp56Time2a转时间字符串
*
* @param bytes 字符数组
* @return 时间字符串
*/
public
static
String
parseCp56Time2aStr
(
byte
[]
bytes
)
{
int
milliseconds1
=
bytes
[
0
]
<
0
?
256
+
bytes
[
0
]
:
bytes
[
0
];
int
milliseconds2
=
bytes
[
1
]
<
0
?
256
+
bytes
[
1
]
:
bytes
[
1
];
int
milliseconds
=
milliseconds2
*
256
+
milliseconds1
;
// 位于 0011 1111
int
minutes
=
bytes
[
2
]
&
0x3F
;
// 位于 0001 1111
int
hours
=
bytes
[
3
]
&
0x1F
;
// 位于 0001 1111
int
days
=
bytes
[
4
]
&
0x1F
;
// 位于 0000 1111
int
months
=
bytes
[
5
]
&
0x0F
;
// 位于 0111 1111
int
years
=
bytes
[
6
]
&
0x7F
;
return
"20"
+
String
.
format
(
"%02d"
,
years
)
+
"-"
+
String
.
format
(
"%02d"
,
months
)
+
"-"
+
String
.
format
(
"%02d"
,
days
)
+
" "
+
String
.
format
(
"%02d"
,
hours
)
+
":"
+
String
.
format
(
"%02d"
,
minutes
)
+
":"
+
String
.
format
(
"%02d"
,
milliseconds
/
1000
);
}
/**
* 转为时间格式
*
* @param bytes 字符数组
* @return 时间
*/
public
static
Date
parseCp56Time2a
(
byte
[]
bytes
)
{
String
dateString
=
parseCp56Time2aStr
(
bytes
);
return
DateUtils
.
strToDate
(
dateString
,
"yyyy-MM-dd HH:mm:ss"
);
}
public
static
Date
parseCp56Time2a
(
String
s
)
{
byte
[]
b
=
HexUtil
.
decodeHex
(
s
);
return
parseCp56Time2a
(
b
);
}
/**
* 时间转16进制字符串
*
* @param date 时间
* @return 16进制字符串
*/
public
static
String
cp56Time2a
(
Date
date
)
{
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
setTime
(
date
);
StringBuilder
builder
=
new
StringBuilder
();
String
milliSecond
=
String
.
format
(
"%04X"
,
(
calendar
.
get
(
Calendar
.
SECOND
)
*
1000
)
+
calendar
.
get
(
Calendar
.
MILLISECOND
));
builder
.
append
(
milliSecond
.
substring
(
2
,
4
));
builder
.
append
(
milliSecond
.
substring
(
0
,
2
));
builder
.
append
(
String
.
format
(
"%02X"
,
calendar
.
get
(
Calendar
.
MINUTE
)
&
0x3F
));
builder
.
append
(
String
.
format
(
"%02X"
,
calendar
.
get
(
Calendar
.
HOUR_OF_DAY
)
&
0x1F
));
int
week
=
calendar
.
get
(
Calendar
.
DAY_OF_WEEK
);
if
(
week
==
Calendar
.
SUNDAY
)
{
week
=
7
;
}
else
{
week
--;
}
builder
.
append
(
String
.
format
(
"%02X"
,
(
week
<<
5
)
+
(
calendar
.
get
(
Calendar
.
DAY_OF_MONTH
)
&
0x1F
)));
builder
.
append
(
String
.
format
(
"%02X"
,
calendar
.
get
(
Calendar
.
MONTH
)
+
1
));
builder
.
append
(
String
.
format
(
"%02X"
,
calendar
.
get
(
Calendar
.
YEAR
)
-
2000
));
return
builder
.
toString
();
}
public
static
void
main
(
String
[]
args
)
{
String
decodeStr
=
"A7232E0FB80217"
;
String
originStr
=
"2023-02-24 15:46:09"
;
byte
[]
byteTimes
=
HexUtil
.
decodeHex
(
decodeStr
);
System
.
out
.
println
(
"Cp56Time2a原值: "
+
originStr
);
System
.
out
.
println
(
"解析 "
+
decodeStr
+
": "
+
parseCp56Time2aStr
(
byteTimes
));
Date
time
=
parseCp56Time2a
(
byteTimes
);
String
hexString
=
cp56Time2a
(
new
Date
());
System
.
out
.
println
(
"新Cp56Time2a: "
+
hexString
);
System
.
out
.
println
(
"新Cp56Time2a原值: "
+
parseCp56Time2aStr
(
HexUtil
.
decodeHex
(
hexString
)));
// System.out.println(ByteUtils.reverse(1));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/CallbackTask.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/ClassUtil.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.io.File
;
import
java.io.IOException
;
import
java.lang.annotation.Annotation
;
import
java.lang.reflect.Modifier
;
import
java.net.URL
;
import
java.util.ArrayList
;
import
java.util.Enumeration
;
import
java.util.HashSet
;
import
java.util.List
;
import
java.util.Set
;
import
java.util.function.Predicate
;
import
java.util.jar.JarEntry
;
import
java.util.jar.JarFile
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
org.springframework.core.io.Resource
;
import
org.springframework.core.io.support.PathMatchingResourcePatternResolver
;
import
org.springframework.core.io.support.ResourcePatternResolver
;
import
org.springframework.core.type.classreading.MetadataReader
;
import
org.springframework.core.type.classreading.MetadataReaderFactory
;
import
org.springframework.core.type.classreading.SimpleMetadataReaderFactory
;
import
org.springframework.util.ClassUtils
;
import
org.springframework.util.ResourceUtils
;
import
cn.hutool.core.util.StrUtil
;
/**
* @author jiangmy
* @version 1.0
* @created 2013-10-24 下午4:47:30
*/
@SuppressWarnings
({
"rawtypes"
,
"unchecked"
})
public
class
ClassUtil
{
private
static
final
Logger
logger
=
LoggerFactory
.
getLogger
(
ClassUtil
.
class
);
/**
* 获取某包下(包括该包的所有子包)所有类
*
* @param packageName 包名
* @return 类的完整名称
*/
public
static
List
<
Class
>
getClassName
(
String
packageName
)
{
return
getClassName
(
packageName
,
true
);
}
/**
* 获取某包下所有类
*
* @param packageName 包名
* @param childPackage 是否遍历子包
* @return 类的完整名称
*/
public
static
List
<
Class
>
getClassName
(
String
packageName
,
boolean
childPackage
)
{
if
(
packageName
==
null
)
{
return
null
;
}
List
<
Class
>
fileNames
=
new
ArrayList
<
Class
>();
ClassLoader
loader
=
Thread
.
currentThread
().
getContextClassLoader
();
String
packagePath
=
packageName
.
replace
(
"."
,
"/"
);
try
{
if
(
loader
==
null
)
{
return
null
;
}
Enumeration
<
URL
>
urls
=
loader
.
getResources
(
packagePath
);
while
(
urls
.
hasMoreElements
())
{
URL
url
=
urls
.
nextElement
();
String
type
=
url
.
getProtocol
();
if
(
type
.
equals
(
"file"
))
{
fileNames
.
addAll
(
getClassNameByFile
(
url
.
getPath
(),
childPackage
));
}
else
if
(
type
.
equals
(
"jar"
))
{
fileNames
.
addAll
(
getClassNameByJar
(
url
.
getPath
(),
childPackage
));
}
// fileNames.addAll(getClassNameByJars(((URLClassLoader) loader).getURLs(), packagePath, childPackage));
}
}
catch
(
Exception
e
)
{
logger
.
error
(
packageName
,
e
);
}
return
fileNames
;
}
/**
* 从项目文件获取某包下所有类
*
* @param filePath 文件路径
* @param className 类名集合
* @param childPackage 是否遍历子包
* @return 类的完整名称
* @throws ClassNotFoundException
*/
private
static
List
<
Class
>
getClassNameByFile
(
String
filePath
,
boolean
childPackage
)
{
List
<
Class
>
myClassName
=
new
ArrayList
<
Class
>();
File
file
=
new
File
(
filePath
);
File
[]
childFiles
=
file
.
listFiles
();
if
(
null
==
childFiles
)
{
return
myClassName
;
}
for
(
File
childFile
:
childFiles
)
{
if
(
childFile
.
isDirectory
())
{
if
(
childPackage
)
{
myClassName
.
addAll
(
getClassNameByFile
(
childFile
.
getPath
(),
childPackage
));
}
}
else
{
String
childFilePath
=
childFile
.
getPath
();
if
(
childFilePath
.
endsWith
(
".class"
))
{
childFilePath
=
childFilePath
.
substring
(
childFilePath
.
indexOf
(
"classes\\"
)
+
8
,
childFilePath
.
lastIndexOf
(
"."
));
childFilePath
=
childFilePath
.
replace
(
"\\"
,
"."
);
try
{
logger
.
debug
(
"getClassNameByFile: {} {}"
,
childFilePath
,
filePath
);
myClassName
.
add
(
Class
.
forName
(
childFilePath
,
false
,
Thread
.
currentThread
().
getContextClassLoader
()));
}
catch
(
Exception
e
)
{
logger
.
warn
(
"Not Found:"
+
filePath
);
}
}
}
}
return
myClassName
;
}
/**
* 从jar获取某包下所有类
*
* @param jarPath jar文件路径
* @param childPackage 是否遍历子包
* @return 类的完整名称
*/
private
static
List
<
Class
>
getClassNameByJar
(
String
jarPath
,
boolean
childPackage
)
{
List
<
Class
>
myClassName
=
new
ArrayList
<
Class
>();
String
[]
jarInfo
=
jarPath
.
split
(
"!"
);
String
jarFilePath
=
jarInfo
[
0
].
substring
(
jarInfo
[
0
].
indexOf
(
"/"
));
String
packagePath
=
jarInfo
[
1
].
substring
(
1
);
logger
.
info
(
"jar:"
+
jarFilePath
+
" package:"
+
packagePath
);
try
{
@SuppressWarnings
(
"resource"
)
JarFile
jarFile
=
new
JarFile
(
jarFilePath
);
// e:/maven_repo/org/springframework/web/spring-web-4.0.5-RELEASE.jar
Enumeration
<
JarEntry
>
entrys
=
jarFile
.
entries
();
// org/springframework/http/client
Class
c
;
while
(
entrys
.
hasMoreElements
())
{
JarEntry
jarEntry
=
entrys
.
nextElement
();
String
entryName
=
jarEntry
.
getName
();
if
(!
entryName
.
startsWith
(
packagePath
)
||
entryName
.
equals
(
packagePath
+
"/"
))
{
continue
;
}
if
(
entryName
.
endsWith
(
".class"
))
{
entryName
=
StrUtil
.
contains
(
entryName
,
"classes/"
)
?
StrUtil
.
subAfter
(
entryName
,
"classes/"
,
true
)
:
entryName
;
entryName
=
entryName
.
replace
(
"/"
,
"."
).
substring
(
0
,
entryName
.
lastIndexOf
(
"."
));
// logger.info(" entryName:" + entryName);
try
{
c
=
Class
.
forName
(
entryName
,
false
,
Thread
.
currentThread
().
getContextClassLoader
());
myClassName
.
add
(
c
);
// logger.info(entryName);
}
catch
(
Exception
e
)
{
logger
.
warn
(
"Not Found:"
+
entryName
);
}
}
else
if
(
childPackage
&&
entryName
.
endsWith
(
"/"
))
{
// 子目录
logger
.
info
(
"childPackage:"
+
entryName
.
replace
(
"/"
,
"."
));
myClassName
.
addAll
(
getClassName
(
jarFilePath
+
"!"
+
entryName
,
childPackage
));
}
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
myClassName
;
}
public
static
<
T
>
List
<
Class
<?
extends
T
>>
getAllAssignedClass
(
Class
<
T
>
c
)
{
return
getAllAssignedClass
(
c
,
(
String
)
null
);
}
/**
* @param c
* @param path
* @return 获取path下的c的子类或者接口实现类
*/
public
static
<
T
>
List
<
Class
<?
extends
T
>>
getAllAssignedClass
(
Class
<
T
>
c
,
String
...
paths
)
{
Set
<
Class
>
set
=
new
HashSet
<
Class
>();
try
{
for
(
String
path
:
paths
)
{
if
(
path
!=
null
&&
path
.
trim
().
length
()
>
0
)
{
List
<
Class
>
ls1
=
getClassName
(
path
);
if
(
ls1
!=
null
)
{
// System.out.println(JsonUtil.toJson(ls1));
set
.
addAll
(
ls1
);
}
}
if
(!
Modifier
.
isFinal
(
c
.
getModifiers
()))
{
List
<
Class
>
ls2
=
getClassName
(
c
.
getPackage
().
getName
());
if
(
ls2
!=
null
)
{
// System.out.println(JsonUtil.toJson(ls2));
set
.
addAll
(
ls2
);
}
}
Set
<
Class
<?>>
set2
=
ClassScanner
.
listAllSubclasses
(
path
,
c
);
// System.out.println(JsonUtil.toJson(set2));
set
.
addAll
(
set2
);
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
set
.
remove
(
c
);
List
<
Class
<?
extends
T
>>
ls
=
new
ArrayList
<
Class
<?
extends
T
>>();
for
(
Class
cl
:
set
)
{
// System.out.println(cl + " " + !cl.isInterface() + " " + !Modifier.isAbstract(cl.getModifiers()) + " " + (c.isAssignableFrom(cl) ));
if
(!
cl
.
isInterface
()
&&
!
Modifier
.
isAbstract
(
cl
.
getModifiers
())
&&
c
.
isAssignableFrom
(
cl
)
&&
c
!=
cl
)
{
ls
.
add
(
cl
);
}
}
return
ls
;
}
public
static
List
<
Class
>
getAllClassByInterface
(
Class
c
)
{
// 返回结果
List
<
Class
>
returnClassList
=
new
ArrayList
<
Class
>();
// 如果不是一个接口,则不做处理
// 获得当前的包名
String
packageName
=
c
.
getPackage
().
getName
();
try
{
// 获得当前包下以及子包下的所有类
List
<
Class
>
allClass
=
ClassUtil
.
getClasses
(
packageName
);
// 判断是否是同一个接口
for
(
int
i
=
0
;
i
<
allClass
.
size
();
i
++)
{
// 判断是不是一个接口
if
(
c
.
isAssignableFrom
(
allClass
.
get
(
i
)))
{
// 本身不加进去
if
(!
c
.
equals
(
allClass
.
get
(
i
)))
{
returnClassList
.
add
(
allClass
.
get
(
i
));
}
}
}
}
catch
(
ClassNotFoundException
e
)
{
e
.
printStackTrace
();
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
return
returnClassList
;
}
// 从一个包中查找出所有的类,在jar包中不能查找
private
static
List
<
Class
>
getClasses
(
String
packageName
)
throws
ClassNotFoundException
,
IOException
{
ClassLoader
classLoader
=
Thread
.
currentThread
().
getContextClassLoader
();
// 用'/'代替'.'路径
String
path
=
packageName
.
replace
(
'.'
,
'/'
);
Enumeration
<
URL
>
resources
=
classLoader
.
getResources
(
path
);
List
<
File
>
dirs
=
new
ArrayList
<
File
>();
while
(
resources
.
hasMoreElements
())
{
URL
resource
=
resources
.
nextElement
();
dirs
.
add
(
new
File
(
resource
.
getFile
()));
}
ArrayList
<
Class
>
classes
=
new
ArrayList
<
Class
>();
for
(
File
directory
:
dirs
)
{
classes
.
addAll
(
ClassUtil
.
findClasses
(
directory
,
packageName
));
}
return
classes
;
}
private
static
List
<
Class
>
findClasses
(
File
directory
,
String
packageName
)
throws
ClassNotFoundException
{
List
<
Class
>
classes
=
new
ArrayList
<
Class
>();
if
(!
directory
.
exists
())
{
return
classes
;
}
File
[]
files
=
directory
.
listFiles
();
for
(
File
file
:
files
)
{
if
(
file
.
isDirectory
())
{
assert
!
file
.
getName
().
contains
(
"."
);
classes
.
addAll
(
ClassUtil
.
findClasses
(
file
,
packageName
+
"."
+
file
.
getName
()));
}
else
if
(
file
.
getName
().
endsWith
(
".class"
))
{
// 去掉'.class'
classes
.
add
(
Class
.
forName
(
packageName
+
'.'
+
file
.
getName
().
substring
(
0
,
file
.
getName
().
length
()
-
6
)));
}
}
return
classes
;
}
/**
* @param clz
* @return 区分Integer.class和int.class
*/
public
static
boolean
isWrapClass
(
Class
clz
)
{
try
{
return
((
Class
)
clz
.
getField
(
"TYPE"
).
get
(
null
)).
isPrimitive
();
}
catch
(
Exception
e
)
{
return
false
;
}
}
public
static
void
testGetClassName
()
{
// 方法1:通过SecurityManager的保护方法getClassContext()
String
clazzName
=
new
SecurityManager
()
{
public
String
getClassName
()
{
return
getClassContext
()[
1
].
getName
();
}
}.
getClassName
();
System
.
out
.
println
(
clazzName
);
// 方法2:通过Throwable的方法getStackTrace()
String
clazzName2
=
new
Throwable
().
getStackTrace
()[
1
].
getClassName
();
System
.
out
.
println
(
clazzName2
);
// 方法3:通过分析匿名类名称(性能最好)
String
clazzName3
=
new
Object
()
{
public
String
getClassName
()
{
String
clazzName
=
this
.
getClass
().
getName
();
return
clazzName
.
substring
(
0
,
clazzName
.
lastIndexOf
(
'$'
));
}
}.
getClassName
();
System
.
out
.
println
(
clazzName3
);
// 方法4:通过Thread的方法getStackTrace()
String
clazzName4
=
Thread
.
currentThread
().
getStackTrace
()[
2
].
getClassName
();
System
.
out
.
println
(
clazzName4
);
}
public
static
void
testGetFunctionName
()
{
// 方法1:通过Throwable的方法getStackTrace()
String
funcName2
=
new
Throwable
().
getStackTrace
()[
1
].
getMethodName
();
System
.
out
.
println
(
funcName2
);
// 方法2:通过Thread的方法getStackTrace()
String
clazzName4
=
Thread
.
currentThread
().
getStackTrace
()[
2
].
getMethodName
();
System
.
out
.
println
(
clazzName4
);
}
public
static
class
ClassScanner
{
private
static
Logger
logger
=
LoggerFactory
.
getLogger
(
ClassScanner
.
class
);
/**
* 默认过滤器(无实现)
*/
private
final
static
Predicate
<
Class
<?>>
EMPTY_FILTER
=
clazz
->
true
;
/**
* 扫描目录下的所有class文件
*
* @param scanPackage 搜索的包根路径
* @return
*/
public
static
Set
<
Class
<?>>
getClasses
(
String
scanPackage
)
{
return
getClasses
(
scanPackage
,
EMPTY_FILTER
);
}
/**
* 返回所有的子类(不包括抽象类)
*
* @param scanPackage 搜索的包根路径
* @param parent
* @return
*/
public
static
Set
<
Class
<?>>
listAllSubclasses
(
String
scanPackage
,
Class
<?>
parent
)
{
return
getClasses
(
scanPackage
,
(
clazz
)
->
{
return
parent
.
isAssignableFrom
(
clazz
)
&&
!
Modifier
.
isAbstract
(
clazz
.
getModifiers
());
});
}
/**
* 返回所有带制定注解的class列表
*
* @param scanPackage 搜索的包根路径
* @param annotation
* @return
*/
public
static
<
A
extends
Annotation
>
Set
<
Class
<?>>
listClassesWithAnnotation
(
String
scanPackage
,
Class
<
A
>
annotation
)
{
return
getClasses
(
scanPackage
,
(
clazz
)
->
{
return
clazz
.
getAnnotation
(
annotation
)
!=
null
;
});
}
/**
* 扫描目录下的所有class文件
*
* @param pack 包路径
* @param filter 自定义类过滤器
* @return
*/
public
static
Set
<
Class
<?>>
getClasses
(
String
pack
,
Predicate
<
Class
<?>>
filter
)
{
ResourcePatternResolver
patternResolver
=
new
PathMatchingResourcePatternResolver
();
MetadataReaderFactory
metaFactory
=
new
SimpleMetadataReaderFactory
(
patternResolver
);
String
path
=
ClassUtils
.
convertClassNameToResourcePath
(
pack
);
String
location
=
ResourceUtils
.
CLASSPATH_URL_PREFIX
+
path
+
"/**/*.class"
;
Resource
[]
resources
;
Set
<
Class
<?>>
result
=
new
HashSet
<>();
try
{
resources
=
patternResolver
.
getResources
(
location
);
for
(
Resource
resource
:
resources
)
{
MetadataReader
metaReader
=
metaFactory
.
getMetadataReader
(
resource
);
if
(
resource
.
isReadable
())
{
String
clazzName
=
metaReader
.
getClassMetadata
().
getClassName
();
if
(
clazzName
.
contains
(
"$"
))
{
// 忽略内部类
continue
;
}
// Class<?> clazz = Class.forName(clazzName);
Class
<?>
clazz
=
Thread
.
currentThread
().
getContextClassLoader
().
loadClass
(
clazzName
);
if
(
filter
.
test
(
clazz
))
{
result
.
add
(
clazz
);
}
}
}
}
catch
(
Exception
e
)
{
logger
.
warn
(
"path:{} {}"
,
location
,
e
.
getMessage
());
}
return
result
;
}
}
public
static
void
main
(
String
[]
args
)
{
Set
<
Class
<?>>
clazzs
=
ClassScanner
.
getClasses
(
"cn.com.glsx.charging.im.web.vo"
);
for
(
Class
<?>
c
:
clazzs
)
{
System
.
err
.
println
(
c
);
}
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/ClassUtils.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/CloseableUtils.java
0 → 100644
View file @
81f2091
/*
* @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
(
""
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/CrcUtils.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/DateUtil.java
0 → 100644
View file @
81f2091
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
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/DateUtils.java
0 → 100644
View file @
81f2091
/*
* @Copyright: 2014~2018 www.yyfax.com Inc. All rights reserved.
*/
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.sql.Timestamp
;
import
java.text.DateFormat
;
import
java.text.ParseException
;
import
java.text.SimpleDateFormat
;
import
java.time.Duration
;
import
java.time.LocalDate
;
import
java.time.LocalDateTime
;
import
java.time.LocalTime
;
import
java.time.ZoneId
;
import
java.time.format.DateTimeFormatterBuilder
;
import
java.util.ArrayList
;
import
java.util.Calendar
;
import
java.util.Date
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Map
;
import
java.util.concurrent.TimeUnit
;
import
org.apache.commons.lang3.StringUtils
;
import
lombok.extern.slf4j.Slf4j
;
/**
* 日期操作
* <p>
* 5. 【强制】SimpleDateFormat是线程不安全的类,一般不要定义为static变量,如果定义为
* static,必须加锁,或者使用DateUtils工具类。 正例:注意线程安全,使用DateUtils。亦推荐如下处理:
*
* <pre>
* private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>() {
* @Override
* protected DateFormat initialValue() {
* return new SimpleDateFormat("yyyy-MM-dd");
* }
* };
* </pre>
* <p>
* 说明:如果是JDK8的应用,可以使用Instant代替Date,LocalDateTime代替Calendar,
* DateTimeFormatter代替SimpleDateFormat,官方给出的解释:simple beautiful strong immutable
* thread-safe。
* </p>
*
* @author jiangmy
* @date 2018年1月15日 下午3:43:28
* @since 1.0.0
*/
@Slf4j
public
class
DateUtils
{
/**
* 存放不同的日期模板格式的sdf的Map
*/
private
static
ThreadLocal
<
Map
<
String
,
SimpleDateFormat
>>
sdfMap
=
new
ThreadLocal
<
Map
<
String
,
SimpleDateFormat
>>()
{
@Override
protected
Map
<
String
,
SimpleDateFormat
>
initialValue
()
{
return
new
HashMap
<>();
}
};
public
static
final
Timestamp
ZERO_TIMESTAMP
=
new
Timestamp
(
0
);
public
static
final
String
FORMAT_DATE
=
"yyyy-MM-dd"
;
public
static
final
String
FORMAT_DATETIME
=
"yyyy-MM-dd HH:mm:ss"
;
public
static
final
String
FORMAT_YYYYMMDD
=
"yyyyMMdd"
;
public
static
final
String
FORMAT_YYYYMMDDHHMMSS
=
"yyyyMMddHHmmss"
;
public
static
final
String
FORMAT_YYYY
年
MM
月
DD
日
HHMM
=
"yyyy年MM月dd日 HH:mm"
;
private
DateUtils
()
{
}
/**
* 日期字符串转日期格式
*
* @param str
* @return *
* @author jiangmy
* @date 2018年2月28日 下午4:47:38
* @since 1.0.0
*/
public
static
Date
strToDate
(
String
str
)
{
return
strToDate
(
str
,
FORMAT_DATE
);
}
public
static
Date
strToDateTime
(
String
str
)
{
return
strToDate
(
str
,
FORMAT_DATETIME
);
}
/**
* 日期字符串转日期格式
*
* @param str 日期字符串
* @param pattern 日期字符串格式
* @return java.util.Date格式
* @author jiangmy
* @date 2016-08-04 14:31:05
* @since 1.0.0
*/
public
static
Date
strToDate
(
String
str
,
String
pattern
)
{
if
(
StringUtils
.
isBlank
(
str
))
{
return
null
;
}
Date
date
=
null
;
DateFormat
format
;
try
{
if
(
str
.
length
()
<
pattern
.
length
())
{
pattern
=
pattern
.
substring
(
0
,
str
.
length
());
}
else
if
(
str
.
length
()
>
pattern
.
length
())
{
str
=
str
.
substring
(
0
,
pattern
.
length
());
}
format
=
getSdf
(
pattern
);
date
=
format
.
parse
(
str
);
}
catch
(
Exception
e
)
{
try
{
format
=
getSdf
(
pattern
,
Locale
.
ENGLISH
);
date
=
format
.
parse
(
str
);
}
catch
(
Exception
e2
)
{
}
}
return
date
;
}
/**
* jdk8日期类
*
* @param str
* @return *
* @author jiangmy
* @date 2018年2月28日 下午4:36:07
* @since 1.0.0
*/
public
static
LocalDate
strToLocalDate
(
String
str
)
{
return
strToLocalDate
(
str
,
FORMAT_DATE
);
}
/**
* jdk8日期类
*
* @param str
* @param pattern
* @return *
* @author jiangmy
* @date 2018年2月28日 下午4:36:30
* @since 1.0.0
*/
public
static
LocalDate
strToLocalDate
(
String
str
,
String
pattern
)
{
return
LocalDate
.
parse
(
str
,
new
DateTimeFormatterBuilder
().
appendPattern
(
pattern
).
toFormatter
());
}
/**
* jdk8日期时间类
*
* @param str
* @return *
* @author jiangmy
* @date 2018年2月28日 下午4:40:18
* @since 1.0.0
*/
public
static
LocalDateTime
strToLocalDateTime
(
String
str
)
{
return
strToLocalDateTime
(
str
,
FORMAT_DATETIME
);
}
/**
* jdk8日期时间类
*
* @param str
* @param pattern
* @return *
* @author jiangmy
* @date 2018年2月28日 下午4:36:41
* @since 1.0.0
*/
public
static
LocalDateTime
strToLocalDateTime
(
String
str
,
String
pattern
)
{
return
LocalDateTime
.
parse
(
str
,
new
DateTimeFormatterBuilder
().
appendPattern
(
pattern
).
toFormatter
());
}
/**
* jdk8日期时间类 Date转jdk8 LocalDateTime
*
* @param date
* @return *
* @author zhangxy
* @date 2019年3月18日 下午4:10:00
* @since 1.0.0
*/
public
static
LocalDateTime
dateToLocalDateTime
(
Date
date
)
{
if
(
date
==
null
)
{
return
null
;
}
return
LocalDateTime
.
ofInstant
(
date
.
toInstant
(),
ZoneId
.
systemDefault
());
}
/**
* jdk8日期时间类 Date转jdk8 LocalDate
*
* @param date
* @return *
* @author zhangxy
* @date 2019年3月18日 下午4:10:00
* @since 1.0.0
*/
public
static
LocalDate
dateToLocalDate
(
Date
date
)
{
if
(
date
==
null
)
{
return
null
;
}
return
LocalDateTime
.
ofInstant
(
date
.
toInstant
(),
ZoneId
.
systemDefault
()).
toLocalDate
();
}
/**
* jdk8日期时间类 Date转jdk8 LocalTime
*
* @param date
* @return *
* @author zhangxy
* @date 2019年3月18日 下午4:10:00
* @since 1.0.0
*/
public
static
LocalTime
dateToLocalTime
(
Date
date
)
{
if
(
date
==
null
)
{
return
null
;
}
return
LocalDateTime
.
ofInstant
(
date
.
toInstant
(),
ZoneId
.
systemDefault
()).
toLocalTime
();
}
/**
* 是否是今年第一天
*
* @param date
* @return *
* @author zhengxt
* @date 2020年9月07日 下午4:10:00
* @since 1.0.0
*/
public
static
boolean
isFirstDayOfYear
(
Date
date
)
{
if
(
date
==
null
)
{
return
false
;
}
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
setTime
(
date
);
return
calendar
.
get
(
Calendar
.
DAY_OF_YEAR
)
==
1
;
}
/**
* 校验日期字符串是否是所需格式
*
* @param str
* @param pattern
* @return
* @author jiangmy
* @date 2017年6月12日 下午2:59:56
* @since 1.0.0
*/
public
static
boolean
isFormat
(
String
str
,
String
pattern
)
{
DateFormat
format
;
try
{
if
(
str
.
length
()
!=
pattern
.
length
())
{
return
false
;
}
format
=
getSdf
(
pattern
,
Locale
.
CHINESE
);
// 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期
format
.
setLenient
(
false
);
format
.
parse
(
str
);
}
catch
(
Exception
e
)
{
log
.
debug
(
"字符:{}转换成时间格式:{},失败"
,
str
,
pattern
);
return
false
;
}
return
true
;
}
/**
* 判断日期格式
*
* @param str
* @param pattern
* @return *
* @author jiangmy
* @date 2018年2月28日 下午5:05:45
* @since 1.0.0
*/
public
static
boolean
isLocalDateFormat
(
String
str
,
String
pattern
)
{
try
{
LocalDate
.
parse
(
str
,
new
DateTimeFormatterBuilder
().
appendPattern
(
pattern
).
toFormatter
());
return
true
;
}
catch
(
Exception
e
)
{
log
.
debug
(
"字符:{}转换成日期格式:{},失败"
,
str
,
pattern
);
return
false
;
}
}
/**
* 默认yyyy-MM-dd HH:mm:ss格式字符串转时间戳
*
* @param str 字符串(格式yyyy-MM-dd HH:mm:ss)
* @return java.sql.Timestamp格式
* @author jiangmy
* @date 2016-08-04 14:36:42
* @since 1.0.0
*/
public
static
Timestamp
str2Timestamp
(
String
str
)
{
Timestamp
rs
=
null
;
try
{
rs
=
Timestamp
.
valueOf
(
str
);
}
catch
(
Exception
e
)
{
Date
date
=
strToDate
(
str
);
if
(
date
!=
null
)
{
rs
=
new
Timestamp
(
date
.
getTime
());
}
}
return
rs
;
}
/**
* java.util.Date格式 转 java.sql.Timestamp格式
*
* @param date
* @return java.sql.Timestamp格式
* @author jiangmy
* @date 2016-08-04 14:37:18
* @since 1.0.0
*/
public
static
Timestamp
toTimestamp
(
Date
date
)
{
return
new
Timestamp
(
date
.
getTime
());
}
/**
* 日期转字符串
*
* @param date java.util.Date格式
* @param pattern 目标字符串格式
* @return String
* @author jiangmy
* @date 2016-08-04 14:38:06
* @since 1.0.0
*/
public
static
String
dateToStr
(
Date
date
,
String
pattern
)
{
if
(
date
==
null
)
{
return
null
;
}
String
str
=
null
;
try
{
SimpleDateFormat
format
=
getSdf
(
pattern
);
str
=
format
.
format
(
date
);
format
=
null
;
}
catch
(
Exception
e
)
{
}
return
str
;
}
/**
* 日期时间转字符串
*
* @param dt java.util.Date格式
* @return String(yyyy - MM - dd HH : mm : ss)
* @author jiangmy
* @date 2016-08-04 14:43:57
* @since 1.0.0
*/
public
static
String
datetimeToStr2
(
Date
dt
)
{
String
tmstr
=
String
.
format
(
"%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS"
,
dt
);
return
tmstr
;
}
/**
* 日期转字符串
*
* @param date java.util.Date格式
* @return String(yyyy - MM - dd)
* @author jiangmy
* @date 2016-08-04 14:44:41
* @since 1.0.0
*/
public
static
String
dateToStr
(
Date
date
)
{
return
dateToStr
(
date
,
FORMAT_DATE
);
}
public
static
String
dateToStr
()
{
return
dateToStr
(
new
Date
());
}
public
static
String
dateStrFormat
(
String
dateStr
,
String
form
,
String
format
)
{
SimpleDateFormat
sdfIn
=
new
SimpleDateFormat
(
form
);
Date
date
=
null
;
try
{
date
=
sdfIn
.
parse
(
dateStr
);
}
catch
(
ParseException
e
)
{
log
.
error
(
"数据格式化异常,dateStr:{},form:{},format:{}"
,
dateStr
,
form
,
format
);
}
SimpleDateFormat
sdfOut
=
new
SimpleDateFormat
(
format
);
return
sdfOut
.
format
(
date
);
}
/**
* 日期时间转字符串
*
* @param date java.util.Date格式
* @return String(yyyy - MM - dd HH : mm : ss)
* @author jiangmy
* @date 2016-08-04 14:45:08
* @since 1.0.0
*/
public
static
String
datetimeToStr
(
Date
date
)
{
return
dateToStr
(
date
,
FORMAT_DATETIME
);
}
/**
* 获取服务器当前系统时间
*
* @return String(yyyy - MM - dd HH : mm : ss)
* @author jiangmy
* @date 2016-08-04 14:45:08
* @since 1.0.0
*/
public
static
String
getCurrentDateTime
()
{
return
dateToStr
(
new
Date
(),
FORMAT_DATETIME
);
}
/**
* 获取服务器当前系统时间(格式FORMAT_YYYYMMDDHHMMSS)
*
* @return String(yyyy - MM - dd HH : mm : ss)
* @author xiemh
* @date 2016-08-04 14:45:08
* @since 1.0.0
*/
public
static
String
getCurrentDateTimeNum
()
{
return
dateToStr
(
new
Date
(),
FORMAT_YYYYMMDDHHMMSS
);
}
public
static
String
getCurrentDate
()
{
return
dateToStr
(
new
Date
(),
FORMAT_DATE
);
}
/**
* 获取当前年份
*
* @return int(yyyy)
* @author buyi
* @date 2016-12-28 16:28:26
* @since 1.0.0
*/
public
static
int
getCurrentYear
()
{
return
Calendar
.
getInstance
().
get
(
Calendar
.
YEAR
);
}
/**
* 获取当前年月的上一个月 格式 yyyy-MM
*
* @return String(yyyy - MM)
* @author buyi
* @date 2016-12-28 16:28:26
* @since 1.0.0
*/
public
static
String
getCurrentYearMonth
()
{
int
month
=
Calendar
.
getInstance
().
get
(
Calendar
.
MONTH
);
if
(
month
>=
10
)
{
return
getCurrentYear
()
+
"-"
+
month
;
}
return
getCurrentYear
()
+
"-0"
+
month
;
}
/**
* 获取传入时间的年份 格式 yyyy
*
* @return int(yyyy)
* @author buyi
* @date 2016-12-28 16:28:26
* @since 1.0.0
*/
public
static
int
getCurrentYear
(
Date
date
)
{
Calendar
cal
=
Calendar
.
getInstance
();
cal
.
setTime
(
date
);
return
cal
.
get
(
Calendar
.
YEAR
);
}
/**
* 获取传入时间的月份 格式 M
*
* @return String(M)
* @author buyi
* @date 2016-12-28 16:28:26
* @since 1.0.0
*/
public
static
String
getCurrentMonth
(
Date
date
)
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
"M"
);
return
sdf
.
format
(
date
);
}
/**
* 获取传入时间的天 几号 格式 M
*
* @return String(M)
* @author buyi
* @date 2016-12-28 16:28:26
* @since 1.0.0
*/
public
static
String
getCurrentDay
(
Date
date
)
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
"dd"
);
return
sdf
.
format
(
date
);
}
/**
* 获取当前年月 格式 yyyy-MM
*
* @return String(yyyy - MM)
* @author buyi
* @date 2016-12-28 16:28:26
* @since 1.0.0
*/
public
static
String
getCurrentYearMonth1
()
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
"yyyy-MM"
);
String
yearMonth
=
sdf
.
format
(
new
Date
());
return
yearMonth
;
}
/**
* 获取当前年月的上一个月 格式 yyyy-MM
*
* @return String(yyyy - MM)
* @author buyi
* @date 2016-12-28 16:28:26
* @since 1.0.0
*/
public
static
String
getBeforeMonth
(
String
yearMonth
)
{
SimpleDateFormat
sd
=
new
SimpleDateFormat
(
"yyyy-MM"
);
Date
currdate
=
null
;
try
{
currdate
=
sd
.
parse
(
yearMonth
);
}
catch
(
ParseException
e
)
{
e
.
printStackTrace
();
}
Calendar
calendar
=
Calendar
.
getInstance
();
assert
currdate
!=
null
;
calendar
.
setTime
(
currdate
);
calendar
.
set
(
Calendar
.
MONTH
,
calendar
.
get
(
Calendar
.
MONTH
)
-
1
);
return
sd
.
format
(
calendar
.
getTime
());
}
/**
* 获取当年第一天
*
* @return String(yyyy - MM - dd)
* @author zhengxt
* @date 2020-09-07 16:28:26
* @since 1.0.0
*/
public
static
String
getFirstDayOfYear
()
{
Calendar
currCal
=
Calendar
.
getInstance
();
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
clear
();
calendar
.
set
(
Calendar
.
YEAR
,
currCal
.
get
(
Calendar
.
YEAR
));
Date
time
=
calendar
.
getTime
();
return
dateToStr
(
time
);
}
/**
* 获取该日期的周日
*
* @return String(yyyy - MM - dd)
* @author zhengxt
* @date 2020-09-07 16:28:26
* @since 1.0.0
*/
public
static
String
getLastDayOfWeek
(
String
dateStr
,
String
format
)
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
format
);
// 设置时间格式
Calendar
cal
=
null
;
try
{
cal
=
Calendar
.
getInstance
();
Date
time
=
sdf
.
parse
(
dateStr
);
assert
time
!=
null
;
cal
.
setTime
(
time
);
// 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
int
dayWeek
=
cal
.
get
(
Calendar
.
DAY_OF_WEEK
);
// 获得当前日期是一个星期的第几天
if
(
1
==
dayWeek
)
{
cal
.
add
(
Calendar
.
DAY_OF_MONTH
,
-
1
);
}
cal
.
setFirstDayOfWeek
(
Calendar
.
MONDAY
);
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
int
day
=
cal
.
get
(
Calendar
.
DAY_OF_WEEK
);
// 获得当前日期是一个星期的第几天
cal
.
add
(
Calendar
.
DATE
,
cal
.
getFirstDayOfWeek
()
-
day
);
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
cal
.
add
(
Calendar
.
DATE
,
6
);
}
catch
(
ParseException
e
)
{
e
.
printStackTrace
();
}
return
sdf
.
format
(
cal
.
getTime
());
}
/**
* 获取当年第一天
*
* @return Date
* @author zhengxt
* @date 2020-09-07 16:28:26
* @since 1.0.0
*/
public
static
Date
getFirstDateOfYear
()
{
Calendar
currCal
=
Calendar
.
getInstance
();
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
clear
();
calendar
.
set
(
Calendar
.
YEAR
,
currCal
.
get
(
Calendar
.
YEAR
));
Date
time
=
calendar
.
getTime
();
return
time
;
}
/**
* 获取当年第一天
*
* @return String(yyyy - MM - dd)
* @author zhengxt
* @date 2020-09-07 16:28:26
* @since 1.0.0
*/
public
static
String
getFirstDayOfYear
(
Date
date
)
{
SimpleDateFormat
format
=
new
SimpleDateFormat
(
"yyyy"
);
String
year
=
format
.
format
(
date
);
return
year
+
"-01-01"
;
}
/**
* 获取上周一时间
*
* @return
*/
public
static
String
getLastWeekMonday
()
{
Date
date
=
new
Date
();
Calendar
cal
=
Calendar
.
getInstance
();
cal
.
setTime
(
date
);
// 判断当前日期是否为周末,因为周末是本周第一天,如果不向后推迟一天的到的将是下周一的零点,而不是本周周一零点
if
(
1
==
cal
.
get
(
Calendar
.
DAY_OF_WEEK
))
{
cal
.
add
(
Calendar
.
DATE
,
-
1
);
}
// 时间减去7天
cal
.
add
(
Calendar
.
DAY_OF_MONTH
,
-
7
);
// Calendar.MONDAY 想获取周几就更换这个
cal
.
set
(
Calendar
.
DAY_OF_WEEK
,
Calendar
.
MONDAY
);
return
dateToStr
(
cal
.
getTime
());
}
/**
* 获取上周周天时间
*
* @return
*/
public
static
String
getLastWeekSunday
()
{
Date
date
=
new
Date
();
Calendar
cal
=
Calendar
.
getInstance
();
cal
.
setTime
(
date
);
if
(
1
==
cal
.
get
(
Calendar
.
DAY_OF_WEEK
))
{
cal
.
add
(
Calendar
.
DATE
,
-
1
);
}
cal
.
set
(
Calendar
.
DAY_OF_WEEK
,
Calendar
.
SUNDAY
);
return
dateToStr
(
cal
.
getTime
());
}
/**
* 当前时间戳
*
* @return java.sql.Timestamp (yyyy-MM-dd HH:mm:ss)
* @author jiangmy
* @date 2016-08-04 14:48:04
* @since 1.0.0
*/
public
static
Timestamp
now
()
{
return
new
Timestamp
(
System
.
currentTimeMillis
());
}
/**
* 当前日期0点的时间戳
*
* @return java.sql.Timestamp (yyyy-MM-dd 00:00:00)
* @author jiangmy
* @date 2016-08-04 14:50:06
* @since 1.0.0
*/
public
static
Timestamp
nowDay
()
{
return
toTimestamp
(
today
());
}
/**
* 当前日期0点的Date
*
* @return java.util.Date (yyyy-MM-dd 00:00:00)
* @author jiangmy
* @date 2016-08-04 14:50:48
* @since 1.0.0
*/
public
static
Date
today
()
{
return
formatDate
(
new
Date
(),
FORMAT_DATE
);
}
public
static
Date
yesterday
()
{
return
addDay
(
today
(),
-
1
);
}
public
static
Date
lastWeekEnd
()
{
return
lastWeekEnd
(
null
);
}
public
static
Date
lastWeekEnd
(
Date
date
)
{
if
(
date
==
null
)
{
date
=
today
();
}
return
lastWeekEnd
(
date
,
true
);
}
public
static
Date
lastWeekSunday
(
Date
date
)
{
return
lastWeekEnd
(
date
,
true
);
}
public
static
Date
lastWeekMonday
(
Date
date
)
{
return
addDay
(
lastWeekSunday
(
date
),
-
6
);
}
public
static
Date
lastWeekEnd
(
Date
date
,
boolean
isSundayAsWeekEnd
)
{
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
c
.
set
(
Calendar
.
DAY_OF_WEEK
,
Calendar
.
SUNDAY
);
if
(!
c
.
getTime
().
before
(
date
))
{
c
.
add
(
Calendar
.
WEEK_OF_YEAR
,
-
1
);
}
return
c
.
getTime
();
}
public
static
Date
lastMonthEnd
()
{
return
lastWeekEnd
(
null
);
}
public
static
Date
lastMonthEnd
(
Date
date
)
{
if
(
date
==
null
)
{
date
=
today
();
}
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
c
.
set
(
Calendar
.
DAY_OF_MONTH
,
1
);
c
.
add
(
Calendar
.
DAY_OF_YEAR
,
-
1
);
return
c
.
getTime
();
}
public
static
boolean
isSunday
(
Date
date
)
{
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
return
c
.
get
(
Calendar
.
DAY_OF_WEEK
)
==
Calendar
.
SUNDAY
;
}
public
static
boolean
isMonthend
(
Date
date
)
{
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
addDay
(
date
,
1
));
return
c
.
get
(
Calendar
.
DAY_OF_MONTH
)
==
1
;
}
public
static
Date
lastMonthHead
(
Date
date
)
{
if
(
date
==
null
)
{
date
=
today
();
}
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
c
.
set
(
Calendar
.
DAY_OF_MONTH
,
1
);
c
.
add
(
Calendar
.
MONTH
,
-
1
);
return
c
.
getTime
();
}
public
static
Date
lastYearEnd
()
{
return
lastYearEnd
(
null
);
}
public
static
Date
lastYearEnd
(
Date
date
)
{
if
(
date
==
null
)
{
date
=
today
();
}
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
c
.
set
(
Calendar
.
DAY_OF_YEAR
,
1
);
c
.
add
(
Calendar
.
DAY_OF_YEAR
,
-
1
);
return
c
.
getTime
();
}
/**
* 格式化日期(去掉时间)
*
* @param date
* @return java.util.Date (yyyy-MM-dd 00:00:00)
* @author jiangmy
* @date 2016-08-04 14:51:15
* @since 1.0.0
*/
public
static
Date
formatDate
(
Date
date
)
{
return
formatDate
(
date
,
FORMAT_DATE
);
}
/**
* 格式化时间戳(去掉时间)
*
* @param date
* @return java.sql.Timestamp (yyyy-MM-dd 00:00:00)
* @author jiangmy
* @date 2016-08-04 14:51:49
* @since 1.0.0
*/
public
static
Timestamp
formatDate
(
Timestamp
date
)
{
return
toTimestamp
(
formatDate
(
date
,
FORMAT_DATE
));
}
/**
* 格式化日期
*
* @param date 日期
* @param pattern 格式
* @return java.util.Date
* @author jiangmy
* @date 2016-08-04 14:57:02
* @since 1.0.0
*/
public
static
Date
formatDate
(
Date
date
,
String
pattern
)
{
try
{
if
(
pattern
==
null
)
{
pattern
=
FORMAT_DATE
;
}
SimpleDateFormat
format
=
getSdf
(
pattern
);
return
format
.
parse
(
format
.
format
(
date
));
}
catch
(
ParseException
e
)
{
log
.
warn
(
"date:{} pattern:{}"
,
date
,
pattern
,
e
);
}
return
null
;
}
public
static
Date
add
(
Date
date
,
TimeUnit
unit
,
long
amount
)
{
try
{
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
c
.
add
(
Calendar
.
MILLISECOND
,
(
int
)
unit
.
toMillis
(
amount
));
return
c
.
getTime
();
}
catch
(
Exception
e
)
{
}
return
null
;
}
public
static
Date
add
(
Date
date
,
int
field
,
int
amount
)
{
try
{
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
c
.
add
(
field
,
amount
);
return
c
.
getTime
();
}
catch
(
Exception
e
)
{
}
return
null
;
}
/**
* 设置时分秒
*
* @param date
* @param hour
* @param minute
* @param second
* @return
* @author buyi
* @date 2017-04-20 17:23:39
* @since 1.0.0
*/
public
static
Date
set
(
Date
date
,
int
hour
,
int
minute
,
int
second
)
{
try
{
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
c
.
set
(
Calendar
.
HOUR_OF_DAY
,
hour
);
c
.
set
(
Calendar
.
MINUTE
,
minute
);
c
.
set
(
Calendar
.
SECOND
,
second
);
return
c
.
getTime
();
}
catch
(
Exception
e
)
{
}
return
null
;
}
public
static
Date
add
(
Date
date
,
int
year
,
int
month
,
int
day
,
int
hour
,
int
minute
,
int
second
)
{
try
{
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
c
.
add
(
Calendar
.
YEAR
,
year
);
c
.
add
(
Calendar
.
MONTH
,
month
);
c
.
add
(
Calendar
.
DATE
,
day
);
c
.
add
(
Calendar
.
HOUR
,
hour
);
c
.
add
(
Calendar
.
MINUTE
,
minute
);
c
.
add
(
Calendar
.
SECOND
,
second
);
return
c
.
getTime
();
}
catch
(
Exception
e
)
{
}
return
null
;
}
public
static
Timestamp
add
(
Timestamp
date
,
int
field
,
int
amount
)
{
try
{
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
date
);
c
.
add
(
field
,
amount
);
return
new
Timestamp
(
c
.
getTimeInMillis
());
}
catch
(
Exception
e
)
{
}
return
null
;
}
public
static
Date
addYear
(
Date
date
,
int
amount
)
{
return
add
(
date
,
Calendar
.
YEAR
,
amount
);
}
public
static
Date
addMonth
(
Date
date
,
int
amount
)
{
return
add
(
date
,
Calendar
.
MONTH
,
amount
);
}
public
static
Date
addDay
(
Date
date
,
int
amount
)
{
return
add
(
date
,
Calendar
.
DATE
,
amount
);
}
public
static
Date
addWeek
(
Date
date
,
int
amount
)
{
return
add
(
date
,
Calendar
.
WEEK_OF_YEAR
,
amount
);
}
public
static
Date
addHour
(
Date
date
,
int
amount
)
{
return
add
(
date
,
Calendar
.
HOUR
,
amount
);
}
public
static
Date
addSecond
(
Date
date
,
int
amount
)
{
return
add
(
date
,
Calendar
.
SECOND
,
amount
);
}
// 获取date所在周的周一
public
static
Date
getMonday
(
Date
date
)
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
"yyyy-MM-dd"
);
// 设置时间格式
Calendar
cal
=
Calendar
.
getInstance
();
cal
.
setTime
(
date
);
// 判断要计算的日期是否是周日,如果是则减一天计算周六的,否则会出问题,计算到下一周去了
int
dayWeek
=
cal
.
get
(
Calendar
.
DAY_OF_WEEK
);
// 获得当前日期是一个星期的第几天
if
(
1
==
dayWeek
)
{
cal
.
add
(
Calendar
.
DAY_OF_MONTH
,
-
1
);
}
System
.
out
.
println
(
"要计算日期为:"
+
sdf
.
format
(
cal
.
getTime
()));
// 输出要计算日期
cal
.
setFirstDayOfWeek
(
Calendar
.
MONDAY
);
// 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
int
day
=
cal
.
get
(
Calendar
.
DAY_OF_WEEK
);
// 获得当前日期是一个星期的第几天
cal
.
add
(
Calendar
.
DATE
,
cal
.
getFirstDayOfWeek
()
-
day
);
// 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
return
cal
.
getTime
();
}
/**
* 获取date所在月的第一天0点
*
* @param date
* @return
* @author jiangmy
* @date 2016-08-04 15:00:02
* @since 1.0.0
*/
public
static
Date
getMonthHead
(
Date
date
)
{
return
formatDate
(
date
,
"yyyy-MM-01"
);
}
/**
* 获取date所在月的最后一天23:59:59
*
* @param date
* @return
* @author jiangmy
* @date 2016-08-04 15:00:52
* @since 1.0.0
*/
public
static
Date
getMonthTail
(
Date
date
,
String
pattern
)
{
return
formatDate
(
addSecond
(
addMonth
(
getMonthHead
(
date
),
1
),
-
1
),
pattern
);
}
/**
* 判断两个时间是否是同一天
*
* @param date1
* @param date2
* @return
* @since 1.0.0
*/
public
static
boolean
isSameDay
(
Date
date1
,
Date
date2
)
{
if
(
date1
==
null
||
date2
==
null
)
{
return
false
;
}
return
dateToStr
(
date1
).
equals
(
dateToStr
(
date2
));
}
/**
* date1 - date2的时间差(舍弃小数部分,取整)
*
* @param toDate
* @param fromDate
* @param unit
* @return
*/
public
static
long
getTimeDiff
(
Date
toDate
,
Date
fromDate
,
TimeUnit
unit
)
{
if
(
toDate
==
null
||
fromDate
==
null
)
{
throw
new
IllegalArgumentException
(
"date1:"
+
toDate
+
", date2:"
+
fromDate
+
" both cannot be null!!"
);
}
return
unit
.
convert
(
toDate
.
getTime
()
-
fromDate
.
getTime
(),
TimeUnit
.
MILLISECONDS
);
}
public
static
long
getTimeDiff
(
Timestamp
date1
,
Timestamp
date2
,
TimeUnit
unit
)
{
if
(
date1
==
null
||
date2
==
null
)
{
throw
new
IllegalArgumentException
(
"date1:"
+
date1
+
", date2:"
+
date2
+
" both cannot be null!!"
);
}
return
unit
.
convert
(
date1
.
getTime
()
-
date2
.
getTime
(),
TimeUnit
.
MILLISECONDS
);
}
public
static
Date
addMinute
(
Date
startTime
,
int
i
)
{
return
add
(
startTime
,
Calendar
.
MINUTE
,
i
);
}
/**
* 时间戳毫秒转字符串(yyyy-MM-dd HH:mm:ss)
*
* @param t
* @return
* @author jiangmy
* @date 2016-08-04 15:01:53
* @since 1.0.0
*/
public
static
String
milli2str
(
long
t
)
{
return
DateUtils
.
datetimeToStr
(
new
Date
(
t
));
}
/**
* @param date
* @return
* @author jiangmy
* @date 2016-12-08 13:20:02
*/
public
static
Date
lastSecondOfDay
(
Date
date
)
{
return
DateUtils
.
add
(
DateUtils
.
formatDate
(
date
),
0
,
0
,
1
,
0
,
0
,
-
1
);
}
public
static
Date
lastSecondOfToday
()
{
return
DateUtils
.
add
(
DateUtils
.
formatDate
(
new
Date
()),
0
,
0
,
1
,
0
,
0
,
-
1
);
}
/**
* 获取年份的最后一天日期
*/
public
static
Date
lastDayOfYear
(
int
year
)
{
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
clear
();
calendar
.
set
(
Calendar
.
YEAR
,
year
);
calendar
.
roll
(
Calendar
.
DAY_OF_YEAR
,
-
1
);
Date
currYearLast
=
calendar
.
getTime
();
return
currYearLast
;
}
/**
* @param date
* @return
* @author jiangmy
* @date 2017-04-25 10:27:33
* @since 1.0.0
*/
public
static
int
getMonthDayCount
(
Date
date
)
{
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
setTime
(
date
);
return
calendar
.
getActualMaximum
(
Calendar
.
DAY_OF_MONTH
);
}
/**
* 求指定日期距离今天的天数
*
* @param endDate
* @return
* @author qinqz
* @date 2017-05-09 19:09:37
* @since 1.0.0
*/
public
static
long
getDayLeft
(
Date
endDate
)
{
long
timeLeft
=
0L
;
try
{
Date
now
=
new
Date
(
System
.
currentTimeMillis
());
long
lefttime
=
(
endDate
.
getTime
()
-
now
.
getTime
())
/
1000
;
long
day
=
lefttime
/
(
24
*
60
*
60
);
return
day
;
}
catch
(
Exception
e
)
{
}
return
timeLeft
;
}
/**
* 求指定日期距离今天的剩余的时间(倒计时)
*
* @param endDate
* @return
* @author qinqz
* @date 2017-05-09 19:09:37
* @since 1.0.0
*/
public
static
String
getTimeLeft
(
Date
endDate
)
{
String
timeLeft
=
""
;
try
{
Date
now
=
new
Date
(
System
.
currentTimeMillis
());
long
lefttime
=
(
endDate
.
getTime
()
-
now
.
getTime
())
/
1000
;
long
day
=
lefttime
/
(
24
*
60
*
60
);
long
hour
=
lefttime
/
(
60
*
60
)
-
day
*
24
;
long
minute
=
lefttime
/
60
-
day
*
24
*
60
-
hour
*
60
;
long
second
=
lefttime
-
day
*
24
*
60
*
60
-
hour
*
60
*
60
-
minute
*
60
;
timeLeft
=
(
day
+
"天"
+
hour
+
"小时"
+
minute
+
"分"
+
second
+
"秒"
);
}
catch
(
Exception
e
)
{
}
return
timeLeft
;
}
public
static
long
millisBetweenDate
(
String
start
,
String
end
)
{
return
Duration
.
between
(
strToLocalDate
(
start
),
strToLocalDate
(
end
)).
toMillis
();
}
public
static
int
daysBetweenDate
(
Date
start
,
Date
end
)
{
long
startTime
=
start
.
getTime
();
long
endTime
=
end
.
getTime
();
int
days
=
(
int
)
((
endTime
-
startTime
)
/
(
86400
*
1000
));
return
days
;
}
public
static
long
millisBetweenDateTime
(
String
start
,
String
end
)
{
return
Duration
.
between
(
strToLocalDateTime
(
start
),
strToLocalDateTime
(
end
)).
toMillis
();
}
public
static
long
millisToNow
(
String
start
)
{
return
Duration
.
between
(
strToLocalDateTime
(
start
),
LocalDateTime
.
now
()).
toMillis
();
}
public
static
long
millisFromNow
(
LocalDateTime
end
)
{
return
Duration
.
between
(
LocalDateTime
.
now
(),
end
).
toMillis
();
}
public
static
long
millisFromNow
(
String
end
)
{
return
millisFromNow
(
strToDateTime
(
end
));
}
private
static
long
millisFromNow
(
Date
strToDateTime
)
{
return
System
.
currentTimeMillis
()
-
strToDateTime
.
getTime
();
}
/**
* 返回一个SimpleDateFormat,每个线程只会new一次pattern对应的sdf
*
* @param pattern
* @return
*/
private
static
SimpleDateFormat
getSdf
(
final
String
pattern
)
{
return
getSdf
(
pattern
,
Locale
.
CHINESE
);
}
private
static
SimpleDateFormat
getSdf
(
final
String
pattern
,
Locale
locale
)
{
Map
<
String
,
SimpleDateFormat
>
tl
=
sdfMap
.
get
();
SimpleDateFormat
sdf
=
tl
.
get
(
pattern
);
if
(
sdf
==
null
)
{
sdf
=
new
SimpleDateFormat
(
pattern
,
locale
);
tl
.
put
(
pattern
,
sdf
);
}
return
sdf
;
}
/**
* 获取星期几
*/
public
static
String
getWeekStr
(
Date
date
)
{
Calendar
cal
=
Calendar
.
getInstance
();
if
(
date
!=
null
)
cal
.
setTime
(
date
);
int
week
=
cal
.
get
(
Calendar
.
DAY_OF_WEEK
);
switch
(
week
)
{
case
1
:
return
"Sunday"
;
case
2
:
return
"Monday"
;
case
3
:
return
"Tuesday"
;
case
4
:
return
"Wednesday"
;
case
5
:
return
"Thursday"
;
case
6
:
return
"Friday"
;
case
7
:
return
"Saturday"
;
}
return
""
;
}
/**
* 判断两个时间是否在七天内
*/
public
static
boolean
isLatestWeek
(
Date
addtime
,
Date
now
)
{
Calendar
calendar
=
Calendar
.
getInstance
();
// 得到日历
calendar
.
setTime
(
now
);
// 把当前时间赋给日历
calendar
.
add
(
Calendar
.
DAY_OF_MONTH
,
-
7
);
// 设置为7天前
Date
before7days
=
calendar
.
getTime
();
// 得到7天前的时间
if
(
before7days
.
getTime
()
<
addtime
.
getTime
())
{
return
true
;
}
else
{
return
false
;
}
}
/**
* @param d
* @return
*/
public
static
int
getDayOfYear
(
Date
d
)
{
Calendar
c
=
Calendar
.
getInstance
();
c
.
setTime
(
d
);
return
c
.
get
(
Calendar
.
DAY_OF_YEAR
);
}
/**
* 获取时间年月
*
* @param date
* @return
*/
public
static
String
getYearMonth
(
Date
date
)
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
"yyyy-MM"
);
String
time
=
sdf
.
format
(
date
);
return
time
;
}
public
static
boolean
isBetween
(
Date
date
,
Date
startDate
,
Date
endTime
)
{
long
t
=
date
.
getTime
();
return
t
>=
startDate
.
getTime
()
&&
t
<=
endTime
.
getTime
();
}
// 获取当前时间的前几天的日期
public
static
String
getDiffDateStr
(
int
day
)
{
Date
date
=
new
Date
();
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
"yyyyMMdd"
);
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
setTime
(
date
);
calendar
.
add
(
Calendar
.
DATE
,
day
);
date
=
calendar
.
getTime
();
String
diffDate
=
sdf
.
format
(
date
);
return
diffDate
;
}
/**
* 生成时间列表
*
* @param date 时间
* @param nday 天数
* @param format 时间字符串格式
* @return
* @throws Exception
*/
public
static
List
<
String
>
createDateList
(
Date
date
,
int
nday
,
String
format
)
{
Calendar
cal
=
Calendar
.
getInstance
();
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
format
);
// Date date = sdf.parse(datestr);
cal
.
setTime
(
date
);
List
<
String
>
dateList
=
new
ArrayList
<
String
>();
for
(
int
i
=
0
;
i
<
nday
;
i
++)
{
dateList
.
add
(
sdf
.
format
(
cal
.
getTime
()));
cal
.
add
(
Calendar
.
DATE
,
-
1
);
}
return
dateList
;
}
public
static
void
main
(
String
[]
args
)
{
// System.out.println(lastSecondOfDay(new Date()));
// System.out.println(getCurrentDateTime());
// System.out.println(getMonthDayCount(new Date()));
// System.out.println(getMonthDayCount(DateUtils.strToDate("2018-02-03")));
// System.out.println(DateUtils.strToDate("2018-02-03"));
// System.out.println(DateUtils.strToLocalDate("2018-02-03", "yyyy-MM-dd"));
// System.out.println(DateUtils.strToLocalDateTime("2018-02-03 00", "yyyy-MM-dd HH"));
// System.out.println(DateUtils.isLocalDateFormat("2018-02-03", "yyyy-MM-dd"));
// System.out.println(DateUtils.millisFromNow("2018-02-03 13:00:00"));
// System.out.println(DateUtils.lastMonthEnd());
// System.out.println(DateUtils.lastYearEnd(DateUtils.strToDate("2020-12-01")));
// System.out.println(lastWeekEnd(strToDate("2020-10-20")));
// System.out.println(lastWeekMonday(strToDate("2020-10-20")));
System
.
out
.
println
(
lastMonthHead
(
strToDate
(
"2020-10-01"
)));
System
.
out
.
println
(
lastMonthEnd
(
strToDate
(
"2020-01-01"
)));
System
.
out
.
println
(
isSunday
(
strToDate
(
"2020-10-24"
)));
System
.
out
.
println
(
isMonthend
(
strToDate
(
"2021-02-28"
)));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/EnumUtil.java
0 → 100644
View file @
81f2091
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/FileFormatUtils.java
0 → 100644
View file @
81f2091
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"
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/HttpServletRequestUtil.java
0 → 100644
View file @
81f2091
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
();
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/HttpServletResponseUtil.java
0 → 100644
View file @
81f2091
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
();
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/HttpUtils.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.io.DataOutputStream
;
import
java.io.File
;
import
java.io.FileInputStream
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.io.OutputStream
;
import
java.io.UnsupportedEncodingException
;
import
java.net.HttpURLConnection
;
import
java.net.URL
;
import
java.net.URLEncoder
;
import
java.nio.charset.Charset
;
import
java.nio.charset.StandardCharsets
;
import
java.security.GeneralSecurityException
;
import
java.security.KeyManagementException
;
import
java.security.KeyStore
;
import
java.security.NoSuchAlgorithmException
;
import
java.security.NoSuchProviderException
;
import
java.security.SecureRandom
;
import
java.security.cert.CertificateException
;
import
java.security.cert.X509Certificate
;
import
java.util.HashMap
;
import
java.util.List
;
import
java.util.Map
;
import
java.util.Map.Entry
;
import
java.util.regex.Matcher
;
import
java.util.regex.Pattern
;
import
javax.net.ssl.HostnameVerifier
;
import
javax.net.ssl.HttpsURLConnection
;
import
javax.net.ssl.KeyManagerFactory
;
import
javax.net.ssl.SSLContext
;
import
javax.net.ssl.SSLSession
;
import
javax.net.ssl.TrustManager
;
import
javax.net.ssl.TrustManagerFactory
;
import
javax.net.ssl.X509TrustManager
;
import
org.apache.commons.codec.binary.Base64
;
import
org.apache.commons.lang3.StringUtils
;
import
org.springframework.util.StreamUtils
;
import
com.google.common.collect.Lists
;
import
com.google.common.collect.Maps
;
import
cn.hutool.core.io.FileUtil
;
import
cn.hutool.core.io.IoUtil
;
import
cn.hutool.core.util.StrUtil
;
import
cn.hutool.http.HttpUtil
;
import
lombok.Getter
;
import
lombok.Setter
;
import
lombok.extern.slf4j.Slf4j
;
/**
* https 请求 微信为https的请求
*
* @author jiangmy
* @date 2016-08-01 下午2:40:19
*/
@Slf4j
public
class
HttpUtils
{
private
static
final
int
CONNECT_TIMEOUT
=
30000
;
private
static
final
int
READ_TIMEOUT
=
60000
;
private
static
final
String
DEFAULT_CHARSET
=
"UTF-8"
;
// 默认字符集
private
static
final
String
_GET
=
"GET"
;
// GET
private
static
final
String
_POST
=
"POST"
;
// POST
private
static
final
String
_CONTENT_TYPE_JSON
=
"application/json"
;
private
static
final
String
_CONTENT_TYPE_FORM
=
"application/x-www-form-urlencoded"
;
// add by maojian 信任全部
private
static
TrustManager
[]
trustAllCerts
=
new
TrustManager
[]
{
new
X509TrustManager
()
{
@Override
public
java
.
security
.
cert
.
X509Certificate
[]
getAcceptedIssuers
()
{
return
null
;
}
@Override
public
void
checkClientTrusted
(
java
.
security
.
cert
.
X509Certificate
[]
certs
,
String
authType
)
{
}
@Override
public
void
checkServerTrusted
(
java
.
security
.
cert
.
X509Certificate
[]
certs
,
String
authType
)
{
}
}
};
// add by maojian 忽略hostname验证
private
static
HostnameVerifier
hostnameVerifier
=
(
s
,
sslSession
)
->
true
;
public
static
void
setSNI
(
String
value
)
{
System
.
setProperty
(
"jsse.enableSNIExtension"
,
value
);
}
private
static
String
getSNI
()
{
return
System
.
getProperty
(
"jsse.enableSNIExtension"
);
}
/**
* 获得KeyStore.
*
* @param keyStorePath 密钥库路径
* @param password 密码
* @return 密钥库
* @throws Exception
*/
public
static
KeyStore
getKeyStore
(
String
password
,
String
keyStorePath
)
throws
Exception
{
// 实例化密钥库
KeyStore
ks
=
KeyStore
.
getInstance
(
KeyStore
.
getDefaultType
());
// 获得密钥库文件流
try
(
FileInputStream
is
=
new
FileInputStream
(
keyStorePath
))
{
// 加载密钥库
ks
.
load
(
is
,
password
.
toCharArray
());
}
return
ks
;
}
/**
* 获得SSLSocketFactory.
*
* @param password 密码
* @param keyStorePath 密钥库路径
* @param trustStorePath 信任库路径
* @return SSLSocketFactory
* @throws Exception
*/
public
static
SSLContext
getSSLContext
(
String
password
,
String
keyStorePath
,
String
trustStorePath
)
throws
Exception
{
// 实例化SSL上下文
SSLContext
ctx
=
SSLContext
.
getInstance
(
"TLS"
);
// 实例化密钥库
KeyManagerFactory
keyManagerFactory
=
KeyManagerFactory
.
getInstance
(
KeyManagerFactory
.
getDefaultAlgorithm
());
// 获得密钥库
KeyStore
keyStore
=
getKeyStore
(
password
,
keyStorePath
);
// 初始化密钥工厂
keyManagerFactory
.
init
(
keyStore
,
password
.
toCharArray
());
if
(
trustStorePath
==
null
)
{
TrustManager
[]
tm
=
{
new
MyX509TrustManager
()
};
// 初始化SSL上下文
ctx
.
init
(
keyManagerFactory
.
getKeyManagers
(),
tm
,
new
java
.
security
.
SecureRandom
());
return
ctx
;
}
// 获得信任库
KeyStore
trustStore
=
getKeyStore
(
password
,
trustStorePath
);
// 实例化信任库
TrustManagerFactory
trustManagerFactory
=
TrustManagerFactory
.
getInstance
(
TrustManagerFactory
.
getDefaultAlgorithm
());
// 初始化信任库
trustManagerFactory
.
init
(
trustStore
);
// 初始化SSL上下文
ctx
.
init
(
keyManagerFactory
.
getKeyManagers
(),
trustManagerFactory
.
getTrustManagers
(),
null
);
// 获得SSLSocketFactory
return
ctx
;
}
/**
* 导证书,此方法不能被调用,会影响其它渠道走https,例如存管。
*
* @See initHttpsURLConnection(String password, String keyStorePath, String
* trustStorePath, HttpsURLConnection connection)
* @param password 密码
* @param keyStorePath 密钥库路径
* @param trustStorePath 信任库路径
* @throws Exception
*/
@Deprecated
public
static
void
initHttpsURLConnection
(
String
password
,
String
keyStorePath
,
String
trustStorePath
)
throws
Exception
{
// 声明SSL上下文
SSLContext
sslContext
=
null
;
// 实例化主机名验证接口
HostnameVerifier
hnv
=
new
MyHostnameVerifier
();
try
{
sslContext
=
getSSLContext
(
password
,
keyStorePath
,
trustStorePath
);
}
catch
(
GeneralSecurityException
e
)
{
e
.
printStackTrace
();
}
if
(
sslContext
!=
null
)
{
HttpsURLConnection
.
setDefaultSSLSocketFactory
(
sslContext
.
getSocketFactory
());
}
HttpsURLConnection
.
setDefaultHostnameVerifier
(
hnv
);
}
/**
* 导证书
*
* @param password 密码
* @param keyStorePath 密钥库路径
* @param trustStorePath 信任库路径
* @throws Exception
*/
public
static
void
initHttpsURLConnection
(
String
password
,
String
keyStorePath
,
String
trustStorePath
,
HttpsURLConnection
connection
)
throws
Exception
{
// 声明SSL上下文
SSLContext
sslContext
=
null
;
// 实例化主机名验证接口
HostnameVerifier
hnv
=
new
MyHostnameVerifier
();
try
{
sslContext
=
getSSLContext
(
password
,
keyStorePath
,
trustStorePath
);
}
catch
(
GeneralSecurityException
e
)
{
e
.
printStackTrace
();
}
if
(
sslContext
!=
null
)
{
connection
.
setSSLSocketFactory
(
sslContext
.
getSocketFactory
());
}
connection
.
setHostnameVerifier
(
hnv
);
}
public
static
String
joinParams
(
Map
<
String
,
String
>
params
,
String
charset
)
{
if
(
params
==
null
||
params
.
isEmpty
())
{
return
null
;
}
StringBuilder
sb
=
new
StringBuilder
();
for
(
Entry
<
String
,
String
>
entry
:
params
.
entrySet
())
{
try
{
if
(
entry
.
getValue
()
==
null
)
{
continue
;
}
if
(
sb
.
length
()
>
0
)
{
sb
.
append
(
"&"
);
}
sb
.
append
(
entry
.
getKey
()).
append
(
"="
).
append
(
URLEncoder
.
encode
(
entry
.
getValue
(),
charset
));
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
String
p
=
sb
.
toString
();
return
p
;
}
/**
* @author jiangmy
* @date 2017-03-11 16:15:55
* @since v1.0.0
* @param params
* @return
*/
public
static
String
joinParams
(
String
url
,
Map
<
String
,
String
>
params
,
String
charset
)
{
String
p
=
joinParams
(
params
,
charset
);
if
(
StringUtils
.
isNotBlank
(
p
))
{
if
(
url
.
contains
(
"?"
))
{
url
+=
"&"
+
p
;
}
else
{
url
+=
"?"
+
p
;
}
}
return
url
;
}
/**
* 检测是否https
*
* @param url
*/
private
static
boolean
isHttps
(
String
url
)
{
return
url
.
toLowerCase
().
startsWith
(
"https"
);
}
/**
* 初始化http请求参数
*
* @param url
* @param method
* @param readTimeout
* @param connectTimeout
* @param charset
* @param charset2
* @param password
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
private
static
HttpURLConnection
initConnection
(
String
url
,
String
method
,
Map
<
String
,
String
>
headers
,
String
userName
,
String
password
,
String
contentType
,
String
charset
,
int
connectTimeout
,
int
readTimeout
)
throws
IOException
,
NoSuchAlgorithmException
,
NoSuchProviderException
,
KeyManagementException
{
// 格式化一下url
if
(
StringUtils
.
contains
(
url
,
"?"
))
{
url
=
build
(
url
,
charset
).
getUrlEncoded
();
}
URL
_url
=
new
URL
(
url
);
HttpURLConnection
http
;
if
(
isHttps
(
url
))
{
http
=
(
HttpsURLConnection
)
_url
.
openConnection
();
}
else
{
http
=
(
HttpURLConnection
)
_url
.
openConnection
();
}
http
.
setConnectTimeout
(
connectTimeout
);
// 连接超时
http
.
setReadTimeout
(
connectTimeout
);
// 读取超时 --服务器响应比较慢,增大时间
http
.
setRequestMethod
(
method
);
http
.
setUseCaches
(
false
);
http
.
setDoOutput
(
true
);
http
.
setDoInput
(
true
);
http
.
setRequestProperty
(
"accept"
,
"*/*"
);
http
.
setRequestProperty
(
"connection"
,
"Keep-Alive"
);
http
.
setRequestProperty
(
"user-agent"
,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"
);
http
.
setRequestProperty
(
"Accept-Charset"
,
charset
);
http
.
setRequestProperty
(
"Content-Type"
,
contentType
);
http
.
setRequestProperty
(
"User-Agent"
,
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.30 Safari/537.36"
);
if
(
StringUtils
.
isNotBlank
(
userName
))
{
String
authentication
=
userName
+
':'
+
password
;
String
encoded
=
Base64
.
encodeBase64String
(
authentication
.
getBytes
(
charset
));
http
.
setRequestProperty
(
"Authorization"
,
"Basic "
+
encoded
);
}
if
(
null
!=
headers
&&
!
headers
.
isEmpty
())
{
for
(
Entry
<
String
,
String
>
entry
:
headers
.
entrySet
())
{
http
.
setRequestProperty
(
entry
.
getKey
(),
entry
.
getValue
());
}
}
return
http
;
}
/**
* 初始化http请求参数
*
* @param url
* @param method
* @param readTimeout
* @param connectTimeout
* @param charset
* @param charset2
* @param password
* @return
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyManagementException
*/
private
static
HttpURLConnection
initConnection
(
String
url
,
String
method
,
Map
<
String
,
String
>
headers
,
String
userName
,
String
password
,
String
contentType
,
String
charset
,
int
connectTimeout
,
int
readTimeout
,
boolean
isIgnore
)
throws
IOException
,
NoSuchAlgorithmException
,
NoSuchProviderException
,
KeyManagementException
{
URL
_url
=
new
URL
(
url
);
HttpURLConnection
http
;
if
(
isHttps
(
url
))
{
HttpsURLConnection
https
=
(
HttpsURLConnection
)
_url
.
openConnection
();
if
(
isIgnore
)
{
SSLContext
sc
=
SSLContext
.
getInstance
(
"TLS"
);
sc
.
init
(
null
,
trustAllCerts
,
new
SecureRandom
());
https
.
setSSLSocketFactory
(
sc
.
getSocketFactory
());
https
.
setHostnameVerifier
(
hostnameVerifier
);
}
http
=
https
;
}
else
{
http
=
(
HttpURLConnection
)
_url
.
openConnection
();
}
http
.
setConnectTimeout
(
connectTimeout
);
// 连接超时
http
.
setReadTimeout
(
connectTimeout
);
// 读取超时 --服务器响应比较慢,增大时间
http
.
setRequestMethod
(
method
);
http
.
setUseCaches
(
false
);
http
.
setDoOutput
(
true
);
http
.
setDoInput
(
true
);
http
.
setRequestProperty
(
"accept"
,
"*/*"
);
http
.
setRequestProperty
(
"connection"
,
"Keep-Alive"
);
http
.
setRequestProperty
(
"user-agent"
,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"
);
http
.
setRequestProperty
(
"Accept-Charset"
,
charset
);
http
.
setRequestProperty
(
"Content-Type"
,
contentType
);
http
.
setRequestProperty
(
"User-Agent"
,
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.30 Safari/537.36"
);
if
(
StringUtils
.
isNotBlank
(
userName
))
{
String
authentication
=
userName
+
':'
+
password
;
String
encoded
=
Base64
.
encodeBase64String
(
authentication
.
getBytes
(
charset
));
http
.
setRequestProperty
(
"Authorization"
,
"Basic "
+
encoded
);
}
if
(
null
!=
headers
&&
!
headers
.
isEmpty
())
{
for
(
Entry
<
String
,
String
>
entry
:
headers
.
entrySet
())
{
http
.
setRequestProperty
(
entry
.
getKey
(),
entry
.
getValue
());
}
}
return
http
;
}
public
static
String
getForm
(
String
url
,
Map
<
String
,
String
>
params
,
Map
<
String
,
String
>
headers
,
String
contentType
,
String
charset
,
String
userName
,
String
password
,
int
connectTimeout
,
int
readTimeout
)
{
HttpURLConnection
urlCon
;
try
{
charset
=
StringUtils
.
isBlank
(
charset
)
?
DEFAULT_CHARSET
:
charset
;
contentType
=
StringUtils
.
isBlank
(
contentType
)
?
_CONTENT_TYPE_FORM
+
";charset="
+
charset
:
contentType
;
//
url
=
joinParams
(
url
,
params
,
charset
);
//
urlCon
=
initConnection
(
url
,
_GET
,
headers
,
userName
,
password
,
contentType
,
charset
,
connectTimeout
,
readTimeout
);
urlCon
.
connect
();
//
if
(
urlCon
.
getResponseCode
()
==
200
)
{
log
.
info
(
"url:{} rsp:{}"
,
url
,
urlCon
.
getResponseCode
());
try
(
InputStream
inputStream
=
urlCon
.
getInputStream
())
{
byte
[]
data
=
IoUtil
.
readBytes
(
inputStream
);
return
new
String
(
data
,
charset
);
}
}
else
{
log
.
error
(
"url:{} rsp:{}"
,
url
,
urlCon
.
getResponseCode
());
}
}
catch
(
Exception
e
)
{
log
.
error
(
"url:"
+
url
,
e
);
}
return
null
;
}
public
static
String
postForm
(
String
url
,
Map
<
String
,
String
>
params
,
Map
<
String
,
String
>
headers
,
String
contentType
,
String
charset
,
String
userName
,
String
password
,
int
connectTimeout
,
int
readTimeout
)
{
try
{
return
postFormDirect
(
url
,
params
,
headers
,
contentType
,
charset
,
userName
,
password
,
connectTimeout
,
readTimeout
);
}
catch
(
IOException
e
)
{
log
.
info
(
"url:{} params:{} exc:{}"
,
url
,
params
,
e
.
getMessage
());
}
return
null
;
}
public
static
String
postForm
(
String
url
,
Map
<
String
,
String
>
params
,
Map
<
String
,
String
>
headers
,
String
contentType
,
String
charset
,
String
userName
,
String
password
,
int
connectTimeout
,
int
readTimeout
,
boolean
isIgnore
)
{
try
{
return
postFormDirect
(
url
,
params
,
headers
,
contentType
,
charset
,
userName
,
password
,
connectTimeout
,
readTimeout
,
isIgnore
);
}
catch
(
IOException
e
)
{
log
.
info
(
"url:{} params:{} exc:{}"
,
url
,
params
,
e
.
getMessage
());
}
return
null
;
}
public
static
String
postBody
(
String
url
,
String
json
,
Map
<
String
,
String
>
headers
,
String
contentType
,
String
charset
,
String
userName
,
String
password
,
int
connectTimeout
,
int
readTimeout
)
{
try
{
return
postBodyDirect
(
url
,
json
,
headers
,
contentType
,
charset
,
userName
,
password
,
connectTimeout
,
readTimeout
);
}
catch
(
IOException
e
)
{
log
.
info
(
"url:{} json:{} exc:{}"
,
url
,
json
,
e
.
getMessage
());
}
return
null
;
}
public
static
String
postFormDirect
(
String
url
,
Map
<
String
,
String
>
params
,
Map
<
String
,
String
>
headers
,
String
contentType
,
String
charset
,
String
userName
,
String
password
,
int
connectTimeout
,
int
readTimeout
)
throws
IOException
{
charset
=
charset
==
null
?
Charset
.
defaultCharset
().
name
()
:
charset
;
return
postFormDirect
(
url
,
joinParams
(
params
,
charset
),
headers
,
contentType
,
charset
,
userName
,
password
,
connectTimeout
,
readTimeout
);
}
public
static
String
postFormDirect
(
String
url
,
Map
<
String
,
String
>
params
,
Map
<
String
,
String
>
headers
,
String
contentType
,
String
charset
,
String
userName
,
String
password
,
int
connectTimeout
,
int
readTimeout
,
boolean
isIgnore
)
throws
IOException
{
charset
=
charset
==
null
?
Charset
.
defaultCharset
().
name
()
:
charset
;
return
postFormDirect
(
url
,
joinParams
(
params
,
charset
),
headers
,
contentType
,
charset
,
userName
,
password
,
connectTimeout
,
readTimeout
,
isIgnore
);
}
public
static
String
postFormDirect
(
String
url
,
String
param
,
Map
<
String
,
String
>
headers
,
String
contentType
,
String
charset
,
String
userName
,
String
password
,
int
connectTimeout
,
int
readTimeout
)
throws
IOException
{
HttpURLConnection
urlCon
=
null
;
charset
=
charset
==
null
?
Charset
.
defaultCharset
().
name
()
:
charset
;
// String param = joinParams(params, charset);
try
{
contentType
=
contentType
==
null
?
_CONTENT_TYPE_FORM
+
";charset="
+
charset
:
contentType
;
//
urlCon
=
initConnection
(
url
,
_POST
,
headers
,
userName
,
password
,
contentType
,
charset
,
connectTimeout
,
readTimeout
);
urlCon
.
setRequestProperty
(
"Content-Type"
,
contentType
);
urlCon
.
connect
();
//
if
(
StringUtils
.
isNotBlank
(
param
))
{
try
(
OutputStream
outputStream
=
urlCon
.
getOutputStream
())
{
outputStream
.
write
(
param
.
getBytes
(
charset
));
// 输入参数
outputStream
.
flush
();
}
}
//
if
(
urlCon
.
getResponseCode
()
==
200
)
{
log
.
info
(
"url:{}; param:{}; rsp:{}"
,
url
,
param
,
urlCon
.
getResponseCode
());
try
(
InputStream
inputStream
=
urlCon
.
getInputStream
())
{
byte
[]
data
=
StreamUtils
.
copyToByteArray
(
inputStream
);
return
new
String
(
data
,
charset
);
}
}
else
{
log
.
error
(
"url:{}; param:{}; rsp:{}"
,
url
,
param
,
urlCon
.
getResponseCode
());
}
}
catch
(
UnsupportedEncodingException
|
NoSuchAlgorithmException
|
KeyManagementException
|
NoSuchProviderException
e
)
{
log
.
error
(
"url:"
+
url
+
" param:"
+
param
,
e
);
}
finally
{
if
(
urlCon
!=
null
)
{
urlCon
.
disconnect
();
}
}
return
null
;
}
public
static
String
postFormDirect
(
String
url
,
String
param
,
Map
<
String
,
String
>
headers
,
String
contentType
,
String
charset
,
String
userName
,
String
password
,
int
connectTimeout
,
int
readTimeout
,
boolean
isIgnore
)
throws
IOException
{
HttpURLConnection
urlCon
=
null
;
charset
=
charset
==
null
?
Charset
.
defaultCharset
().
name
()
:
charset
;
// String param = joinParams(params, charset);
try
{
contentType
=
contentType
==
null
?
_CONTENT_TYPE_FORM
+
";charset="
+
charset
:
contentType
;
//
urlCon
=
initConnection
(
url
,
_POST
,
headers
,
userName
,
password
,
contentType
,
charset
,
connectTimeout
,
readTimeout
,
isIgnore
);
urlCon
.
setRequestProperty
(
"Content-Type"
,
contentType
);
urlCon
.
connect
();
//
if
(
StringUtils
.
isNotBlank
(
param
))
{
try
(
OutputStream
outputStream
=
urlCon
.
getOutputStream
())
{
outputStream
.
write
(
param
.
getBytes
(
charset
));
// 输入参数
outputStream
.
flush
();
}
}
//
if
(
urlCon
.
getResponseCode
()
==
200
)
{
log
.
info
(
"url:{}; param:{}; rsp:{}"
,
url
,
param
,
urlCon
.
getResponseCode
());
try
(
InputStream
inputStream
=
urlCon
.
getInputStream
())
{
byte
[]
data
=
StreamUtils
.
copyToByteArray
(
inputStream
);
return
new
String
(
data
,
charset
);
}
}
else
{
log
.
error
(
"url:{}; param:{}; rsp:{}"
,
url
,
param
,
urlCon
.
getResponseCode
());
}
}
catch
(
UnsupportedEncodingException
|
NoSuchAlgorithmException
|
KeyManagementException
|
NoSuchProviderException
e
)
{
log
.
error
(
"url:"
+
url
+
" param:"
+
param
,
e
);
}
finally
{
if
(
urlCon
!=
null
)
{
urlCon
.
disconnect
();
}
}
return
null
;
}
public
static
String
postBodyDirect
(
String
url
,
String
json
,
Map
<
String
,
String
>
headers
,
String
contentType
,
String
charset
,
String
userName
,
String
password
,
int
connectTimeout
,
int
readTimeout
)
throws
IOException
{
HttpURLConnection
urlCon
=
null
;
try
{
charset
=
charset
==
null
?
Charset
.
defaultCharset
().
name
()
:
charset
;
contentType
=
contentType
==
null
?
_CONTENT_TYPE_JSON
+
";charset="
+
charset
:
contentType
;
//
String
sni
=
getSNI
();
if
(
null
!=
sni
&&
sni
.
equals
(
"false"
))
{
urlCon
=
initConnection
(
url
,
_POST
,
headers
,
userName
,
password
,
contentType
,
charset
,
connectTimeout
,
readTimeout
,
true
);
}
else
{
urlCon
=
initConnection
(
url
,
_POST
,
headers
,
userName
,
password
,
contentType
,
charset
,
connectTimeout
,
readTimeout
);
}
urlCon
.
setRequestProperty
(
"Content-Type"
,
contentType
);
urlCon
.
connect
();
//
if
(
StringUtils
.
isNotBlank
(
json
))
{
try
(
OutputStream
outputStream
=
urlCon
.
getOutputStream
())
{
outputStream
.
write
(
json
.
getBytes
(
charset
));
// 输入参数
outputStream
.
flush
();
}
}
if
(
urlCon
.
getResponseCode
()
==
200
)
{
log
.
info
(
"url:{}; json:{}; rsp:{}"
,
url
,
json
,
urlCon
.
getResponseCode
());
try
(
InputStream
inputStream
=
urlCon
.
getInputStream
())
{
byte
[]
data
=
StreamUtils
.
copyToByteArray
(
inputStream
);
return
new
String
(
data
,
charset
);
}
}
else
{
log
.
error
(
"url:{}; json:{}; rsp:{}"
,
url
,
json
,
urlCon
.
getResponseCode
());
}
}
catch
(
UnsupportedEncodingException
|
NoSuchAlgorithmException
|
KeyManagementException
|
NoSuchProviderException
e
)
{
log
.
error
(
"url:"
+
url
+
" json:"
+
json
,
e
);
}
finally
{
if
(
urlCon
!=
null
)
{
urlCon
.
disconnect
();
}
}
return
null
;
}
public
static
String
upload
(
String
uploadUrl
,
List
<
File
>
files
)
{
try
{
String
BOUNDARY
=
"---------7d4a6d158c9"
;
// 定义数据分隔线
URL
url
=
new
URL
(
uploadUrl
);
HttpURLConnection
conn
=
(
HttpURLConnection
)
url
.
openConnection
();
// 发送POST请求必须设置如下两行
conn
.
setDoOutput
(
true
);
conn
.
setDoInput
(
true
);
conn
.
setUseCaches
(
false
);
conn
.
setRequestMethod
(
"POST"
);
conn
.
setRequestProperty
(
"connection"
,
"Keep-Alive"
);
conn
.
setRequestProperty
(
"user-agent"
,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"
);
conn
.
setRequestProperty
(
"Charsert"
,
"UTF-8"
);
conn
.
setRequestProperty
(
"Content-Type"
,
"multipart/form-data; boundary="
+
BOUNDARY
);
try
(
OutputStream
out
=
new
DataOutputStream
(
conn
.
getOutputStream
()))
{
byte
[]
end_data
=
(
"\r\n--"
+
BOUNDARY
+
"--\r\n"
).
getBytes
();
// 定义最后数据分隔线
for
(
File
file
:
files
)
{
byte
[]
fileData
=
FileUtil
.
readBytes
(
file
);
// String fname = list.get(i);
// File file = new File(fname);
StringBuilder
sb
=
new
StringBuilder
();
sb
.
append
(
"--"
);
sb
.
append
(
BOUNDARY
);
sb
.
append
(
"\r\n"
);
sb
.
append
(
"Content-Disposition: form-data;name=\"media\";filename=\""
+
file
.
getName
()
+
"\"; filelength="
+
fileData
.
length
+
"\r\n"
);
sb
.
append
(
"Content-Type:application/octet-stream\r\n\r\n"
);
byte
[]
data
=
sb
.
toString
().
getBytes
();
out
.
write
(
data
);
out
.
write
(
fileData
);
out
.
write
(
"\r\n"
.
getBytes
());
// 多个文件时,二个文件之间加入这个
}
out
.
write
(
end_data
);
out
.
flush
();
}
return
IoUtil
.
read
(
conn
.
getInputStream
(),
Charset
.
defaultCharset
());
}
catch
(
Exception
e
)
{
log
.
error
(
uploadUrl
,
e
);
}
return
null
;
}
/**
* @description 功能描述: get 请求
* @return 返回类型:
*/
public
static
String
get
(
String
url
)
{
return
getForm
(
url
,
null
,
null
,
null
,
null
,
null
,
null
,
CONNECT_TIMEOUT
,
READ_TIMEOUT
);
}
/**
* @description 功能描述: get 请求
* @return 返回类型:
* @throws UnsupportedEncodingException
*/
public
static
String
get
(
String
url
,
Map
<
String
,
String
>
params
)
{
return
getForm
(
url
,
params
,
null
,
null
,
null
,
null
,
null
,
CONNECT_TIMEOUT
,
READ_TIMEOUT
);
}
/**
* @description 功能描述: POST 请求
* @return 返回类型:
*/
public
static
String
post
(
String
url
,
String
json
)
{
return
postBody
(
url
,
json
,
null
,
null
,
null
,
null
,
null
,
CONNECT_TIMEOUT
,
READ_TIMEOUT
);
}
/**
* post map 请求
*
* @param url
* @param params
* @return
* @throws UnsupportedEncodingException
*/
public
static
String
post
(
String
url
,
Map
<
String
,
String
>
params
)
{
return
postForm
(
url
,
params
,
null
,
null
,
null
,
null
,
null
,
CONNECT_TIMEOUT
,
READ_TIMEOUT
);
}
/**
* post map 请求
*
* @param url
* @param params
* @return
* @throws UnsupportedEncodingException
*/
public
static
String
post
(
String
url
,
Map
<
String
,
String
>
params
,
boolean
isIgnore
)
{
return
postForm
(
url
,
params
,
null
,
null
,
null
,
null
,
null
,
CONNECT_TIMEOUT
,
READ_TIMEOUT
,
isIgnore
);
}
/**
* post map 请求,headers请求头
*
* @param url
* @param params
* @return
* @throws UnsupportedEncodingException
*/
public
static
String
post
(
String
url
,
Map
<
String
,
String
>
params
,
Map
<
String
,
String
>
headers
)
{
return
postForm
(
url
,
params
,
headers
,
null
,
null
,
null
,
null
,
CONNECT_TIMEOUT
,
READ_TIMEOUT
);
}
/**
* map构造url
*
* @description 功能描述:
* @return 返回类型:
* @throws UnsupportedEncodingException
*/
public
static
String
map2Url
(
Map
<
String
,
String
>
paramToMap
)
{
if
(
null
==
paramToMap
||
paramToMap
.
isEmpty
())
{
return
null
;
}
StringBuffer
url
=
new
StringBuffer
();
boolean
isfist
=
true
;
for
(
Entry
<
String
,
String
>
entry
:
paramToMap
.
entrySet
())
{
if
(
isfist
)
{
isfist
=
false
;
}
else
{
url
.
append
(
'&'
);
}
url
.
append
(
entry
.
getKey
()).
append
(
'='
);
String
value
=
entry
.
getValue
();
if
(
StringUtils
.
isNotBlank
(
value
))
{
try
{
url
.
append
(
URLEncoder
.
encode
(
value
,
DEFAULT_CHARSET
));
}
catch
(
UnsupportedEncodingException
e
)
{
e
.
printStackTrace
();
}
}
}
return
url
.
toString
();
}
private
static
final
String
URL_REG
=
"([a-zA-z]+)://([^\\:\\?\\/]+)(\\:[0-9]+){0,1}(/[^\\?]*){0,}(\\?){0,}(.*)"
;
private
static
Pattern
pattern
=
Pattern
.
compile
(
URL_REG
);
private
static
PluralCache
<
String
,
Url
>
CACHE
=
new
PluralCache
<>(
3000
);
public
static
Url
build
(
String
url
)
{
return
build
(
url
,
null
);
}
public
static
Url
build
(
String
url
,
String
charset
)
{
Url
u
=
CACHE
.
get
(
url
);
if
(
u
==
null
)
{
u
=
new
Url
(
url
,
charset
);
CACHE
.
put
(
url
,
u
);
}
return
u
;
}
@Getter
@Setter
public
static
class
Url
{
private
String
protocol
;
private
String
domain
;
private
int
port
=
80
;
private
String
uri
;
private
String
queryStr
;
private
String
charset
=
StandardCharsets
.
UTF_8
.
name
();
private
String
lastUri
=
""
;
public
Url
(
String
url
)
{
this
(
url
,
null
);
}
public
Url
(
String
url
,
String
charset
)
{
if
(
charset
!=
null
)
{
this
.
charset
=
charset
;
}
Matcher
matcher
=
pattern
.
matcher
(
url
);
if
(
matcher
.
find
())
{
this
.
protocol
=
matcher
.
group
(
1
);
this
.
domain
=
matcher
.
group
(
2
);
String
p
=
matcher
.
group
(
3
);
if
(
p
!=
null
)
{
this
.
port
=
Integer
.
parseInt
(
p
.
substring
(
1
));
}
this
.
uri
=
matcher
.
group
(
4
);
if
(
this
.
uri
==
null
)
{
this
.
uri
=
""
;
}
this
.
queryStr
=
matcher
.
group
(
6
);
if
(
isHttps
()
&&
this
.
port
==
80
)
{
this
.
port
=
443
;
}
if
(
StringUtils
.
isNotBlank
(
this
.
uri
))
{
this
.
lastUri
=
StringUtils
.
substringAfterLast
(
this
.
uri
,
"/"
);
}
}
}
public
boolean
isHttps
()
{
return
StringUtils
.
equalsIgnoreCase
(
this
.
protocol
,
"HTTPS"
);
}
public
Map
<
String
,
String
>
parameterMap
()
{
Map
<
String
,
String
>
map
=
Maps
.
newHashMap
();
if
(
StringUtils
.
isNotBlank
(
this
.
queryStr
))
{
String
[]
arr
=
this
.
queryStr
.
split
(
"\\&"
);
for
(
String
s
:
arr
)
{
String
[]
brr
=
s
.
split
(
"\\="
);
if
(
brr
!=
null
&&
brr
.
length
==
2
)
{
map
.
put
(
brr
[
0
],
brr
[
1
]);
}
}
}
return
map
;
}
public
String
getUrlEncoded
()
{
Map
<
String
,
String
>
map
=
parameterMap
();
List
<
String
>
ls
=
Lists
.
newArrayList
();
for
(
Entry
<
String
,
String
>
e
:
map
.
entrySet
())
{
try
{
ls
.
add
(
e
.
getKey
()
+
"="
+
URLEncoder
.
encode
(
e
.
getValue
(),
this
.
charset
));
}
catch
(
UnsupportedEncodingException
e1
)
{
e1
.
printStackTrace
();
}
}
String
u
=
this
.
protocol
+
"://"
+
this
.
domain
+
":"
+
this
.
port
+
this
.
uri
+
"?"
+
StringUtils
.
join
(
ls
,
"&"
);
return
u
;
}
public
String
getExt
()
{
if
(
StrUtil
.
contains
(
lastUri
,
"."
))
{
String
ext
=
StrUtil
.
subAfter
(
lastUri
,
"."
,
true
);
if
(
ext
!=
null
&&
ext
.
length
()
<
6
)
{
return
ext
;
}
}
return
null
;
}
}
public
static
String
getProtocol
(
String
url
)
{
return
build
(
url
,
null
).
getProtocol
();
}
public
static
String
getDomain
(
String
url
)
{
return
build
(
url
,
null
).
getDomain
();
}
public
static
int
getPort
(
String
url
)
{
return
build
(
url
,
null
).
getPort
();
}
public
static
String
getContext
(
String
url
)
{
return
build
(
url
,
null
).
getUri
();
}
public
static
String
getUrlEncoded
(
String
url
)
{
return
build
(
url
,
null
).
getUrlEncoded
();
}
public
static
String
downloadFile
(
String
fileUrl
,
String
destDir
,
String
ext
)
{
if
(
StrUtil
.
isBlank
(
fileUrl
))
{
return
null
;
}
File
dir
=
new
File
(
destDir
);
Url
url
=
new
Url
(
fileUrl
);
String
filename
=
SnowFlakeIdUtils
.
generate
(
12
)
+
"_"
+
StringUtils
.
substring
(
url
.
getLastUri
(),
Math
.
max
(
0
,
url
.
getLastUri
().
length
()
-
8
));
if
(
StrUtil
.
isBlank
(
url
.
getExt
())
&&
StrUtil
.
isNotBlank
(
ext
))
{
filename
=
filename
+
"."
+
ext
;
}
try
{
File
destFile
=
new
File
(
dir
,
filename
);
HttpUtil
.
downloadFile
(
fileUrl
,
destFile
);
String
destPath
=
destFile
.
getPath
();
log
.
info
(
"下载网络文件:{} <- {}"
,
destPath
,
fileUrl
);
return
destPath
;
}
catch
(
Exception
e
)
{
log
.
warn
(
"下载网络文件错误:{}/{} -> {} {}"
,
dir
.
getPath
(),
filename
,
fileUrl
,
e
.
getMessage
());
}
return
null
;
}
public
static
String
downloadAndCompressImage
(
String
url
,
String
dstDir
,
float
quality
)
{
String
file
=
downloadFile
(
url
,
dstDir
,
"png"
);
File
f
=
new
File
(
file
);
if
(
f
!=
null
&&
f
.
length
()
>
400_000
)
{
// 500k
String
compressFile
=
StrUtil
.
replace
(
file
,
".png"
,
"_c.png"
);
// ImgUtil.compress(new File(file), new File(compressFile), quality);
try
{
ImageUtils
.
compressPictureByQality
(
new
File
(
file
),
compressFile
,
quality
);
file
=
compressFile
;
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
}
}
return
file
;
}
/**
* 测试方法.
*
* @param args
* @throws Exception
*/
public
static
void
main
(
String
[]
args
)
throws
Exception
{
String
url
=
"https://baidu.com/s?q=xxx&t=2019-11-14 12:00:00"
;
System
.
out
.
println
(
JacksonUtils
.
toJson
(
build
(
url
)));
StringBuffer
sb
=
new
StringBuffer
();
try
{
sb
.
append
(
"http://gcloudtest.gac-toyota.com.cn:8005/GCloudWebService.asmx/SetSalesLeads"
);
Map
<
String
,
String
>
params
=
new
HashMap
<>();
params
.
put
(
"media_code"
,
"d945bca5-04e5-4592-b8a3-0a21768c66d3"
);
params
.
put
(
"INTERFACE_NAME"
,
"Interface_salesleads"
);
params
.
put
(
"JSONSTRING"
,
"[{\"media_code\":\"d945bca5-04e5-4592-b8a3-0a21768c66d3\",\"clue_code\":\"1571635834946\",\"dealer_code\":\"53A10\",\"is_publicorder\":\"2\",\"clue_type\":\"1\",\"modle_code\":\"004038\",\"modle_name\":\"\",\"create_time\":\"2019-11-14 16:55:18\",\"customer_name\":\"xxx\",\"phone\":\"13568905632\",\"mobile\":\"13568905632\"}]"
);
System
.
out
.
println
(
get
(
sb
.
toString
(),
params
));
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
}
/**
* 实现用于主机名验证的基接口。 在握手期间,如果 URL 的主机名和服务器的标识主机名不匹配,则验证机制可以回调此接口的实现程序来确定是否应该允许此连接。
*/
class
MyHostnameVerifier
implements
HostnameVerifier
{
@Override
public
boolean
verify
(
String
hostname
,
SSLSession
session
)
{
if
(
"localhost"
.
equals
(
hostname
))
{
return
true
;
}
else
{
return
false
;
}
}
}
// 证书管理
class
MyX509TrustManager
implements
X509TrustManager
{
@Override
public
X509Certificate
[]
getAcceptedIssuers
()
{
return
null
;
}
@Override
public
void
checkClientTrusted
(
X509Certificate
[]
chain
,
String
authType
)
throws
CertificateException
{
}
@Override
public
void
checkServerTrusted
(
X509Certificate
[]
chain
,
String
authType
)
throws
CertificateException
{
}
}
/**
* https 域名校验
*
* @param url
* @param params
* @return
*/
class
TrustAnyHostnameVerifier
implements
HostnameVerifier
{
@Override
public
boolean
verify
(
String
hostname
,
SSLSession
session
)
{
return
true
;
// 直接返回true
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/ImageUtils.java
0 → 100644
View file @
81f2091
/**
*
*/
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
()
+
2
f
);
bounds
=
graphics
.
getFontMetrics
(
font
).
getStringBounds
(
text
,
graphics
);
}
return
font
.
deriveFont
(
font
.
getSize
()
-
1
f
);
}
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
\ No newline at end of file
platform-charging/src/main/java/cn/com/glsx/charging/util/IpUtil.java
0 → 100644
View file @
81f2091
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
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/JacksonUtils.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.io.IOException
;
import
java.lang.reflect.Type
;
import
java.text.SimpleDateFormat
;
import
java.time.LocalDateTime
;
import
java.time.ZonedDateTime
;
import
java.time.format.DateTimeFormatter
;
import
java.util.ArrayList
;
import
java.util.Date
;
import
java.util.List
;
import
org.apache.commons.codec.binary.Base64
;
import
org.apache.commons.lang3.StringUtils
;
import
com.fasterxml.jackson.annotation.JsonInclude
;
import
com.fasterxml.jackson.core.JsonGenerator
;
import
com.fasterxml.jackson.core.JsonParser
;
import
com.fasterxml.jackson.core.JsonProcessingException
;
import
com.fasterxml.jackson.core.type.TypeReference
;
import
com.fasterxml.jackson.databind.BeanProperty
;
import
com.fasterxml.jackson.databind.DeserializationContext
;
import
com.fasterxml.jackson.databind.DeserializationFeature
;
import
com.fasterxml.jackson.databind.JavaType
;
import
com.fasterxml.jackson.databind.JsonDeserializer
;
import
com.fasterxml.jackson.databind.JsonMappingException
;
import
com.fasterxml.jackson.databind.JsonSerializer
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.fasterxml.jackson.databind.PropertyNamingStrategy
;
import
com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy
;
import
com.fasterxml.jackson.databind.SerializationFeature
;
import
com.fasterxml.jackson.databind.SerializerProvider
;
import
com.fasterxml.jackson.databind.cfg.MapperConfig
;
import
com.fasterxml.jackson.databind.deser.ContextualDeserializer
;
import
com.fasterxml.jackson.databind.deser.std.StdDeserializer
;
import
com.fasterxml.jackson.databind.introspect.AnnotatedField
;
import
com.fasterxml.jackson.databind.introspect.AnnotatedMethod
;
import
com.fasterxml.jackson.databind.module.SimpleModule
;
import
com.fasterxml.jackson.databind.ser.std.StdSerializer
;
import
com.fasterxml.jackson.databind.util.JSONPObject
;
import
cn.hutool.core.date.DatePattern
;
import
lombok.val
;
import
lombok.extern.slf4j.Slf4j
;
import
sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl
;
@SuppressWarnings
(
"restriction"
)
public
class
JacksonUtils
{
// 转换全部字段
public
final
static
JsonMapper
normalMapper
=
JsonMapper
.
buildNormalBinder
();
// 不转换默认值的字段
public
final
static
JsonMapper
nodefaultMapper
=
JsonMapper
.
buildNonDefaultBinder
();
// 不转换空字段
public
final
static
JsonMapper
noemptyMapper
=
JsonMapper
.
buildNonEmptyBinder
();
// 不转换null字段
public
final
static
JsonMapper
nonullMapper
=
JsonMapper
.
buildNonNullBinder
();
// 不转换null字段
public
final
static
JsonMapper
null2emptyMapper
=
JsonMapper
.
buildNull2EmptyBinder
();
// 首字母大写
public
final
static
JsonMapper
downCaseMapper
=
JsonMapper
.
buildDownCaseBinder
();
// 下划线
public
final
static
JsonMapper
snakeMapper
=
JsonMapper
.
buildSnakeCaseBinder
();
// // 下划线+base64 decode
// public final static JsonMapper wxMapper = JsonMapper.buildWxCaseBinder();
public
static
<
T
>
String
toJson
(
T
t
)
{
return
normalMapper
.
toJson
(
t
);
}
public
static
<
T
>
T
fromJson
(
String
json
,
Class
<
T
>
clazz
)
{
return
normalMapper
.
fromJson
(
json
,
clazz
);
}
public
static
<
T
,
S
>
T
fromJson
(
String
json
,
Class
<
T
>
owner
,
Class
<
S
>
subClass
)
{
return
normalMapper
.
fromJson
(
json
,
owner
,
subClass
);
}
/**
* <code>
* List<String> list = JsonUtil.fromJson(json, new TypeReference<ArrayList<String>>() {});
* </code>
*
* @param <T>
* @param json
* @param t
* @return
*/
public
static
<
T
>
T
fromJson
(
String
json
,
TypeReference
<
T
>
t
)
{
return
normalMapper
.
fromJson
(
json
,
t
);
}
public
static
<
T
>
T
convertJsonClazz
(
Object
object
,
Class
<
T
>
clazz
)
{
return
normalMapper
.
convertJsonClazz
(
object
,
clazz
);
}
/**
* 构造函数
*/
private
JacksonUtils
()
{
}
@Slf4j
public
static
class
JsonMapper
{
private
ObjectMapper
mapper
;
protected
JsonMapper
()
{
this
(
JsonInclude
.
Include
.
ALWAYS
);
}
public
JsonMapper
(
JsonInclude
.
Include
include
)
{
mapper
=
new
ObjectMapper
();
// 设置输出时包含属性的风格
mapper
.
setSerializationInclusion
(
include
);
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper
.
disable
(
DeserializationFeature
.
FAIL_ON_UNKNOWN_PROPERTIES
);
// 空的bean不解析
mapper
.
disable
(
SerializationFeature
.
FAIL_ON_EMPTY_BEANS
);
// 设置日期格式
mapper
.
setDateFormat
(
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
));
//
mapper
.
registerModule
(
simpleModule
());
}
/** 创建输出全部属性到Json字符串的Binder. */
public
static
JsonMapper
buildNormalBinder
()
{
return
new
JsonMapper
(
JsonInclude
.
Include
.
ALWAYS
);
}
/** 创建只输出非空属性到Json字符串的Binder. */
public
static
JsonMapper
buildNonNullBinder
()
{
return
new
JsonMapper
(
JsonInclude
.
Include
.
NON_NULL
);
}
public
static
JsonMapper
buildNull2EmptyBinder
()
{
JsonMapper
m
=
new
JsonMapper
(
JsonInclude
.
Include
.
ALWAYS
);
m
.
mapper
.
getSerializerProvider
().
setNullValueSerializer
(
new
JsonSerializer
<
Object
>()
{
@Override
public
void
serialize
(
Object
value
,
JsonGenerator
jgen
,
SerializerProvider
provider
)
throws
IOException
,
JsonProcessingException
{
jgen
.
writeString
(
""
);
}
});
return
m
;
}
/** 创建只输出初始值被改变的属性到Json字符串的Binder. */
public
static
JsonMapper
buildNonDefaultBinder
()
{
return
new
JsonMapper
(
JsonInclude
.
Include
.
NON_DEFAULT
);
}
/** 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Binder */
public
static
JsonMapper
buildNonEmptyBinder
()
{
return
new
JsonMapper
(
JsonInclude
.
Include
.
NON_EMPTY
);
}
/** 首字母大写 */
public
static
JsonMapper
buildDownCaseBinder
()
{
// 首字母默认小写
JsonMapper
mapper
=
new
JsonMapper
(
JsonInclude
.
Include
.
ALWAYS
);
mapper
.
mapper
.
setPropertyNamingStrategy
(
new
JacksonInitialDownCaseStrategy
());
return
mapper
;
}
/** 下划线连接 */
public
static
JsonMapper
buildSnakeCaseBinder
()
{
// 下划线
JsonMapper
mapper
=
new
JsonMapper
(
JsonInclude
.
Include
.
NON_NULL
);
mapper
.
mapper
.
setPropertyNamingStrategy
(
new
SnakeCaseStrategy
());
return
mapper
;
}
// /** 下划线连接+Base64 */
// public static JsonMapper buildWxCaseBinder() {
// // 下划线
// JsonMapper mapper = new JsonMapper(JsonInclude.Include.ALWAYS);
// mapper.mapper.setPropertyNamingStrategy(new SnakeCaseStrategy());
// mapper.mapper.setBase64Variant(Base64Variants.MIME_NO_LINEFEEDS);
// return mapper;
// }
/**
* 反序列化POJO或简单Collection如List<String>. 如果JSON字符串为null或"null"字符串,返回null. 如果JSON字符串为"[]",返回空集合.
* 如需读取集合如List/Map,且不是List<String>这种简单类型时,使用後面的函數.
*/
public
<
T
>
T
fromJson
(
String
jsonString
,
Class
<
T
>
clazz
)
{
if
(
StringUtils
.
isEmpty
(
jsonString
))
{
return
null
;
}
try
{
return
mapper
.
readValue
(
jsonString
,
clazz
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"parse json string error:"
+
jsonString
,
e
);
return
null
;
}
}
public
<
T
>
T
fromJson
(
String
jsonString
,
TypeReference
<
T
>
type
)
{
if
(
StringUtils
.
isEmpty
(
jsonString
))
{
return
null
;
}
try
{
return
mapper
.
readValue
(
jsonString
,
type
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"parse json string error:"
+
jsonString
,
e
);
return
null
;
}
}
public
<
T
,
S
>
T
fromJson
(
String
json
,
Class
<
T
>
owner
,
Class
<
S
>
subClass
)
{
if
(
subClass
==
null
)
{
return
fromJson
(
json
,
owner
);
}
Type
[]
types
=
new
Type
[
1
];
types
[
0
]
=
subClass
;
final
ParameterizedTypeImpl
type
=
ParameterizedTypeImpl
.
make
(
owner
,
types
,
owner
.
getDeclaringClass
());
TypeReference
<
T
>
typeReference
=
new
TypeReference
<
T
>()
{
@Override
public
Type
getType
()
{
return
type
;
}
};
return
fromJson
(
json
,
typeReference
);
}
/**
* 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调. 如果JSON字符串为null或"null"字符串,返回null. 如果JSON字符串为"[]",返回空集合.
*/
@SuppressWarnings
(
"unchecked"
)
public
<
T
>
T
fromJson
(
String
jsonString
,
JavaType
javaType
)
{
if
(
StringUtils
.
isEmpty
(
jsonString
))
{
return
null
;
}
try
{
return
(
T
)
mapper
.
readValue
(
jsonString
,
javaType
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"parse json string error:"
+
jsonString
,
e
);
return
null
;
}
}
/** 構造泛型的Type如List<MyBean>, Map<String,MyBean> */
public
JavaType
createCollectionType
(
Class
<?>
collectionClass
,
Class
<?>...
elementClasses
)
{
return
mapper
.
getTypeFactory
().
constructParametricType
(
collectionClass
,
elementClasses
);
}
/**
* Object可以是POJO,也可以是Collection或数组. 如果对象为null,返回"null". 如果集合为空集合,返回"[]".
*/
public
String
toJson
(
Object
object
)
{
try
{
if
(
object
==
null
)
{
return
null
;
}
return
mapper
.
writeValueAsString
(
object
);
}
catch
(
IOException
e
)
{
log
.
warn
(
"write to json string error:"
+
object
,
e
);
return
null
;
}
}
// 转换类型
public
<
T
>
T
convertJsonClazz
(
Object
object
,
Class
<
T
>
clazz
)
{
String
json
=
toJson
(
object
);
return
fromJson
(
json
,
clazz
);
}
/** 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性. */
@SuppressWarnings
(
"unchecked"
)
public
<
T
>
T
update
(
String
jsonString
,
T
object
)
{
try
{
return
(
T
)
mapper
.
readerForUpdating
(
object
).
readValue
(
jsonString
);
}
catch
(
Exception
e
)
{
log
.
warn
(
"parse json string"
+
jsonString
+
" to object:"
+
object
+
" error."
,
e
);
}
return
null
;
}
/** 輸出JSONP格式數據. */
public
String
toJsonP
(
String
functionName
,
Object
object
)
{
return
toJson
(
new
JSONPObject
(
functionName
,
object
));
}
/** 设定是否使用Enum的toString函數來读写Enum, */
public
void
enableEnumUseToString
()
{
mapper
.
enable
(
SerializationFeature
.
WRITE_ENUMS_USING_TO_STRING
);
mapper
.
enable
(
DeserializationFeature
.
READ_ENUMS_USING_TO_STRING
);
}
}
public
static
SimpleModule
simpleModule
()
{
val
bean
=
new
SimpleModule
();
bean
.
addDeserializer
(
ZonedDateTime
.
class
,
new
JsonDeserializer
<
ZonedDateTime
>()
{
@Override
public
ZonedDateTime
deserialize
(
JsonParser
jsonParser
,
DeserializationContext
deserializationContext
)
throws
IOException
,
JsonProcessingException
{
return
ZonedDateTime
.
parse
(
jsonParser
.
getValueAsString
(),
DateTimeFormatter
.
ISO_ZONED_DATE_TIME
);
}
});
bean
.
addDeserializer
(
LocalDateTime
.
class
,
new
MyLocalDatetimeDeserializer
());
bean
.
addSerializer
(
ZonedDateTime
.
class
,
new
JsonSerializer
<
ZonedDateTime
>()
{
@Override
public
void
serialize
(
ZonedDateTime
zonedDateTime
,
JsonGenerator
jsonGenerator
,
SerializerProvider
serializerProvider
)
throws
IOException
{
jsonGenerator
.
writeString
(
DateTimeFormatter
.
ISO_ZONED_DATE_TIME
.
format
(
zonedDateTime
));
}
});
bean
.
addSerializer
(
LocalDateTime
.
class
,
new
MyLocalDatetimeSerializer
());
return
bean
;
}
@SuppressWarnings
(
"serial"
)
static
class
JacksonInitialDownCaseStrategy
extends
PropertyNamingStrategy
{
@Override
public
String
nameForField
(
@SuppressWarnings
(
"rawtypes"
)
MapperConfig
config
,
AnnotatedField
field
,
String
defaultName
)
{
return
convert
(
defaultName
);
}
@Override
public
String
nameForGetterMethod
(
@SuppressWarnings
(
"rawtypes"
)
MapperConfig
config
,
AnnotatedMethod
method
,
String
defaultName
)
{
return
convert
(
defaultName
);
}
@Override
public
String
nameForSetterMethod
(
@SuppressWarnings
(
"rawtypes"
)
MapperConfig
config
,
AnnotatedMethod
method
,
String
defaultName
)
{
String
a
=
convert
(
defaultName
);
return
a
;
}
public
String
convert
(
String
defaultName
)
{
char
[]
arr
=
defaultName
.
toCharArray
();
if
(
arr
.
length
!=
0
)
{
if
(
Character
.
isLowerCase
(
arr
[
0
]))
{
char
upper
=
Character
.
toUpperCase
(
arr
[
0
]);
arr
[
0
]
=
upper
;
}
}
return
new
StringBuilder
().
append
(
arr
).
toString
();
}
}
@SuppressWarnings
({
"unchecked"
,
"rawtypes"
})
public
static
class
Base64Deserializer
extends
JsonDeserializer
implements
ContextualDeserializer
{
@Override
public
JsonDeserializer
createContextual
(
DeserializationContext
context
,
BeanProperty
property
)
throws
JsonMappingException
{
return
this
;
}
@Override
public
Object
deserialize
(
JsonParser
parser
,
DeserializationContext
context
)
throws
IOException
,
JsonProcessingException
{
String
value
=
parser
.
getValueAsString
();
try
{
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
;
}
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
value
;
}
}
@SuppressWarnings
({
"unchecked"
,
"rawtypes"
})
public
static
class
GBKBase64Deserializer
extends
JsonDeserializer
implements
ContextualDeserializer
{
@Override
public
JsonDeserializer
createContextual
(
DeserializationContext
context
,
BeanProperty
property
)
throws
JsonMappingException
{
return
this
;
}
@Override
public
Object
deserialize
(
JsonParser
parser
,
DeserializationContext
context
)
throws
IOException
,
JsonProcessingException
{
String
value
=
parser
.
getValueAsString
();
try
{
if
(
Base64
.
isBase64
(
value
))
{
// TODO 判断是否切换编码格式
// value = new String(Base64.decode(value.getBytes()), "GBK");
value
=
new
String
(
org
.
apache
.
commons
.
codec
.
binary
.
Base64
.
decodeBase64
(
value
),
"GBK"
);
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
value
;
}
}
@SuppressWarnings
({
"serial"
})
public
static
class
LongToDateDeserializer
extends
StdDeserializer
<
Date
>
{
public
LongToDateDeserializer
()
{
this
(
StdDeserializer
.
class
);
}
protected
LongToDateDeserializer
(
Class
<?>
c
)
{
super
(
c
);
}
static
long
MIN
=
DateUtils
.
str2Timestamp
(
"1980-01-01 00:00:00"
).
getTime
();
@Override
public
Date
deserialize
(
JsonParser
jsonParser
,
DeserializationContext
deserializationContext
)
throws
IOException
{
// SimpleDateFormat formatter = new SimpleDateFormat(DateUtils.FORMAT_DATETIME);
long
ts
=
jsonParser
.
getLongValue
();
if
(
ts
<
MIN
)
{
ts
=
ts
*
1000L
;
}
return
new
Date
(
ts
);
// change the implementation of deserialise method if date format is needed.
}
}
public
static
class
JsonDateSerializer
extends
JsonSerializer
<
Date
>
{
@Override
public
void
serialize
(
Date
date
,
JsonGenerator
arg1
,
SerializerProvider
arg2
)
throws
IOException
,
JsonProcessingException
{
arg1
.
writeString
(
DateUtils
.
datetimeToStr
(
date
));
}
}
public
static
class
JsonDateDeserializer
extends
JsonDeserializer
<
Date
>
{
@Override
public
Date
deserialize
(
JsonParser
p
,
DeserializationContext
ctxt
)
throws
IOException
,
JsonProcessingException
{
String
str
=
p
.
getText
();
return
DateUtils
.
strToDate
(
str
);
}
}
public
static
class
MyLocalDatetimeDeserializer
extends
StdDeserializer
<
LocalDateTime
>
{
private
static
final
long
serialVersionUID
=
1L
;
protected
MyLocalDatetimeDeserializer
()
{
super
(
LocalDateTime
.
class
);
}
@Override
public
LocalDateTime
deserialize
(
JsonParser
jp
,
DeserializationContext
ctxt
)
throws
IOException
,
JsonProcessingException
{
return
LocalDateTime
.
parse
(
jp
.
readValueAs
(
String
.
class
),
DateTimeFormatter
.
ofPattern
(
DatePattern
.
NORM_DATETIME_PATTERN
));
}
}
public
static
class
MyLocalDatetimeSerializer
extends
StdSerializer
<
LocalDateTime
>
{
private
static
final
long
serialVersionUID
=
1L
;
public
MyLocalDatetimeSerializer
()
{
super
(
LocalDateTime
.
class
);
}
@Override
public
void
serialize
(
LocalDateTime
value
,
JsonGenerator
gen
,
SerializerProvider
sp
)
throws
IOException
,
JsonProcessingException
{
gen
.
writeString
(
value
.
format
(
DateTimeFormatter
.
ofPattern
(
DatePattern
.
NORM_DATETIME_PATTERN
)));
}
}
// @SuppressWarnings({ "rawtypes" })
// public static class Base64Serializer extends JsonSerializer implements ContextualSerializer {
//
// @Override
// public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
// return this;
// }
//
// @Override
// public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
// if (!Base64.isBase64Pattern((String) value)) {
// value = Base64.decodeStr((String) value);
// }
// gen.writeObject(value);
// }
//
// }
@SuppressWarnings
(
"unchecked"
)
public
static
void
main
(
String
[]
args
)
{
String
json
=
"[\"A\",\"B\"]"
;
List
<
String
>
list
=
JacksonUtils
.
fromJson
(
json
,
ArrayList
.
class
);
System
.
out
.
println
(
list
.
get
(
0
));
list
=
JacksonUtils
.
fromJson
(
json
,
new
TypeReference
<
ArrayList
<
String
>>()
{
});
System
.
out
.
println
(
list
.
get
(
0
));
System
.
out
.
println
(
DateUtils
.
str2Timestamp
(
"1980-01-01 00:00:00"
).
getTime
());
System
.
out
.
println
(
new
Date
(
10000000000000L
));
}
}
\ No newline at end of file
\ No newline at end of file
platform-charging/src/main/java/cn/com/glsx/charging/util/LoginUtil.java
0 → 100644
View file @
81f2091
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;
// }
}
platform-charging/src/main/java/cn/com/glsx/charging/util/MapUtils.java
0 → 100644
View file @
81f2091
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
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/Md5Utils.java
0 → 100644
View file @
81f2091
/*
* @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
);
}
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/Pair.java
0 → 100644
View file @
81f2091
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
\ No newline at end of file
platform-charging/src/main/java/cn/com/glsx/charging/util/PasswordUtil.java
0 → 100644
View file @
81f2091
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"
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/PluralCache.java
0 → 100644
View file @
81f2091
/**
*
*/
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
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/PropertiesUtils.java
0 → 100644
View file @
81f2091
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"
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/RedisCacheUtil.java
0 → 100644
View file @
81f2091
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
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/RedisKey.java
0 → 100644
View file @
81f2091
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"
;
}
platform-charging/src/main/java/cn/com/glsx/charging/util/SnowFlakeIdUtils.java
0 → 100644
View file @
81f2091
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
));
}
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/SnowFlakeUtil.java
0 → 100644
View file @
81f2091
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
\ No newline at end of file
platform-charging/src/main/java/cn/com/glsx/charging/util/SpringContextUtil.java
0 → 100644
View file @
81f2091
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
\ No newline at end of file
platform-charging/src/main/java/cn/com/glsx/charging/util/StorageDB.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
/**
* @author liujixiang
* @date 2018-11-08
*/
public
class
StorageDB
{
}
platform-charging/src/main/java/cn/com/glsx/charging/util/StrUtils.java
0 → 100644
View file @
81f2091
/**
*
*/
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/SystemUtils.java
0 → 100644
View file @
81f2091
/*
* @Copyright: 2014~2018 www.yyfax.com Inc. All rights reserved.
*/
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.io.File
;
import
java.io.IOException
;
import
java.lang.management.ManagementFactory
;
import
java.lang.management.RuntimeMXBean
;
import
java.net.Inet4Address
;
import
java.net.InetAddress
;
import
java.net.NetworkInterface
;
import
java.net.Socket
;
import
java.net.URL
;
import
java.sql.Timestamp
;
import
java.util.ArrayList
;
import
java.util.Date
;
import
java.util.Enumeration
;
import
java.util.List
;
import
java.util.Map.Entry
;
import
java.util.Properties
;
import
org.apache.commons.lang3.StringUtils
;
import
lombok.extern.slf4j.Slf4j
;
/**
* @author jiangmy
* @date 2018年1月15日 下午4:57:52
* @since 1.0.0
*/
@Slf4j
public
class
SystemUtils
{
/**
* @return 当前Jvm启动的毫秒数
*/
public
static
long
getJvmUptime
()
{
RuntimeMXBean
rb
=
ManagementFactory
.
getRuntimeMXBean
();
return
rb
.
getUptime
();
}
/**
* @return 进程ID
*/
public
static
short
getJvmPid
()
{
String
processName
=
java
.
lang
.
management
.
ManagementFactory
.
getRuntimeMXBean
().
getName
();
return
Long
.
valueOf
(
processName
.
split
(
"@"
)[
0
]).
shortValue
();
}
/**
* @return 当前Jvm启动的时间
*/
public
static
Date
getJvmStarttime
()
{
RuntimeMXBean
rb
=
ManagementFactory
.
getRuntimeMXBean
();
return
new
Timestamp
(
rb
.
getStartTime
());
}
/**
* @return Java版本
*/
public
static
String
getJavaVersion
()
{
return
System
.
getProperty
(
"java.version"
);
}
public
static
String
getJvmName
()
{
return
System
.
getProperty
(
"java.vm.name"
);
}
public
static
String
getLineSeparator
()
{
return
System
.
getProperty
(
"line.separator"
);
}
public
static
String
getFileEncoding
()
{
return
System
.
getProperty
(
"file.encoding"
);
}
/**
* @return Java_home版本
*/
public
static
String
getJavaHome
()
{
return
System
.
getProperty
(
"java.home"
);
}
/**
* @return 用户临时目录
*/
public
static
String
getUserHome
()
{
return
System
.
getProperty
(
"user.home"
);
}
public
static
String
getUserName
()
{
return
System
.
getProperty
(
"user.name"
);
}
public
static
String
getUserLanguage
()
{
return
System
.
getProperty
(
"user.language"
);
}
public
static
String
getUserDir
()
{
return
System
.
getProperty
(
"user.dir"
);
}
/**
* @return tmp_dir版本
*/
public
static
String
getJavaIoTmpDir
()
{
return
System
.
getProperty
(
"java.io.tmpdir"
);
}
/**
* @return 文件分隔符
*/
public
static
String
getFileSeparator
()
{
return
System
.
getProperty
(
"file.separator"
);
}
public
static
String
getOsName
()
{
return
System
.
getProperty
(
"os.name"
);
}
public
static
String
getOsArch
()
{
return
System
.
getProperty
(
"os.arch"
);
}
public
static
String
getJvmArch
()
{
return
System
.
getProperty
(
"sun.arch.data.model"
);
}
public
static
String
getOsVersion
()
{
return
System
.
getProperty
(
"os.version"
);
}
/**
* @return Java版本
*/
public
static
float
getJavaSpecificationVersion
()
{
return
Float
.
parseFloat
(
System
.
getProperty
(
"java.specification.version"
));
}
/**
* @return CPU核数
*/
public
static
int
getAvaliableProcessors
()
{
return
Runtime
.
getRuntime
().
availableProcessors
();
}
/**
* @return 配置的内存中的空闲内存
*/
public
static
long
freeMemory
()
{
return
Runtime
.
getRuntime
().
freeMemory
();
}
/**
* @return 配置的可使用内存
*/
public
static
long
maxMemory
()
{
return
Runtime
.
getRuntime
().
maxMemory
();
}
/**
* @return 当前已使用内存
*/
public
static
long
totalMemory
()
{
return
Runtime
.
getRuntime
().
totalMemory
();
}
/**
* @param resource resource所在目录
* @return
*/
public
static
String
getResourcePath
(
String
resource
)
{
URL
url
=
SystemUtils
.
class
.
getClassLoader
().
getResource
(
resource
);
if
(
url
==
null
)
{
log
.
warn
(
"Failed load properties, file["
+
resource
+
"] not exists, please check it !!!!!!!!!"
);
return
null
;
}
return
url
.
getPath
();
}
/**
* @return 分区根目录
*/
public
static
String
getPartitionRoot
()
{
return
new
File
(
"/"
).
getAbsolutePath
();
}
public
static
String
getProjectBase
()
{
return
(
new
File
(
""
)).
getAbsolutePath
();
}
public
static
String
getProjectFile
(
String
filePath
)
{
String
projectFile
=
SystemUtils
.
getProjectBase
()
+
"/src/main/resources/"
+
filePath
;
File
file
=
new
File
(
projectFile
);
if
(!
file
.
exists
())
{
projectFile
=
SystemUtils
.
getResourcePath
(
filePath
);
if
(
projectFile
!=
null
)
{
file
=
new
File
(
projectFile
);
}
}
if
(!
file
.
exists
())
{
log
.
warn
(
"没找到文件:{} -> {}"
,
filePath
,
file
.
getPath
());
return
null
;
}
return
file
.
getPath
();
}
public
static
String
getCatalinaHome
()
{
return
System
.
getenv
(
"catalina.home"
);
}
/**
* @return classpath根目录
*/
public
static
String
getClasspathBase
()
{
return
SystemUtils
.
class
.
getResource
(
"/"
).
getPath
();
}
/**
* @param claz
* @return 该class所在的目录
*/
public
static
String
getClasspath
(
Class
<?>
claz
)
{
return
claz
.
getResource
(
""
).
getPath
();
}
public
static
void
print
()
{
Properties
properties
=
System
.
getProperties
();
for
(
Entry
<
Object
,
Object
>
entry
:
properties
.
entrySet
())
{
log
.
info
(
entry
.
getKey
()
+
" = "
+
entry
.
getValue
());
}
}
/***
* true:already in using false:not using
*/
public
static
boolean
isPortUsing
(
int
port
)
{
try
{
new
Socket
(
InetAddress
.
getLocalHost
(),
port
).
close
();
return
true
;
}
catch
(
IOException
e
)
{
}
return
false
;
}
/**
* 获取本机IP
*/
public
static
List
<
String
>
getLocalIPList
()
{
try
{
List
<
String
>
list
=
new
ArrayList
<
String
>();
Enumeration
<
NetworkInterface
>
allNetInterfaces
=
NetworkInterface
.
getNetworkInterfaces
();
InetAddress
ip
=
null
;
while
(
allNetInterfaces
.
hasMoreElements
())
{
NetworkInterface
netInterface
=
allNetInterfaces
.
nextElement
();
Enumeration
<
InetAddress
>
addresses
=
netInterface
.
getInetAddresses
();
while
(
addresses
.
hasMoreElements
())
{
ip
=
addresses
.
nextElement
();
if
(
ip
!=
null
&&
ip
instanceof
Inet4Address
)
{
list
.
add
(
ip
.
getHostAddress
());
}
}
}
return
list
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
public
static
String
getLocalIP
()
{
List
<
String
>
list
=
getLocalIPList
();
return
list
==
null
||
list
.
isEmpty
()
?
null
:
list
.
get
(
list
.
size
()
-
1
);
}
public
static
String
OS
=
getOsName
();
public
static
EPlatform
PLATFORM
=
EPlatform
.
fromOS
(
OS
);
public
static
boolean
isLinux
()
{
return
PLATFORM
==
EPlatform
.
Linux
;
}
public
static
boolean
isMacOS
()
{
return
PLATFORM
==
EPlatform
.
Mac_OS
;
}
public
static
boolean
isMacOSX
()
{
return
PLATFORM
==
EPlatform
.
Mac_OS_X
;
}
public
static
boolean
isWindows
()
{
return
PLATFORM
==
EPlatform
.
Windows
;
}
public
static
boolean
isSolaris
()
{
return
PLATFORM
==
EPlatform
.
Solaris
;
}
/**
* 平台
*
* @author isea533
*/
public
enum
EPlatform
{
Any
(
"any"
),
Linux
(
"Linux"
),
Mac_OS
(
"Mac OS"
),
Mac_OS_X
(
"Mac OS X"
),
Windows
(
"Windows"
),
OS2
(
"OS/2"
),
Solaris
(
"Solaris"
),
SunOS
(
"SunOS"
),
MPEiX
(
"MPE/iX"
),
HP_UX
(
"HP-UX"
),
AIX
(
"AIX"
),
OS390
(
"OS/390"
),
FreeBSD
(
"FreeBSD"
),
Irix
(
"Irix"
),
Digital_Unix
(
"Digital Unix"
),
NetWare_411
(
"NetWare"
),
OSF1
(
"OSF1"
),
OpenVMS
(
"OpenVMS"
),
Others
(
"Others"
);
private
EPlatform
(
String
desc
)
{
this
.
description
=
desc
;
}
@Override
public
String
toString
()
{
return
description
;
}
private
String
description
;
public
static
EPlatform
fromOS
(
String
os
)
{
for
(
EPlatform
e
:
values
())
{
if
(
StringUtils
.
containsIgnoreCase
(
os
,
e
.
description
))
{
return
e
;
}
}
return
Windows
;
}
}
private
SystemUtils
()
{
}
public
static
void
main
(
String
[]
args
)
{
System
.
out
.
println
(
getOsName
());
print
();
System
.
out
.
println
(
isWindows
());
System
.
out
.
println
(
getClasspathBase
());
System
.
out
.
println
(
getPartitionRoot
());
System
.
out
.
println
(
getProjectBase
());
System
.
out
.
println
(
getResourcePath
(
"org/glsx/wxwork/utils/AudioUtils.class"
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/Task.java
0 → 100644
View file @
81f2091
/**
* Task.java
*/
package
cn
.
com
.
glsx
.
charging
.
util
;
/**
* 任务接口
*
* @author kome.Jiangmy
* @version 1.0
* @created 2012-9-25 上午9:30:39
*/
public
interface
Task
{
/**
* task processore method, task control thread execute it.
*
* @throws Exception
*/
void
execute
()
throws
Exception
;
}
platform-charging/src/main/java/cn/com/glsx/charging/util/TaskExecutor.java
0 → 100644
View file @
81f2091
/**
* TaskExecutor.java
*/
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.util.ArrayList
;
import
java.util.Date
;
import
java.util.List
;
import
java.util.concurrent.ArrayBlockingQueue
;
import
java.util.concurrent.ExecutorService
;
import
java.util.concurrent.Executors
;
import
java.util.concurrent.Future
;
import
java.util.concurrent.ScheduledFuture
;
import
java.util.concurrent.ScheduledThreadPoolExecutor
;
import
java.util.concurrent.ThreadPoolExecutor
;
import
java.util.concurrent.TimeUnit
;
/**
* 线程池+定时器封装
*
* @author kome.Jiangmy
* @version 1.0
* @created 2012-9-28 下午1:43:06
*/
public
class
TaskExecutor
{
static
{
/**
* java hook method, by java VM exist before execute.
*/
Runtime
.
getRuntime
().
addShutdownHook
(
new
Thread
()
{
@Override
public
void
run
()
{
shutdown
();
}
});
}
// private static final AtomicInteger poolSize = new AtomicInteger();
// private static final Logger logger = Logger.getLogger(TaskExecutor.class);
/**
* 创建一个可根据需要创建新线程的线程池,但是在以前构造的线程可用时将重用它们。对于执行很多短期异步任务的程序而言,这些线程池通常可提高程序性能。
*/
private
static
final
ThreadPoolExecutor
cachedPool
=
new
ThreadPoolExecutor
(
16
,
32
,
60L
,
TimeUnit
.
SECONDS
,
new
ArrayBlockingQueue
<
Runnable
>(
50000
));
/**
* 定时任务
*/
private
static
final
ScheduledThreadPoolExecutor
scheduledPool
=
(
ScheduledThreadPoolExecutor
)
Executors
.
newScheduledThreadPool
(
20
);
private
static
Runnable
taskToRunnable
(
final
Task
task
,
final
ExecutorService
cachedPool
)
{
return
new
Runnable
()
{
@Override
public
void
run
()
{
try
{
if
(
cachedPool
.
isShutdown
()
||
cachedPool
.
isTerminated
()
||
task
==
null
)
{
return
;
}
task
.
execute
();
}
catch
(
InterruptedException
e
)
{
Thread
.
currentThread
().
interrupt
();
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
};
}
/**
* 执行一次
*/
public
static
Future
<?>
addTask
(
final
Task
task
)
{
Runnable
runnable
=
taskToRunnable
(
task
,
cachedPool
);
return
cachedPool
.
submit
(
runnable
);
}
public
static
Future
<?>
addDelayTask
(
final
Task
task
,
final
long
delay
)
{
Runnable
runnable
=
taskToRunnable
(
task
,
scheduledPool
);
return
scheduledPool
.
schedule
(
runnable
,
delay
,
TimeUnit
.
MILLISECONDS
);
}
public
static
<
T
>
CallbackTask
<
T
>
addCallback
(
final
CallbackTask
<
T
>
task
)
{
addTask
(
task
);
return
task
;
}
/**
* 重复执行
*/
public
static
ScheduledFuture
<?>
addTask
(
final
Task
task
,
final
long
repeatIntervalTimeMillis
)
{
Runnable
runnable
=
taskToRunnable
(
task
,
scheduledPool
);
return
scheduledPool
.
scheduleAtFixedRate
(
runnable
,
0
,
repeatIntervalTimeMillis
,
TimeUnit
.
MILLISECONDS
);
}
public
static
ScheduledFuture
<?>
addTask
(
final
Task
task
,
final
long
delay
,
final
long
repeatIntervalTimeMillis
)
{
Runnable
runnable
=
taskToRunnable
(
task
,
scheduledPool
);
return
scheduledPool
.
scheduleAtFixedRate
(
runnable
,
delay
,
repeatIntervalTimeMillis
,
TimeUnit
.
MILLISECONDS
);
}
public
static
boolean
cancelTask
(
Future
<?>
future
,
boolean
mayInterruptIfRunning
)
{
return
future
.
cancel
(
mayInterruptIfRunning
);
}
/**
* 定时执行
*/
public
static
ScheduledFuture
<?>
addTask
(
final
Task
task
,
Date
executeTime
)
{
if
(
executeTime
==
null
||
executeTime
.
before
(
new
Date
()))
{
throw
new
IllegalArgumentException
();
}
Runnable
runnable
=
taskToRunnable
(
task
,
scheduledPool
);
long
delay
=
executeTime
.
getTime
()
-
System
.
currentTimeMillis
();
return
scheduledPool
.
schedule
(
runnable
,
delay
,
TimeUnit
.
MILLISECONDS
);
}
/**
* shutdown taskExecutor
*/
public
static
void
shutdown
()
{
try
{
cachedPool
.
shutdown
();
scheduledPool
.
shutdown
();
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
}
public
static
void
main
(
String
[]
args
)
throws
Exception
{
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
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/TimeStackUtils.java
0 → 100644
View file @
81f2091
/*
* @Copyright: 2014~2018 www.yyfax.com Inc. All rights reserved.
*/
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.util.Stack
;
import
org.slf4j.Logger
;
import
lombok.extern.slf4j.Slf4j
;
/**
* 用于计时
*
* @author jiangmy
* @date 2018年1月15日 下午4:58:02
* @since 1.0.0
*/
@Slf4j
public
class
TimeStackUtils
{
private
static
ThreadLocal
<
Stack
<
Long
>>
times
=
new
ThreadLocal
<
Stack
<
Long
>>()
{
@Override
protected
java
.
util
.
Stack
<
Long
>
initialValue
()
{
return
new
Stack
<
Long
>();
}
};
public
static
void
begin
()
{
Stack
<
Long
>
stack
=
times
.
get
();
if
(
stack
.
size
()
>
30
)
{
// 检测是否有遗漏
log
.
warn
(
"栈大小超过30,请检查是否有地方只begin()没有end()!!!"
);
for
(
int
i
=
0
;
i
<
10
;
i
++)
{
stack
.
remove
(
0
);
}
}
stack
.
push
(
System
.
currentTimeMillis
());
}
public
static
long
end
()
{
Stack
<
Long
>
stack
=
times
.
get
();
if
(
stack
.
isEmpty
())
{
log
.
warn
(
"没有begin()操作,计时失败!!!"
);
stack
.
push
(
System
.
currentTimeMillis
());
return
0
;
}
long
begin
=
stack
.
pop
();
if
(
stack
.
size
()
==
0
)
{
stack
.
push
(
System
.
currentTimeMillis
());
}
long
time
=
System
.
currentTimeMillis
()
-
begin
;
return
time
;
}
public
static
void
clear
()
{
Stack
<
Long
>
stack
=
times
.
get
();
if
(!
stack
.
isEmpty
())
{
stack
.
clear
();
}
}
/**
* 打印执行时间日志
*
* @param warnMilllis
* @param message
* @param params
* @author jiangmy
* @date 2010-07-22 下午5:50:31
*/
public
static
void
endAndLog
(
long
warnMilllis
,
String
message
,
Object
...
params
)
{
endAndLog
(
log
,
warnMilllis
,
message
,
params
);
}
/**
* 打印执行时间日志
*
* @param log
* @param warnMilllis
* @param message
* @param params
* @author jiangmy
* @date 2010-07-22 下午5:50:31
*/
public
static
void
endAndLog
(
Logger
log
,
long
warnMilllis
,
String
message
,
Object
...
params
)
{
long
time
=
end
();
if
(
time
>=
warnMilllis
)
{
log
.
warn
(
message
+
"【耗时:"
+
time
+
"ms】"
,
params
);
}
else
{
log
.
info
(
message
+
" 【耗时:"
+
time
+
"ms】"
,
params
);
}
}
/**
* sleep等待,单位毫秒.
*
* @param millis 毫秒
*/
public
static
void
sleep
(
long
millis
)
{
try
{
Thread
.
sleep
(
millis
);
}
catch
(
InterruptedException
e
)
{
// NOSONAR
}
}
public
static
void
main
(
String
[]
args
)
{
begin
();
sleep
(
30
);
begin
();
sleep
(
30
);
endAndLog
(
100
,
"测试计时:{}"
,
"哈哈"
);
sleep
(
300
);
endAndLog
(
100
,
"测试计时"
);
}
private
TimeStackUtils
()
{
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/TimeUtils.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.time.LocalDateTime
;
import
java.time.format.DateTimeFormatter
;
public
class
TimeUtils
{
public
static
String
getNowTime
(
String
pattern
)
{
return
LocalDateTime
.
now
().
format
(
DateTimeFormatter
.
ofPattern
(
pattern
));
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/TokenUtil.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
/**
* @author liujixiang
* @date 2018-11-08
*/
public
class
TokenUtil
{
/**
* 生成token
*
* @return
*/
public
static
String
generateXAuthToken
()
{
String
token
=
"x-auth-token:"
+
UUIDUtil
.
getUUID
();
return
token
;
}
/**
* 生成token
*
* @return
*/
public
static
String
generateFirstLoginRestPwdToken
()
{
String
token
=
"first-login-rest-pwd-token:"
+
UUIDUtil
.
getUUID
();
return
token
;
}
/**
* 生成验证码token
*
* @return
*/
public
static
String
generateVerificationCodeToken
()
{
String
token
=
"verification-code-token:"
+
UUIDUtil
.
getUUID
();
return
token
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/TypeConvertUtil.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.math.BigDecimal
;
import
java.sql.Date
;
import
java.sql.Time
;
import
java.sql.Timestamp
;
import
java.text.DateFormat
;
import
java.text.NumberFormat
;
import
java.text.ParseException
;
import
java.text.SimpleDateFormat
;
import
java.util.Locale
;
import
cn.hutool.core.date.DateUtil
;
/**
* <b>类型转换工具类</b>
*
* @author OSWorks-XC
*/
public
class
TypeConvertUtil
{
/**
* 类型转换实现
*
* @param obj
* @param type
* @param format
* @return @
*/
@SuppressWarnings
(
"unused"
)
public
static
Object
convert
(
Object
obj
,
String
type
,
String
format
)
{
Locale
locale
=
new
Locale
(
"zh"
,
"CN"
,
""
);
if
(
obj
==
null
)
{
return
null
;
}
if
(
obj
.
getClass
().
getName
().
equals
(
type
))
{
return
obj
;
}
if
(
"Object"
.
equals
(
type
)
||
"java.lang.Object"
.
equals
(
type
))
{
return
obj
;
}
String
fromType
=
null
;
if
(
obj
instanceof
String
)
{
fromType
=
"String"
;
String
str
=
(
String
)
obj
;
if
(
"String"
.
equals
(
type
)
||
"java.lang.String"
.
equals
(
type
))
{
return
obj
;
}
if
(
str
.
length
()
==
0
)
{
return
null
;
}
if
(
"Boolean"
.
equals
(
type
)
||
"java.lang.Boolean"
.
equals
(
type
))
{
Boolean
value
=
null
;
if
(
str
.
equalsIgnoreCase
(
"TRUE"
))
{
value
=
true
;
}
else
{
value
=
false
;
}
return
value
;
}
if
(
"Byte"
.
equals
(
type
)
||
"java.lang.Byte"
.
equals
(
type
))
{
try
{
NumberFormat
nf
=
getNf
(
locale
);
nf
.
setMaximumFractionDigits
(
0
);
Number
tempNum
=
nf
.
parse
(
str
);
return
Byte
.
valueOf
(
tempNum
.
byteValue
());
}
catch
(
ParseException
e
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
if
(
"Double"
.
equals
(
type
)
||
"java.lang.Double"
.
equals
(
type
))
{
try
{
Number
tempNum
=
getNf
(
locale
).
parse
(
str
);
return
new
Double
(
tempNum
.
doubleValue
());
}
catch
(
ParseException
e
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
if
(
"BigDecimal"
.
equals
(
type
)
||
"java.math.BigDecimal"
.
equals
(
type
))
{
try
{
BigDecimal
retBig
=
new
BigDecimal
(
str
);
int
iscale
=
str
.
indexOf
(
"."
);
int
keylen
=
str
.
length
();
if
(
iscale
>
-
1
)
{
iscale
=
keylen
-
(
iscale
+
1
);
return
retBig
.
setScale
(
iscale
,
5
);
}
else
{
return
retBig
.
setScale
(
0
,
5
);
}
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
if
(
"Float"
.
equals
(
type
)
||
"java.lang.Float"
.
equals
(
type
))
{
try
{
Number
tempNum
=
getNf
(
locale
).
parse
(
str
);
return
Float
.
valueOf
(
tempNum
.
floatValue
());
}
catch
(
ParseException
e
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
if
(
"Long"
.
equals
(
type
)
||
"java.lang.Long"
.
equals
(
type
))
{
try
{
NumberFormat
nf
=
getNf
(
locale
);
nf
.
setMaximumFractionDigits
(
0
);
Number
tempNum
=
nf
.
parse
(
str
);
return
Long
.
valueOf
(
tempNum
.
longValue
());
}
catch
(
ParseException
e
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
if
(
"Integer"
.
equals
(
type
)
||
"java.lang.Integer"
.
equals
(
type
))
{
try
{
NumberFormat
nf
=
getNf
(
locale
);
nf
.
setMaximumFractionDigits
(
0
);
Number
tempNum
=
nf
.
parse
(
str
);
return
Integer
.
valueOf
(
tempNum
.
intValue
());
}
catch
(
ParseException
e
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
if
(
"Date"
.
equals
(
type
)
||
"java.sql.Date"
.
equals
(
type
))
{
if
(
format
==
null
||
format
.
length
()
==
0
)
{
try
{
return
Date
.
valueOf
(
str
);
}
catch
(
Exception
e
)
{
try
{
DateFormat
df
=
null
;
if
(
locale
!=
null
)
{
df
=
DateFormat
.
getDateInstance
(
3
,
locale
);
}
else
{
df
=
DateFormat
.
getDateInstance
(
3
);
}
java
.
util
.
Date
fieldDate
=
df
.
parse
(
str
);
return
new
Date
(
fieldDate
.
getTime
());
}
catch
(
ParseException
e1
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
}
try
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
format
);
java
.
util
.
Date
fieldDate
=
sdf
.
parse
(
str
);
return
new
Date
(
fieldDate
.
getTime
());
}
catch
(
ParseException
e
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
if
(
"Date"
.
equals
(
type
)
||
"java.util.Date"
.
equals
(
type
))
{
if
(
format
==
null
||
format
.
length
()
==
0
)
{
try
{
return
DateUtil
.
parse
(
str
);
}
catch
(
Exception
e
)
{
try
{
DateFormat
df
=
null
;
if
(
locale
!=
null
)
{
df
=
DateFormat
.
getDateInstance
(
3
,
locale
);
}
else
{
df
=
DateFormat
.
getDateInstance
(
3
);
}
java
.
util
.
Date
fieldDate
=
df
.
parse
(
str
);
return
new
Date
(
fieldDate
.
getTime
());
}
catch
(
ParseException
e1
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
}
try
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
format
);
java
.
util
.
Date
fieldDate
=
sdf
.
parse
(
str
);
return
fieldDate
;
}
catch
(
ParseException
e
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
if
(
"Timestamp"
.
equals
(
type
)
||
"java.sql.Timestamp"
.
equals
(
type
))
{
if
(
str
.
length
()
==
10
)
{
str
=
str
+
" 00:00:00"
;
}
if
(
format
==
null
||
format
.
length
()
==
0
)
{
try
{
return
Timestamp
.
valueOf
(
str
);
}
catch
(
Exception
e
)
{
try
{
DateFormat
df
=
null
;
if
(
locale
!=
null
)
{
df
=
DateFormat
.
getDateTimeInstance
(
3
,
3
,
locale
);
}
else
{
df
=
DateFormat
.
getDateTimeInstance
(
3
,
3
);
}
java
.
util
.
Date
fieldDate
=
df
.
parse
(
str
);
return
new
Timestamp
(
fieldDate
.
getTime
());
}
catch
(
ParseException
e1
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
}
try
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
format
);
java
.
util
.
Date
fieldDate
=
sdf
.
parse
(
str
);
return
new
Timestamp
(
fieldDate
.
getTime
());
}
catch
(
ParseException
e
)
{
throw
new
RuntimeException
(
"Could not convert "
+
str
+
" to "
+
type
+
". "
,
e
);
}
}
else
{
throw
new
RuntimeException
(
"Conversion from ["
+
fromType
+
"] to ["
+
type
+
"] not currently supported"
);
}
}
if
(
obj
instanceof
BigDecimal
)
{
fromType
=
"BigDecimal"
;
BigDecimal
bigD
=
(
BigDecimal
)
obj
;
if
(
"String"
.
equals
(
type
))
{
return
getNf
(
locale
).
format
(
bigD
.
doubleValue
());
}
if
(
"BigDecimal"
.
equals
(
type
)
||
"java.math.BigDecimal"
.
equals
(
type
))
{
return
obj
;
}
if
(
"Double"
.
equals
(
type
))
{
return
Double
.
valueOf
(
bigD
.
doubleValue
());
}
if
(
"Float"
.
equals
(
type
))
{
return
Float
.
valueOf
(
bigD
.
floatValue
());
}
if
(
"Long"
.
equals
(
type
))
{
return
Long
.
valueOf
(
Math
.
round
(
bigD
.
doubleValue
()));
}
if
(
"Integer"
.
equals
(
type
))
{
return
Integer
.
valueOf
((
int
)
Math
.
round
(
bigD
.
doubleValue
()));
}
else
{
throw
new
RuntimeException
(
"Conversion from "
+
fromType
+
" to "
+
type
+
" not currently supported"
);
}
}
if
(
obj
instanceof
Double
)
{
fromType
=
"Double"
;
Double
dbl
=
(
Double
)
obj
;
if
(
"String"
.
equals
(
type
)
||
"java.lang.String"
.
equals
(
type
))
{
return
getNf
(
locale
).
format
(
dbl
.
doubleValue
());
}
if
(
"Double"
.
equals
(
type
)
||
"java.lang.Double"
.
equals
(
type
))
{
return
obj
;
}
if
(
"Float"
.
equals
(
type
)
||
"java.lang.Float"
.
equals
(
type
))
{
return
Float
.
valueOf
(
dbl
.
floatValue
());
}
if
(
"Long"
.
equals
(
type
)
||
"java.lang.Long"
.
equals
(
type
))
{
return
Long
.
valueOf
(
Math
.
round
(
dbl
.
doubleValue
()));
}
if
(
"Integer"
.
equals
(
type
)
||
"java.lang.Integer"
.
equals
(
type
))
{
return
Integer
.
valueOf
((
int
)
Math
.
round
(
dbl
.
doubleValue
()));
}
if
(
"BigDecimal"
.
equals
(
type
)
||
"java.math.BigDecimal"
.
equals
(
type
))
{
return
new
BigDecimal
(
dbl
.
toString
());
}
else
{
throw
new
RuntimeException
(
"Conversion from "
+
fromType
+
" to "
+
type
+
" not currently supported"
);
}
}
if
(
obj
instanceof
Float
)
{
fromType
=
"Float"
;
Float
flt
=
(
Float
)
obj
;
if
(
"String"
.
equals
(
type
))
{
return
getNf
(
locale
).
format
(
flt
.
doubleValue
());
}
if
(
"BigDecimal"
.
equals
(
type
)
||
"java.math.BigDecimal"
.
equals
(
type
))
{
return
new
BigDecimal
(
flt
.
doubleValue
());
}
if
(
"Double"
.
equals
(
type
))
{
return
Double
.
valueOf
(
flt
.
doubleValue
());
}
if
(
"Float"
.
equals
(
type
))
{
return
obj
;
}
if
(
"Long"
.
equals
(
type
))
{
return
Long
.
valueOf
(
Math
.
round
(
flt
.
doubleValue
()));
}
if
(
"Integer"
.
equals
(
type
))
{
return
Integer
.
valueOf
((
int
)
Math
.
round
(
flt
.
doubleValue
()));
}
else
{
throw
new
RuntimeException
(
"Conversion from "
+
fromType
+
" to "
+
type
+
" not currently supported"
);
}
}
if
(
obj
instanceof
Long
)
{
fromType
=
"Long"
;
Long
lng
=
(
Long
)
obj
;
if
(
"String"
.
equals
(
type
)
||
"java.lang.String"
.
equals
(
type
))
{
return
getNf
(
locale
).
format
(
lng
.
longValue
());
}
if
(
"Double"
.
equals
(
type
)
||
"java.lang.Double"
.
equals
(
type
))
{
return
Double
.
valueOf
(
lng
.
doubleValue
());
}
if
(
"Float"
.
equals
(
type
)
||
"java.lang.Float"
.
equals
(
type
))
{
return
Float
.
valueOf
(
lng
.
floatValue
());
}
if
(
"BigDecimal"
.
equals
(
type
)
||
"java.math.BigDecimal"
.
equals
(
type
))
{
return
new
BigDecimal
(
lng
.
toString
());
}
if
(
"Long"
.
equals
(
type
)
||
"java.lang.Long"
.
equals
(
type
))
{
return
obj
;
}
if
(
"Integer"
.
equals
(
type
)
||
"java.lang.Integer"
.
equals
(
type
))
{
return
Integer
.
valueOf
(
lng
.
intValue
());
}
else
{
throw
new
RuntimeException
(
"Conversion from "
+
fromType
+
" to "
+
type
+
" not currently supported"
);
}
}
if
(
obj
instanceof
Integer
)
{
fromType
=
"Integer"
;
Integer
intgr
=
(
Integer
)
obj
;
if
(
"String"
.
equals
(
type
)
||
"java.lang.String"
.
equals
(
type
))
{
return
getNf
(
locale
).
format
(
intgr
.
longValue
());
}
if
(
"Double"
.
equals
(
type
)
||
"java.lang.Double"
.
equals
(
type
))
{
return
Double
.
valueOf
(
intgr
.
doubleValue
());
}
if
(
"Float"
.
equals
(
type
)
||
"java.lang.Float"
.
equals
(
type
))
{
return
Float
.
valueOf
(
intgr
.
floatValue
());
}
if
(
"BigDecimal"
.
equals
(
type
)
||
"java.math.BigDecimal"
.
equals
(
type
))
{
String
str
=
intgr
.
toString
();
BigDecimal
retBig
=
new
BigDecimal
(
intgr
.
doubleValue
());
int
iscale
=
str
.
indexOf
(
"."
);
int
keylen
=
str
.
length
();
if
(
iscale
>
-
1
)
{
iscale
=
keylen
-
(
iscale
+
1
);
return
retBig
.
setScale
(
iscale
,
5
);
}
else
{
return
retBig
.
setScale
(
0
,
5
);
}
}
if
(
"Long"
.
equals
(
type
)
||
"java.lang.Long"
.
equals
(
type
))
{
return
Long
.
valueOf
(
intgr
.
longValue
());
}
if
(
"Integer"
.
equals
(
type
)
||
"java.lang.Integer"
.
equals
(
type
))
{
return
obj
;
}
else
{
throw
new
RuntimeException
(
"Conversion from "
+
fromType
+
" to "
+
type
+
" not currently supported"
);
}
}
if
(
obj
instanceof
Date
)
{
fromType
=
"Date"
;
Date
dte
=
(
Date
)
obj
;
if
(
"String"
.
equals
(
type
)
||
"java.lang.String"
.
equals
(
type
))
{
if
(
format
==
null
||
format
.
length
()
==
0
)
{
return
dte
.
toString
();
}
else
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
format
);
return
sdf
.
format
(
new
java
.
util
.
Date
(
dte
.
getTime
()));
}
}
if
(
"Date"
.
equals
(
type
)
||
"java.sql.Date"
.
equals
(
type
))
{
return
obj
;
}
if
(
"Time"
.
equals
(
type
)
||
"java.sql.Time"
.
equals
(
type
))
{
throw
new
RuntimeException
(
"Conversion from "
+
fromType
+
" to "
+
type
+
" not currently supported"
);
}
if
(
"Timestamp"
.
equals
(
type
)
||
"java.sql.Timestamp"
.
equals
(
type
))
{
return
new
Timestamp
(
dte
.
getTime
());
}
else
{
throw
new
RuntimeException
(
"Conversion from "
+
fromType
+
" to "
+
type
+
" not currently supported"
);
}
}
if
(
obj
instanceof
Timestamp
)
{
fromType
=
"Timestamp"
;
Timestamp
tme
=
(
Timestamp
)
obj
;
if
(
"String"
.
equals
(
type
)
||
"java.lang.String"
.
equals
(
type
))
{
if
(
format
==
null
||
format
.
length
()
==
0
)
{
return
(
new
SimpleDateFormat
(
"yyyy-MM-dd HH:mm:ss"
)).
format
(
tme
).
toString
();
}
else
{
SimpleDateFormat
sdf
=
new
SimpleDateFormat
(
format
);
return
sdf
.
format
(
new
java
.
util
.
Date
(
tme
.
getTime
()));
}
}
if
(
"Date"
.
equals
(
type
)
||
"java.sql.Date"
.
equals
(
type
))
{
return
new
Date
(
tme
.
getTime
());
}
if
(
"Time"
.
equals
(
type
)
||
"java.sql.Time"
.
equals
(
type
))
{
return
new
Time
(
tme
.
getTime
());
}
if
(
"Timestamp"
.
equals
(
type
)
||
"java.sql.Timestamp"
.
equals
(
type
))
{
return
obj
;
}
else
{
throw
new
RuntimeException
(
"Conversion from "
+
fromType
+
" to "
+
type
+
" not currently supported"
);
}
}
if
(
obj
instanceof
Boolean
)
{
fromType
=
"Boolean"
;
Boolean
bol
=
(
Boolean
)
obj
;
if
(
"Boolean"
.
equals
(
type
)
||
"java.lang.Boolean"
.
equals
(
type
))
{
return
bol
;
}
if
(
"String"
.
equals
(
type
)
||
"java.lang.String"
.
equals
(
type
))
{
return
bol
.
toString
();
}
if
(
"Integer"
.
equals
(
type
)
||
"java.lang.Integer"
.
equals
(
type
))
{
if
(
bol
.
booleanValue
())
{
return
Integer
.
valueOf
(
1
);
}
else
{
return
Integer
.
valueOf
(
0
);
}
}
else
{
throw
new
RuntimeException
(
"Conversion from "
+
fromType
+
" to "
+
type
+
" not currently supported"
);
}
}
if
(
"String"
.
equals
(
type
)
||
"java.lang.String"
.
equals
(
type
))
{
return
obj
.
toString
();
}
else
{
throw
new
RuntimeException
(
"Conversion from "
+
obj
.
getClass
().
getName
()
+
" to "
+
type
+
" not currently supported"
);
}
}
private
static
NumberFormat
getNf
(
Locale
locale
)
{
NumberFormat
nf
=
null
;
if
(
locale
==
null
)
{
nf
=
NumberFormat
.
getNumberInstance
();
}
else
{
nf
=
NumberFormat
.
getNumberInstance
(
locale
);
}
nf
.
setGroupingUsed
(
false
);
return
nf
;
}
public
static
Boolean
convert2SBoolean
(
Object
obj
)
{
return
(
Boolean
)
convert
(
obj
,
"Boolean"
,
null
);
}
public
static
Integer
convert2Integer
(
Object
obj
)
{
return
(
Integer
)
convert
(
obj
,
"Integer"
,
null
);
}
public
static
String
convert2String
(
Object
obj
)
{
return
(
String
)
convert
(
obj
,
"String"
,
null
);
}
public
static
String
convert2String
(
Object
obj
,
String
defaultValue
)
{
Object
s
=
convert
(
obj
,
"String"
,
null
);
if
(
s
!=
null
)
{
return
(
String
)
s
;
}
else
{
return
""
;
}
}
public
static
Long
convert2Long
(
Object
obj
)
{
return
(
Long
)
convert
(
obj
,
"Long"
,
null
);
}
public
static
Double
convert2Double
(
Object
obj
)
{
return
(
Double
)
convert
(
obj
,
"Double"
,
null
);
}
public
static
BigDecimal
convert2BigDecimal
(
Object
obj
,
int
scale
)
{
return
((
BigDecimal
)
convert
(
obj
,
"BigDecimal"
,
null
)).
setScale
(
scale
,
5
);
}
public
static
Date
convert2SqlDate
(
Object
obj
,
String
format
)
{
return
(
Date
)
convert
(
obj
,
"Date"
,
format
);
}
public
static
Timestamp
convert2Timestamp
(
Object
obj
,
String
format
)
{
return
(
Timestamp
)
convert
(
obj
,
"Timestamp"
,
format
);
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/UUIDUtil.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.util.UUID
;
/**
* @author liujixiang
* @date 2018-11-08
*/
public
class
UUIDUtil
{
public
static
String
getUUID
()
{
String
uuid
=
UUID
.
randomUUID
().
toString
().
replaceAll
(
"-"
,
""
);
return
uuid
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/VOHelpler.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.lang.reflect.Field
;
import
java.lang.reflect.Modifier
;
import
java.math.BigDecimal
;
import
java.math.RoundingMode
;
import
java.util.Date
;
import
java.util.List
;
import
java.util.concurrent.atomic.AtomicInteger
;
import
org.apache.commons.lang3.RandomUtils
;
import
org.apache.commons.lang3.StringUtils
;
import
com.google.common.collect.Lists
;
import
io.swagger.annotations.ApiModelProperty
;
import
lombok.extern.slf4j.Slf4j
;
@Slf4j
public
class
VOHelpler
{
private
static
AtomicInteger
rec
=
new
AtomicInteger
();
@SuppressWarnings
(
"unchecked"
)
public
static
<
T
,
D
>
T
random
(
Class
<
T
>
t
,
Class
<
D
>
d
)
{
T
o
=
null
;
try
{
if
(
StringUtils
.
startsWithAny
(
t
.
getName
(),
"org.glsx"
,
"cn.com.glsx.charging"
))
{
o
=
initSwaggerExample
(
t
.
newInstance
());
}
else
if
(
t
==
Integer
.
class
||
t
==
int
.
class
)
{
o
=
(
T
)
Integer
.
valueOf
(
RandomUtils
.
nextInt
(
10
,
3000
)
+
1
);
}
else
if
(
t
==
List
.
class
)
{
o
=
(
T
)
Lists
.
newArrayList
();
for
(
int
i
=
0
;
i
<
3
;
i
++)
{
if
(
d
!=
null
)
{
((
List
)
o
).
add
(
random
(
d
,
null
));
}
else
{
((
List
)
o
).
add
(
initSwaggerExample
(
ClassUtils
.
getGenricType
(
t
,
0
)));
}
}
}
else
if
(
t
==
String
.
class
)
{
o
=
(
T
)
"test_str"
;
}
else
if
(
t
==
Date
.
class
)
{
o
=
(
T
)
DateUtils
.
addDay
(
DateUtils
.
today
(),
-
rec
.
getAndIncrement
());
if
(
rec
.
get
()
>=
7
)
{
rec
.
set
(
0
);
}
}
else
if
(
t
==
BigDecimal
.
class
)
{
o
=
(
T
)
BigDecimal
.
valueOf
(
RandomUtils
.
nextDouble
()).
setScale
(
4
,
RoundingMode
.
HALF_UP
);
}
else
{
log
.
info
(
"not init type:{}"
,
t
.
getName
());
}
}
catch
(
Exception
e
)
{
e
.
printStackTrace
();
}
return
o
;
}
public
static
<
O
>
O
initSwaggerExample
(
O
o
)
{
if
(
o
==
null
)
{
return
o
;
}
List
<
Field
>
fields
=
BeanUtils
.
getFields
(
o
.
getClass
());
for
(
Field
f
:
fields
)
{
try
{
f
.
setAccessible
(
true
);
if
(
StringUtils
.
startsWithAny
(
f
.
getType
().
getName
(),
"org.glsx"
,
"cn.com.glsx.charging"
))
{
if
(
f
.
get
(
o
)
==
null
&&
!
Modifier
.
isAbstract
(
f
.
getType
().
getModifiers
()))
{
// 直接初始化
Object
v
=
initSwaggerExample
(
f
.
getType
().
newInstance
());
f
.
set
(
o
,
v
);
}
else
{
initSwaggerExample
(
f
.
get
(
o
));
}
}
else
if
(
StringUtils
.
startsWith
(
f
.
getType
().
getName
(),
"java"
))
{
ApiModelProperty
annon
=
f
.
getAnnotation
(
ApiModelProperty
.
class
);
if
(
annon
!=
null
&&
StringUtils
.
isNotEmpty
(
annon
.
example
()))
{
if
(
StringUtils
.
isNotEmpty
(
annon
.
dataType
()))
{
f
.
set
(
o
,
TypeConvertUtil
.
convert
(
annon
.
example
(),
f
.
getType
().
getName
(),
annon
.
dataType
()));
}
else
{
f
.
set
(
o
,
TypeConvertUtil
.
convert
(
annon
.
example
(),
f
.
getType
().
getName
(),
null
));
}
}
else
{
// 直接初始化
f
.
setAccessible
(
true
);
f
.
set
(
o
,
random
(
f
.
getType
(),
ClassUtils
.
getFieldGenericType
(
f
,
0
)));
}
}
}
catch
(
Exception
e
)
{
log
.
warn
(
"field:{}"
,
f
,
e
);
}
}
return
o
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/VerificationCode.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.awt.Color
;
import
java.awt.Font
;
import
java.awt.Graphics2D
;
import
java.awt.image.BufferedImage
;
import
java.util.Random
;
/**
* @author liujixiang
* @date 2018-11-08
*/
public
class
VerificationCode
{
private
int
weight
=
110
;
// 验证码图片的长和宽
private
int
height
=
38
;
private
String
text
;
// 用来保存验证码的文本内容
private
Random
r
=
new
Random
();
// 获取随机数对象
private
String
[]
fontNames
=
{
"宋体"
,
"华文楷体"
,
"黑体"
,
"微软雅黑"
,
"楷体_GB2312"
};
// 字体数组
private
String
codes
=
"23456789acdefghjkmnopqrstuvwxyzACDEFGHJKMNPQRSTUVWXYZ"
;
// 验证码数组
/**
* 获取随机的颜色
*/
private
Color
randomColor
()
{
// 这里为什么是150,因为当r,g,b都为255时,即为白色,为了好辨认,需要颜色深一点。
int
r
=
this
.
r
.
nextInt
(
150
);
int
g
=
this
.
r
.
nextInt
(
150
);
int
b
=
this
.
r
.
nextInt
(
150
);
// 返回一个随机颜色
return
new
Color
(
r
,
g
,
b
);
}
/**
* 获取随机字体
*/
private
Font
randomFont
()
{
// 获取随机的字体
int
index
=
r
.
nextInt
(
fontNames
.
length
);
String
fontName
=
fontNames
[
index
];
// 随机获取字体的样式,0是无样式,1是加粗,2是斜体,3是加粗加斜体
int
style
=
r
.
nextInt
(
4
);
// 随机获取字体的大小
int
size
=
r
.
nextInt
(
5
)
+
24
;
// 返回一个随机的字体
return
new
Font
(
fontName
,
style
,
size
);
}
/**
* 获取随机字符
*/
private
char
randomChar
()
{
int
index
=
r
.
nextInt
(
codes
.
length
());
return
codes
.
charAt
(
index
);
}
/**
* 画干扰线,验证码干扰线用来防止计算机解析图片
*/
private
void
drawLine
(
BufferedImage
image
)
{
int
num
=
155
;
// 定义干扰线的数量
Graphics2D
g
=
(
Graphics2D
)
image
.
getGraphics
();
for
(
int
i
=
0
;
i
<
num
;
i
++)
{
int
x
=
r
.
nextInt
(
weight
);
int
y
=
r
.
nextInt
(
height
);
int
xl
=
r
.
nextInt
(
weight
);
int
yl
=
r
.
nextInt
(
height
);
g
.
setColor
(
getRandColor
(
160
,
200
));
g
.
drawLine
(
x
,
y
,
x
+
xl
,
y
+
yl
);
}
}
/**
* 创建图片的方法
*/
private
BufferedImage
createImage
()
{
// 创建图片缓冲区
BufferedImage
image
=
new
BufferedImage
(
weight
,
height
,
BufferedImage
.
TYPE_INT_RGB
);
// 获取画笔
Graphics2D
g
=
(
Graphics2D
)
image
.
getGraphics
();
// 设定图像背景色(因为是做背景,所以偏淡)
g
.
setColor
(
getRandColor
(
200
,
250
));
g
.
fillRect
(
0
,
0
,
weight
,
height
);
// 返回一个图片
return
image
;
}
/**
* 获取验证码图片的方法
*/
public
BufferedImage
getImage
()
{
BufferedImage
image
=
createImage
();
// 获取画笔
Graphics2D
g
=
(
Graphics2D
)
image
.
getGraphics
();
StringBuilder
sb
=
new
StringBuilder
();
drawLine
(
image
);
// 画四个字符即可
for
(
int
i
=
0
;
i
<
4
;
i
++)
{
// 随机生成字符,因为只有画字符串的方法,没有画字符的方法,所以需要将字符变成字符串再画
String
s
=
randomChar
()
+
""
;
// 添加到StringBuilder里面
sb
.
append
(
s
);
// 定义字符的x坐标
float
x
=
i
*
1.0
F
*
weight
/
4
;
// 设置字体,随机
g
.
setFont
(
randomFont
());
// 设置颜色,随机
g
.
setColor
(
randomColor
());
g
.
drawString
(
s
,
x
,
height
-
5
);
}
this
.
text
=
sb
.
toString
();
return
image
;
}
/**
* 给定范围获得随机颜色
*/
Color
getRandColor
(
int
fc
,
int
bc
)
{
Random
random
=
new
Random
();
if
(
fc
>
255
)
{
fc
=
255
;
}
if
(
bc
>
255
)
{
bc
=
255
;
}
int
r
=
fc
+
random
.
nextInt
(
bc
-
fc
);
int
g
=
fc
+
random
.
nextInt
(
bc
-
fc
);
int
b
=
fc
+
random
.
nextInt
(
bc
-
fc
);
return
new
Color
(
r
,
g
,
b
);
}
/**
* 获取验证码文本的方法
*/
public
String
getText
()
{
return
text
;
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/WebUtils.java
0 → 100644
View file @
81f2091
/*
* @Copyright: 2014~2018 www.yyfax.com Inc. All rights reserved.
*/
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.io.IOException
;
import
java.io.InputStream
;
import
java.util.Enumeration
;
import
java.util.HashMap
;
import
java.util.Map
;
import
java.util.Map.Entry
;
import
javax.servlet.ServletRequest
;
import
javax.servlet.http.HttpServletRequest
;
import
org.apache.commons.lang3.StringUtils
;
import
org.springframework.core.annotation.AnnotationUtils
;
import
org.springframework.util.StreamUtils
;
import
org.springframework.web.bind.annotation.ResponseBody
;
import
org.springframework.web.bind.annotation.RestController
;
import
org.springframework.web.method.HandlerMethod
;
/**
* web操作工具
*
* @author jiangmy
* @date 2018年1月15日 下午4:58:38
* @since 1.0.0
*/
public
class
WebUtils
{
/**
* 获取登录用户IP地址
*
* @param request
* @return
*/
public
static
String
getRequestIp
(
HttpServletRequest
request
)
{
String
ip
=
request
.
getHeader
(
"X-real-ip"
);
if
(
StringUtils
.
isBlank
(
ip
))
{
ip
=
request
.
getHeader
(
"X-Forward-For"
);
}
if
(
StringUtils
.
isBlank
(
ip
)
||
StringUtils
.
equalsIgnoreCase
(
"unknown"
,
ip
))
{
ip
=
request
.
getHeader
(
"Proxy-Client-IP"
);
}
if
(
StringUtils
.
isBlank
(
ip
)
||
StringUtils
.
equalsIgnoreCase
(
"unknown"
,
ip
))
{
ip
=
request
.
getHeader
(
"WL-Proxy-Client-IP"
);
}
if
(
StringUtils
.
isBlank
(
ip
))
{
ip
=
request
.
getRemoteAddr
();
}
return
ip
;
}
/**
* 从request中获得参数Map,并返回可读的Map. 同名参数用逗号分隔
*
* @param request
* @return
*/
public
static
Map
<
String
,
String
>
getParameterMap
(
HttpServletRequest
request
)
{
// 参数Map
Map
<
String
,
String
[]>
properties
=
request
.
getParameterMap
();
// 返回值Map
Map
<
String
,
String
>
returnMap
=
new
HashMap
<
String
,
String
>();
String
name
=
""
;
String
value
=
""
;
for
(
Entry
<
String
,
String
[]>
entry
:
properties
.
entrySet
())
{
name
=
entry
.
getKey
();
String
[]
values
=
entry
.
getValue
();
if
(
null
==
values
)
{
value
=
""
;
}
else
{
value
=
StringUtils
.
join
(
values
,
","
);
}
returnMap
.
put
(
name
,
value
);
}
return
returnMap
;
}
public
static
Map
<
String
,
String
>
getHeaderMap
(
HttpServletRequest
request
)
{
// 返回值Map
Map
<
String
,
String
>
returnMap
=
new
HashMap
<
String
,
String
>();
Enumeration
<
String
>
names
=
request
.
getHeaderNames
();
String
header
;
while
(
names
.
hasMoreElements
())
{
header
=
names
.
nextElement
();
returnMap
.
put
(
header
,
request
.
getHeader
(
header
));
}
return
returnMap
;
}
/**
* 获取请求Body
*
* @param request
* @return
*/
public
static
String
getBodyString
(
ServletRequest
request
)
{
try
(
InputStream
inputStream
=
request
.
getInputStream
())
{
// reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
// String line = "";
// while ((line = reader.readLine()) != null) {
// sb.append(line).append("\n");
// }
byte
[]
data
=
StreamUtils
.
copyToByteArray
(
inputStream
);
return
new
String
(
data
,
"UTF-8"
);
}
catch
(
IOException
e
)
{
e
.
printStackTrace
();
return
null
;
}
}
/**
* 是否是Json请求
*
* @param request Http请求
* @return 是则返回<code>TRUE</code>
*/
public
static
final
boolean
isJsonRequest
(
HttpServletRequest
request
,
Object
handler
)
{
// Ajax请求默认认为是json请求
String
requestedWith
=
request
.
getHeader
(
"X-Requested-With"
);
if
(
StringUtils
.
equalsIgnoreCase
(
requestedWith
,
"XMLHttpRequest"
))
{
return
true
;
}
// 请求url中包含.json或.jsonp的也认为是json请求
String
requestUri
=
request
.
getRequestURI
();
if
(
StringUtils
.
endsWithIgnoreCase
(
requestUri
,
".json"
)
||
StringUtils
.
endsWithIgnoreCase
(
requestUri
,
".jsonp"
))
{
return
true
;
}
// handler如果带了@ResponseBody也认为是JSON请求
if
(
handler
instanceof
HandlerMethod
)
{
HandlerMethod
hm
=
(
HandlerMethod
)
handler
;
// ResponseBody
if
(
hm
.
getMethod
().
getAnnotation
(
ResponseBody
.
class
)
!=
null
)
{
return
true
;
}
// RestController
if
(
AnnotationUtils
.
findAnnotation
(
hm
.
getBean
().
getClass
(),
RestController
.
class
)
!=
null
)
{
return
true
;
}
}
return
false
;
}
private
WebUtils
()
{
}
}
platform-charging/src/main/java/cn/com/glsx/charging/util/package-info.java
0 → 100644
View file @
81f2091
/**
* 公共工具包
*
* @author liujixiang
* @date 2018-11-08
*/
package
cn
.
com
.
glsx
.
charging
.
util
;
\ No newline at end of file
\ No newline at end of file
platform-charging/src/main/resources/application.properties_standalone
View file @
81f2091
...
@@ -11,6 +11,9 @@ server.tomcat.max-threads=1000
...
@@ -11,6 +11,9 @@ server.tomcat.max-threads=1000
server.tomcat.min-spare-threads=30s
server.tomcat.min-spare-threads=30s
server.tomcat.basedir=/temp
server.tomcat.basedir=/temp
ocpp16.server.host=localhost
ocpp16.server.port=8888
#database
#database
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.0.39:3306/gecc?serverTimeZone=Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.url=jdbc:mysql://192.168.0.39:3306/gecc?serverTimeZone=Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=false
...
...
platform-charging/src/main/resources/bootstrap.properties
View file @
81f2091
#项目名称
#项目名称
spring.application.name
=
rest-admin
spring.application.name
=
platform-charging
#日志路径(logback-spring.xml读取,不要加入配置中心)
#日志路径(logback-spring.xml读取,不要加入配置中心)
logging.path
=
/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
logging.path
=
/data/java_log/jetty/${spring.application.name}/${spring.application.name}.log
logging.config
=
classpath:logback.xml
logging.file
=
/opt/logs/stdout.log
logging.level.io.geekidea.fastspringboot
=
DEBUG
logging.level.org.springframework.web
=
INFO
logging.level.root
=
INFO
#logging.pattern.console=%d{HH:mm:ss.SSS} [%5p] - %m \\(%F:%L\\)%n
#logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%5p] - %m (%F:%L)%n
### 禁用nacos,启用本地配置文件
spring.cloud.nacos.config.enabled
=
false
spring.cloud.nacos.config.refresh-
enabled
=
false
spring.cloud.nacos.discovery.enabled
=
false
spring.cloud.nacos.discovery.instance-
enabled
=
false
#nacos配置中心
#nacos配置中心
spring.cloud.nacos.config.server-
addr
=
192.168.0.63:8868
spring.cloud.nacos.config.server-
addr
=
192.168.0.63:8868
...
...
platform-charging/src/main/resources/logback
-spring
.xml
→
platform-charging/src/main/resources/logback.xml
View file @
81f2091
...
@@ -32,7 +32,7 @@ logback-spring.xml引入文件:
...
@@ -32,7 +32,7 @@ logback-spring.xml引入文件:
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" />-->
<!-- 配置日志输出参数,彩色日志格式 -->
<!-- 配置日志输出参数,彩色日志格式 -->
<property
name=
"CONSOLE_LOG_PATTERN"
value=
"%
clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}
"
/>
<property
name=
"CONSOLE_LOG_PATTERN"
value=
"%
date{HH:mm:ss.SSS} | %-5level | %msg | \\(%file:%line\\) %n
"
/>
<!-- 控制台打印日志 -->
<!-- 控制台打印日志 -->
<appender
name=
"console"
class=
"ch.qos.logback.core.ConsoleAppender"
>
<appender
name=
"console"
class=
"ch.qos.logback.core.ConsoleAppender"
>
...
...
platform-charging/src/test/java/cn/com/glsx/charging/ClientTest.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
;
/*
ChargeTime.eu - Java-OCA-OCPP
Copyright (C) 2015-2016 Thomas Volden <tv@chargetime.eu>
MIT License
Copyright (C) 2016-2018 Thomas Volden
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import
org.junit.runner.RunWith
;
import
org.mockito.junit.MockitoJUnitRunner
;
@RunWith
(
MockitoJUnitRunner
.
class
)
public
class
ClientTest
{
// private Client client;
// private SessionEvents eventHandler;
//
// @Mock private Session session;
// @Mock private Feature feature;
// @Mock private Request request;
// @Mock private CompletableFuture<Confirmation> completableFuture;
// @Mock private ClientEvents events;
// @Mock private IFeatureRepository featureRepository;
// @Mock private IPromiseRepository promiseRepository;
//
// @Before
// public void setup() {
// when(request.validate()).thenReturn(true);
// doAnswer(invocation -> eventHandler = invocation.getArgument(1, SessionEvents.class))
// .when(session)
// .open(any(), any());
//
// when(featureRepository.findFeature(any())).thenReturn(Optional.of(feature));
// when(session.getFeatureRepository()).thenReturn(featureRepository);
// client = new Client(session, promiseRepository);
// }
//
// @Test
// public void connect_connects() {
// // Given
// String someUrl = "localhost";
//
// // When
// client.connect(someUrl, events);
//
// // Then
// verify(session, times(1)).open(eq(someUrl), any());
// }
//
// @Test
// public void connect_connectionOpenedEvent() {
// // Given
// client.connect(null, events);
//
// // When
// this.eventHandler.handleConnectionOpened();
//
// // Then
// verify(events, times(1)).connectionOpened();
// verify(events, never()).connectionClosed();
// }
//
// @Test
// public void connect_connectionClosedEvent() {
// // Given
// client.connect(null, events);
//
// // When
// this.eventHandler.handleConnectionClosed();
//
// // Then
// verify(events, times(1)).connectionClosed();
// verify(events, never()).connectionOpened();
// }
//
// @Test
// public void send_aMessage_isCommunicated() throws Exception {
// // When
// client.send(request);
//
// // Then
// // TODO action and uuid should not be nullable
// verify(session, times(1)).sendRequest(nullable(String.class), eq(request), nullable(String.class));
// }
//
// @Test
// public void responseReceived_aMessageWasSend_PromiseIsCompleted() throws Exception {
// // Given
// String someUniqueId = "Some id";
// lenient().when(session.storeRequest(any())).thenReturn(someUniqueId);
// when(promiseRepository.getPromise(any())).thenReturn(Optional.of(completableFuture));
//
// // When
// client.connect(null, null);
// eventHandler.handleConfirmation(someUniqueId, null);
//
// // Then
// verify(promiseRepository).getPromise(someUniqueId);
// }
//
// @Test
// public void handleRequest_returnsConfirmation() throws UnsupportedFeatureException {
// // Given
// client.connect(null, null);
// when(feature.handleRequest(null, request)).thenReturn(new TestConfirmation());
//
// // When
// Confirmation conf = eventHandler.handleRequest(request);
//
// // Then
// assertThat(conf, instanceOf(TestConfirmation.class));
// }
//
// @Test
// public void handleRequest_callsFeatureHandleRequest() throws UnsupportedFeatureException {
// // Given
// client.connect(null, null);
//
// // When
// eventHandler.handleRequest(request);
//
// // Then
// verify(feature, times(1)).handleRequest(any(), eq(request));
// }
//
// @Test
// public void send_aMessage_validatesMessage() throws Exception {
// // When
// client.send(request);
//
// // Then
// verify(request, times(1)).validate();
// }
}
platform-charging/src/test/java/cn/com/glsx/charging/ServerTest.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
;
import
org.junit.runner.RunWith
;
import
org.mockito.junit.MockitoJUnitRunner
;
/*
ChargeTime.eu - Java-OCA-OCPP
MIT License
Copyright (C) 2016-2018 Thomas Volden <tv@chargetime.eu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
@RunWith
(
MockitoJUnitRunner
.
class
)
public
class
ServerTest
{
private
static
final
String
LOCALHOST
=
"localhost"
;
private
static
final
int
PORT
=
42
;
// private Server server;
// private SessionEvents sessionEvents;
// private ListenerEvents listenerEvents;
// private UUID sessionIndex;
//
// @Mock private Session session;
// @Mock private Feature feature;
// @Mock private Listener listener;
// @Mock private ServerEvents serverEvents;
// @Mock private Request request;
// @Mock private SessionInformation information;
// @Mock private IFeatureRepository featureRepository;
// @Mock private IPromiseRepository promiseRepository;
//
// @Before
// public void setup() {
// UUID sessionId = UUID.randomUUID();
// when(request.validate()).thenReturn(true);
// when(session.getSessionId()).thenReturn(sessionId);
// doAnswer(invocation -> listenerEvents = invocation.getArgument(2, ListenerEvents.class))
// .when(listener)
// .open(anyString(), anyInt(), any());
// doAnswer(invocation -> sessionEvents = invocation.getArgument(0, SessionEvents.class))
// .when(session)
// .accept(any());
// doAnswer(invocation -> sessionIndex = invocation.getArgument(0, UUID.class))
// .when(serverEvents)
// .newSession(any(), any());
//
// when(featureRepository.findFeature(any())).thenReturn(Optional.of(feature));
// when(session.getFeatureRepository()).thenReturn(featureRepository);
// server = new Server(listener, promiseRepository);
// }
//
// @Test
// public void newSession_serverIsListening_sessionIsAccepted() {
// // Given
// server.open(LOCALHOST, PORT, serverEvents);
//
// // When
// listenerEvents.newSession(session, information);
//
// // Then
// verify(session, times(1)).accept(any());
// }
//
// @Test
// public void newSession_serverIsListening_callbackWithIndex0() {
// // Given
// server.open(LOCALHOST, PORT, serverEvents);
//
// // When
// listenerEvents.newSession(session, information);
//
// // Then
// verify(serverEvents, times(1)).newSession(any(UUID.class), eq(information));
// }
//
// @Test
// public void send_aMessage_isCommunicated() throws Exception {
// // Given
// server.open(LOCALHOST, PORT, serverEvents);
// listenerEvents.newSession(session, information);
//
// // When
// server.send(sessionIndex, request);
//
// // Then
// // TODO action and uuid should not be nullable
// verify(session, times(1)).sendRequest(nullable(String.class), eq(request), nullable(String.class));
// }
//
// @Test
// public void handleRequest_callsFeatureHandleRequest() throws UnsupportedFeatureException {
// // Given
// server.open(LOCALHOST, PORT, serverEvents);
// listenerEvents.newSession(session, information);
//
// // When
// sessionEvents.handleRequest(request);
//
// // Then
// verify(feature, times(1)).handleRequest(any(UUID.class), eq(request));
// }
//
// @Test
// public void send_aMessage_validatesMessage() throws Exception {
// // Given
// server.open(LOCALHOST, PORT, serverEvents);
// listenerEvents.newSession(session, information);
//
// // When
// server.send(sessionIndex, request);
//
// // Then
// verify(request, times(1)).validate();
// }
}
platform-charging/src/test/java/cn/com/glsx/charging/TestApplication.java
deleted
100644 → 0
View file @
3d31b91
//package cn.com.glsx.charging;
//
//import com.glsx.microservice.api.EchoCenterFeignService;
//import com.glsx.plat.core.web.R;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.SpringApplication;
//import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
//import org.springframework.cloud.client.loadbalancer.LoadBalanced;
//import org.springframework.context.annotation.Bean;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.client.RestTemplate;
//
//import javax.annotation.Resource;
//
///**
// * 测试spring cloud 服务调用方式
// */
//@EnableDiscoveryClient
//@SpringBootApplication
//public class TestApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(TestApplication.class, args);
// }
//
// @Slf4j
// @RestController
// static class TestController {
//
// @Autowired
// RestTemplate restTemplate;
//
// @Resource
// private EchoCenterFeignService echoCenterFeignService;
//
//// @Autowired
//// private WebClient.Builder webClientBuilder;
//
// @GetMapping("/test1")
// public String test1() {
// String result = restTemplate.getForObject("http://192.168.0.63:8829/rest-echo-center/echo/didi", String.class);
// return "Return : " + result;
// }
//
//// @GetMapping("/test")
//// public Mono<String> test() {
//// Mono<String> result = webClientBuilder.build()
//// .get()
//// .uri("http://alibaba-nacos-discovery-server/hello?name=didi")
//// .retrieve()
//// .bodyToMono(String.class);
//// return result;
//// }
//
// @GetMapping("/test3")
// public R test3() {
// String result = echoCenterFeignService.echo("this is a test!");
// return R.ok().data(result);
// }
// }
//
// @Bean
// @LoadBalanced
// public RestTemplate restTemplate() {
// return new RestTemplate();
// }
//
//// @Bean
//// @LoadBalanced
//// public WebClient.Builder loadBalancedWebClientBuilder() {
//// return WebClient.builder();
//// }
//
//}
\ No newline at end of file
\ No newline at end of file
platform-charging/src/test/java/cn/com/glsx/charging/cn/com/glsx/TestApplication.java
deleted
100644 → 0
View file @
3d31b91
//package cn.com.glsx.charging;
//
//import com.glsx.microservice.api.EchoCenterFeignService;
//import com.glsx.plat.core.web.R;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.SpringApplication;
//import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
//import org.springframework.cloud.client.loadbalancer.LoadBalanced;
//import org.springframework.context.annotation.Bean;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.client.RestTemplate;
//
//import javax.annotation.Resource;
//
///**
// * 测试spring cloud 服务调用方式
// */
//@EnableDiscoveryClient
//@SpringBootApplication
//public class TestApplication {
//
// public static void main(String[] args) {
// SpringApplication.run(TestApplication.class, args);
// }
//
// @Slf4j
// @RestController
// static class TestController {
//
// @Autowired
// RestTemplate restTemplate;
//
// @Resource
// private EchoCenterFeignService echoCenterFeignService;
//
//// @Autowired
//// private WebClient.Builder webClientBuilder;
//
// @GetMapping("/test1")
// public String test1() {
// String result = restTemplate.getForObject("http://192.168.0.63:8829/rest-echo-center/echo/didi", String.class);
// return "Return : " + result;
// }
//
//// @GetMapping("/test")
//// public Mono<String> test() {
//// Mono<String> result = webClientBuilder.build()
//// .get()
//// .uri("http://alibaba-nacos-discovery-server/hello?name=didi")
//// .retrieve()
//// .bodyToMono(String.class);
//// return result;
//// }
//
// @GetMapping("/test3")
// public R test3() {
// String result = echoCenterFeignService.echo("this is a test!");
// return R.ok().data(result);
// }
// }
//
// @Bean
// @LoadBalanced
// public RestTemplate restTemplate() {
// return new RestTemplate();
// }
//
//// @Bean
//// @LoadBalanced
//// public WebClient.Builder loadBalancedWebClientBuilder() {
//// return WebClient.builder();
//// }
//
//}
\ No newline at end of file
\ No newline at end of file
platform-charging/src/test/java/cn/com/glsx/charging/util/JsonSerializationExample.java
0 → 100644
View file @
81f2091
package
cn
.
com
.
glsx
.
charging
.
util
;
import
java.io.IOException
;
import
java.lang.annotation.Retention
;
import
java.lang.annotation.RetentionPolicy
;
import
java.lang.reflect.Field
;
import
com.fasterxml.jackson.core.JsonGenerator
;
import
com.fasterxml.jackson.databind.JsonSerializer
;
import
com.fasterxml.jackson.databind.ObjectMapper
;
import
com.fasterxml.jackson.databind.SerializerProvider
;
import
com.fasterxml.jackson.databind.module.SimpleModule
;
import
lombok.Getter
;
import
lombok.Setter
;
@Retention
(
RetentionPolicy
.
RUNTIME
)
@interface
FieldDescription
{
String
value
();
}
@Getter
@Setter
class
MyClass
{
@FieldDescription
(
"这是一个整数字段"
)
private
int
myIntField
;
@FieldDescription
(
"这是另一个整数字段"
)
private
int
anotherIntField
;
// 省略其他代码(构造函数、getter 和 setter 方法等)
}
class
FieldDescriptionSerializer
extends
JsonSerializer
<
MyClass
>
{
@Override
public
void
serialize
(
MyClass
myObj
,
JsonGenerator
jsonGenerator
,
SerializerProvider
serializerProvider
)
throws
IOException
{
jsonGenerator
.
writeStartObject
();
// 获取类的字段
Field
[]
fields
=
myObj
.
getClass
().
getDeclaredFields
();
for
(
Field
field
:
fields
)
{
// 检查字段是否添加了 FieldDescription 注解
if
(
field
.
isAnnotationPresent
(
FieldDescription
.
class
))
{
FieldDescription
annotation
=
field
.
getAnnotation
(
FieldDescription
.
class
);
String
description
=
annotation
.
value
();
field
.
setAccessible
(
true
);
try
{
// 获取字段的值
Object
value
=
field
.
get
(
myObj
);
// 写入字段名和值到 JSON
jsonGenerator
.
writeFieldName
(
field
.
getName
());
jsonGenerator
.
writeObject
(
value
);
// 写入描述字段名和描述值到 JSON
jsonGenerator
.
writeFieldName
(
field
.
getName
()
+
"Description"
);
jsonGenerator
.
writeString
(
description
);
}
catch
(
IllegalAccessException
e
)
{
e
.
printStackTrace
();
}
}
}
jsonGenerator
.
writeEndObject
();
}
}
public
class
JsonSerializationExample
{
public
static
void
main
(
String
[]
args
)
throws
IOException
{
MyClass
myObj
=
new
MyClass
();
myObj
.
setMyIntField
(
10
);
myObj
.
setAnotherIntField
(
20
);
ObjectMapper
mapper
=
new
ObjectMapper
();
SimpleModule
module
=
new
SimpleModule
();
module
.
addSerializer
(
MyClass
.
class
,
new
FieldDescriptionSerializer
());
mapper
.
registerModule
(
module
);
String
json
=
mapper
.
writeValueAsString
(
myObj
);
System
.
out
.
println
(
json
);
}
}
\ No newline at end of file
\ No newline at end of file
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment