This commit is contained in:
fangming,xu 2025-04-15 15:25:08 +08:00
commit 69f87d4385
564 changed files with 62392 additions and 0 deletions
.idea
README.md
nxgx-commons
nxgx-ifsm-base

8
.idea/.gitignore generated vendored Normal file

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

15
.idea/compiler.xml generated Normal file

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="nxgx-ifsm-base" />
<module name="nxgx-commons" />
</profile>
</annotationProcessing>
</component>
</project>

10
.idea/encodings.xml generated Normal file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/nxgx-commons/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/nxgx-ifsm-base/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/nxgx-ifsm-base/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

9
.idea/ifsm-base.iml generated Normal file

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

@ -0,0 +1,7 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="SpringJavaConstructorAutowiringInspection" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="SpringJavaInjectionPointsAutowiringInspection" enabled="false" level="ERROR" enabled_by_default="false" />
</profile>
</component>

55
.idea/jarRepositories.xml generated Normal file

@ -0,0 +1,55 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="nexus-rootcloud" />
<option name="name" value="nexus-rootcloud" />
<option name="url" value="http://nexus.irootechapp.com/repository/maven-public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="http://maven.aliyun.com/nexus/content/groups/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="jitpack.io" />
<option name="name" value="jitpack.io" />
<option name="url" value="https://jitpack.io" />
</remote-repository>
<remote-repository>
<option name="id" value="jitpack.io" />
<option name="name" value="jitpack.io" />
<option name="url" value="http://maven.aliyun.com/nexus/content/groups/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="nexus-aliyun" />
<option name="name" value="nexus-aliyun" />
<option name="url" value="http://maven.aliyun.com/nexus/content/groups/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="http://maven.aliyun.com/nexus/content/groups/public" />
</remote-repository>
<remote-repository>
<option name="id" value="jitpack.io" />
<option name="name" value="jitpack.io" />
<option name="url" value="http://maven.aliyun.com/nexus/content/groups/public" />
</remote-repository>
</component>
</project>

12
.idea/misc.xml generated Normal file

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK" />
</project>

8
.idea/modules.xml generated Normal file

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/ifsm-base.iml" filepath="$PROJECT_DIR$/.idea/ifsm-base.iml" />
</modules>
</component>
</project>

6
.idea/vcs.xml generated Normal file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>

92
README.md Normal file

@ -0,0 +1,92 @@
# gongxiang_service
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin http://119.3.165.210:8100/gitlab-instance-cbcb2114/gongxiang_service.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](http://119.3.165.210:8100/gitlab-instance-cbcb2114/gongxiang_service/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

31
nxgx-commons/pom.xml Normal file

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>Brussels-SR6</version>
<relativePath />
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<groupId>com.rootcloud</groupId>
<artifactId>nxgx-commons</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,10 @@
package com.rootcloud.utils;
import java.util.HashMap;
public class HashMapChain<K, V> extends HashMap<K, V> {
public HashMapChain putChain(K key, V value) {
super.put(key, value);
return this;
}
}

@ -0,0 +1,152 @@
package com.rootcloud.utils;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class JEUuidUtil {
final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z'};
final static Map<Character, Integer> digitMap = new HashMap<Character, Integer>();
static {
for (int i = 0; i < digits.length; i++) {
digitMap.put(digits[i], (int) i);
}
}
/**
* 支持的最大进制数
*/
public static final int MAX_RADIX = digits.length;
/**
* 支持的最小进制数
*/
public static final int MIN_RADIX = 2;
/**
* 将长整型数值转换为指定的进制数最大支持62进制字母数字已经用尽
*/
public static String toString(long i, int radix) {
if (radix < MIN_RADIX || radix > MAX_RADIX)
radix = 10;
if (radix == 10)
return Long.toString(i);
final int size = 65;
int charPos = 64;
char[] buf = new char[size];
boolean negative = (i < 0);
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = digits[(int) (-(i % radix))];
i = i / radix;
}
buf[charPos] = digits[(int) (-i)];
if (negative) {
buf[--charPos] = '-';
}
return new String(buf, charPos, (size - charPos));
}
static NumberFormatException forInputString(String s) {
return new NumberFormatException("For input string: \"" + s + "\"");
}
/**
* 将字符串转换为长整型数字
*
* @param s 数字字符串
* @param radix 进制数
*/
public static long toNumber(String s, int radix) {
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < MIN_RADIX) {
throw new NumberFormatException("radix " + radix
+ " less than Numbers.MIN_RADIX");
}
if (radix > MAX_RADIX) {
throw new NumberFormatException("radix " + radix
+ " greater than Numbers.MAX_RADIX");
}
long result = 0;
boolean negative = false;
int i = 0, len = s.length();
long limit = -Long.MAX_VALUE;
long multmin;
Integer digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') {
if (firstChar == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (firstChar != '+')
throw forInputString(s);
if (len == 1) {
throw forInputString(s);
}
i++;
}
multmin = limit / radix;
while (i < len) {
digit = digitMap.get(s.charAt(i++));
if (digit == null) {
throw forInputString(s);
}
if (digit < 0) {
throw forInputString(s);
}
if (result < multmin) {
throw forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw forInputString(s);
}
result -= digit;
}
} else {
throw forInputString(s);
}
return negative ? result : -result;
}
private static String digits(long val, int digits) {
long hi = 1L << (digits * 4);
return toString(hi | (val & (hi - 1)), MAX_RADIX).substring(1);
}
/**
* 以62进制字母加数字生成19位UUID最短的UUID
*/
public static String uuid() {
UUID uuid = UUID.randomUUID();
StringBuilder sb = new StringBuilder();
sb.append(digits(uuid.getMostSignificantBits() >> 32, 8));
sb.append(digits(uuid.getMostSignificantBits() >> 16, 4));
sb.append(digits(uuid.getMostSignificantBits(), 4));
sb.append(digits(uuid.getLeastSignificantBits() >> 48, 4));
sb.append(digits(uuid.getLeastSignificantBits(), 12));
return sb.toString();
}
}

@ -0,0 +1,74 @@
package com.rootcloud.utils;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;
/**
* jdk8 时间API
*
* @author leilei.zang
* @date 2021-09-13 11:27
*/
public class LocalDateUtils {
public static final String YYYY_MM_DD = "yyyy-MM-dd";
public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYY_MM_DD_HH_MM_SS_SSS = "yyyyMMddhhmmssSSS";
//格式化date
public static String formatDate(Date date) {
if (Objects.isNull(date)) {
return null;
}
LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
return localDateTime.format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
}
//格式化date
public static String formatDate(Date date, String formatter) {
if (Objects.isNull(date)) {
return null;
}
return formatDate(date.toInstant(), formatter);
}
//格式化instant
public static String formatDate(Instant instant) {
if (Objects.isNull(instant)) {
return null;
}
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
return localDateTime.format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
}
//格式化instant
public static String formatDate(Instant instant, String formatter) {
if (Objects.isNull(instant)) {
return null;
}
LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
if (StringUtil.isNotBlank(formatter)) {
return localDateTime.format(DateTimeFormatter.ofPattern(formatter));
}
return localDateTime.format(DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
}
//获取当前时间
public static String now(String format) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
LocalDateTime now = LocalDateTime.now();
return now.format(dateTimeFormatter);
}
//获取当前时间
public static String now() {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS);
LocalDateTime now = LocalDateTime.now();
return now.format(dateTimeFormatter);
}
}

@ -0,0 +1,6 @@
package com.rootcloud.utils;
public interface Person {
void giveMoney();
}

@ -0,0 +1,33 @@
package com.rootcloud.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 在非spring管理的类中获取spring注册的bean
* @author lujiahao
* @date 2019-05-22 14:25
*/
@Component
public class SpringBeanUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
if (applicationContext == null) {
applicationContext = context;
}
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
}

@ -0,0 +1,86 @@
package com.rootcloud.utils;
import org.apache.commons.lang3.StringUtils;
import java.util.regex.Pattern;
public class StringUtil extends StringUtils {
private static final String[] specialWordArr = {"\\", "$", "(", ")", "*", "+", ".", "[", "]", "?", "^", "{", "}", "|"};
private static String regexPrefix = "^.*";
private static String regexSuffix = ".*$";
public static final String comma = ":";
//fixed by: yangnenghao / date: 2021/4/19 / 导入null
//override String.valueOf()
public static String valueOf(Object obj) {
return (obj == null) ? "" : obj.toString();
}
/**
* 转义特殊字符
*
* @param keyword
* @return java.lang.String
* @date 2021-02-18 16:59
*/
public static String escapeExprSpecialWordStr(String keyword) {
if (isNotBlank(keyword)) {
for (String key : specialWordArr) {
if (keyword.contains(key)) keyword = keyword.replace(key, "\\" + key);
}
}
return keyword;
}
/**
* 转义特殊字符,并编译
*
* @param keyword
* @return java.util.regex.Patternl
* @date 2021-02-18 16:59
*/
public static Pattern escapeExprSpecialWord(String keyword) {
return Pattern.compile(regexPrefix + escapeExprSpecialWordStr(keyword) + regexSuffix, Pattern.CASE_INSENSITIVE);
}
/**
* 转义特殊字符,自定义编译
*
* @param keyword
* @param pattern
* @return java.util.regex.Pattern
* @date 2021-02-19 15:53
*/
public static Pattern escapeExprSpecialWord(String keyword, Integer pattern) {
if (null != pattern)
return Pattern.compile(regexPrefix + escapeExprSpecialWordStr(keyword) + regexSuffix, pattern);
return escapeExprSpecialWord(keyword);
}
/**
* 对老代码使用String.valueOf()的null过滤处理
* 新代码建议使用重写的StringUtil.valueOf()
*
* @param value
* @return boolean
* @author leilei.zang
* @date 2021-08-17 10:37
*/
public static boolean isNotBlank(String value) {
return StringUtils.isNotBlank(value) && !"null".equals(value);
}
/**
* 配合Optional使用,按需使用
*
* @param value
* @return java.lang.String
* @author leilei.zang
* @date 2021-10-12 10:49
*/
public static String values(String value) {
return StringUtil.isNotBlank(value) ? value : null;
}
}

@ -0,0 +1,18 @@
package com.rootcloud.utils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class StuInvocationHandler<T> implements InvocationHandler {
T taget;
public StuInvocationHandler(T taget) {
this.taget = taget;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return method.invoke(taget, args);
}
}

@ -0,0 +1,19 @@
package com.rootcloud.utils;
public class Student implements Person {
private String name;
@Override
public void giveMoney() {
System.out.println(name + "缴费了");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

@ -0,0 +1,30 @@
package com.rootcloud.utils;
import java.lang.reflect.Proxy;
public class StudentProxy implements Person {
private Student student;
public StudentProxy(Person person) {
this.student = (Student) person;
}
@Override
public void giveMoney() {
this.student.giveMoney();
}
public static void main(String [] args){
Student student = new Student();
student.setName("张三");
StudentProxy studentProxy = new StudentProxy(student);
studentProxy.giveMoney();
Person person =(Person)Proxy.newProxyInstance(Person.class.getClassLoader(),new Class<?>[]{Person.class},new StuInvocationHandler<Person>(student));
person.giveMoney();
}
}

Binary file not shown.

Binary file not shown.

@ -0,0 +1,5 @@
#Generated by Apache Maven
#Mon Apr 14 12:01:34 CST 2025
version=Brussels-SR6
groupId=com.rootcloud
artifactId=nxgx-commons

@ -0,0 +1,9 @@
com\rootcloud\utils\Student.class
com\rootcloud\utils\StringUtil.class
com\rootcloud\utils\StuInvocationHandler.class
com\rootcloud\utils\HashMapChain.class
com\rootcloud\utils\LocalDateUtils.class
com\rootcloud\utils\SpringBeanUtils.class
com\rootcloud\utils\JEUuidUtil.class
com\rootcloud\utils\Person.class
com\rootcloud\utils\StudentProxy.class

@ -0,0 +1,9 @@
F:\Documents\WeChat Files\wxid_g25i3132av9k22\FileStorage\File\2025-03\gongxiang_service\gongxiang_service\nxgx-commons\src\main\java\com\rootcloud\utils\Student.java
F:\Documents\WeChat Files\wxid_g25i3132av9k22\FileStorage\File\2025-03\gongxiang_service\gongxiang_service\nxgx-commons\src\main\java\com\rootcloud\utils\StuInvocationHandler.java
F:\Documents\WeChat Files\wxid_g25i3132av9k22\FileStorage\File\2025-03\gongxiang_service\gongxiang_service\nxgx-commons\src\main\java\com\rootcloud\utils\StringUtil.java
F:\Documents\WeChat Files\wxid_g25i3132av9k22\FileStorage\File\2025-03\gongxiang_service\gongxiang_service\nxgx-commons\src\main\java\com\rootcloud\utils\HashMapChain.java
F:\Documents\WeChat Files\wxid_g25i3132av9k22\FileStorage\File\2025-03\gongxiang_service\gongxiang_service\nxgx-commons\src\main\java\com\rootcloud\utils\JEUuidUtil.java
F:\Documents\WeChat Files\wxid_g25i3132av9k22\FileStorage\File\2025-03\gongxiang_service\gongxiang_service\nxgx-commons\src\main\java\com\rootcloud\utils\SpringBeanUtils.java
F:\Documents\WeChat Files\wxid_g25i3132av9k22\FileStorage\File\2025-03\gongxiang_service\gongxiang_service\nxgx-commons\src\main\java\com\rootcloud\utils\LocalDateUtils.java
F:\Documents\WeChat Files\wxid_g25i3132av9k22\FileStorage\File\2025-03\gongxiang_service\gongxiang_service\nxgx-commons\src\main\java\com\rootcloud\utils\StudentProxy.java
F:\Documents\WeChat Files\wxid_g25i3132av9k22\FileStorage\File\2025-03\gongxiang_service\gongxiang_service\nxgx-commons\src\main\java\com\rootcloud\utils\Person.java

Binary file not shown.

149
nxgx-ifsm-base/.gitignore vendored Normal file

@ -0,0 +1,149 @@
######################
# Project Specific
######################
/target/www/**
/src/test/javascript/coverage/
/src/test/javascript/PhantomJS*/
######################
# Node
######################
/node/
node_tmp/
node_modules/
npm-debug.log.*
/.awcache/*
######################
# SASS
######################
.sass-cache/
/*.jh
/*.png
######################
# Eclipse
######################
*.pydevproject
.project
.metadata
tmp/
tmp/**/*
*.tmp
*.bak
*.swp
*~.nib
local.properties
.classpath
.settings/
.loadpath
.factorypath
/src/main/resources/rebel.xml
# External tool builders
.externalToolBuilders/**
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# PDT-specific
.buildpath
######################
# Intellij
######################
.idea/
*.iml
*.iws
*.ipr
*.ids
*.orig
classes/
######################
# Visual Studio Code
######################
.vscode/
######################
# Maven
######################
/log/
/target/
######################
# Gradle
######################
.gradle/
/build/
######################
# Package Files
######################
*.jar
*.war
*.ear
*.db
######################
# Windows
######################
# Windows image file caches
Thumbs.db
# Folder config file
Desktop.ini
######################
# Mac OSX
######################
.DS_Store
.svn
# Thumbnails
._*
# Files that might appear on external disk
.Spotlight-V100
.Trashes
######################
# Directories
######################
/bin/
/deploy/
######################
# Logs
######################
*.log*
######################
# Others
######################
*.class
*.*~
*~
.merge_file*
######################
# Gradle Wrapper
######################
!gradle/wrapper/gradle-wrapper.jar
######################
# Maven Wrapper
######################
!.mvn/wrapper/maven-wrapper.jar
######################
# ESLint
######################
.eslintcache
yarn.lock
/.apt_generated/

305
nxgx-ifsm-base/pom.xml Normal file

@ -0,0 +1,305 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>nxgx-base</artifactId>
<groupId>com.rootcloud</groupId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nxgx-ifsm-base</artifactId>
<properties>
<resilience4jVersion>1.3.0</resilience4jVersion>
</properties>
<dependencies>
<dependency>
<groupId>com.gexin.platform</groupId>
<artifactId>gexin-rp-sdk-http</artifactId>
<version>4.1.2.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>1.4</version>
</dependency>
<!-- json -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>com.cookingfox</groupId>
<artifactId>guava-preconditions</artifactId>
<version>0.1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
<!-- 复制 父项目中依赖,不复制 下载不下来 jar -->
<!--<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot-starter.version}</version>
</dependency>-->
<dependency>
<groupId>com.ejlchina</groupId>
<artifactId>httputils</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!--
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>${mybatis-plus.version}</version>
<exclusions>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>${pagehelper.version}</version>
<exclusions>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</exclusion>
<exclusion>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.taobao.arthas</groupId>-->
<!-- <artifactId>arthas-spring-boot-starter</artifactId>-->
<!-- <version>${arthas-spring-boot-starter.version}</version>-->
<!-- </dependency>-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>${swagger2.version}</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.4.1.Final</version>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.4.1.Final</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- nacos -->
<!-- <dependency>-->
<!-- <groupId>org.apache.dubbo</groupId>-->
<!-- <artifactId>dubbo-registry-nacos</artifactId>-->
<!-- <version>2.7.8</version>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>com.alibaba.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.6.28</version>
<scope>test</scope>
</dependency>
<!-- Groovy-->
<!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>3.0.7</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>com.rootcloud</groupId>
<artifactId>apiconnector-engine</artifactId>
<version>0.0.2-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>eu.bitwalker</groupId>
<artifactId>UserAgentUtils</artifactId>
<version>1.21</version>
</dependency>
<!--RabbitMq-->
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.3</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-poi</artifactId>
<version>4.6.6</version>
</dependency>
<!-- Excel POI插件 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.getui.push/restful-sdk -->
<dependency>
<groupId>com.getui.push</groupId>
<artifactId>restful-sdk</artifactId>
<version>1.0.0.14</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
</project>

@ -0,0 +1,6 @@
FROM private-registry.rootcloud.com/devops/jdk-11-dd:latest
VOLUME /tmp
ADD *.jar /data/app.jar
WORKDIR /data
ENV JAVA_OPTS="-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom -Duser.timezone=Asia/Shanghai"
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -jar /data/app.jar" ]

@ -0,0 +1,56 @@
package com.rootcloud;
import com.rootcloud.common.constant.TemplateConstant;
import com.rootcloud.domain.dao.ConfigDao;
import com.rootcloud.domain.vo.ConfigVO;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.oas.annotations.EnableOpenApi;
import java.util.List;
@EnableScheduling //扫描定时器
@EnableOpenApi
@MapperScan({"com.rootcloud.domain.*.*","com.rootcloud.domain.*"})
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
public class NXGXBaseApp implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(NXGXBaseApp.class);
public static void main(String[] args) {
SpringApplication app = new SpringApplication(NXGXBaseApp.class);
app.run(args);
}
@Override
public void run(String... args) throws Exception {
initData();
}
@Autowired
private ConfigDao configDao;
@Autowired
private RedisTemplate redisTemplate;
private void initData(){
List<ConfigVO> zhidTableList= configDao.listTable_zhid();
for (ConfigVO ztable:zhidTableList) {
redisTemplate.opsForValue().set(TemplateConstant.NXGX_ZH_SPLIT_TABLES+ztable.getName(),ztable.getValue());
}
List<ConfigVO> szhidTableList= configDao.listTable_syzhid();
for (ConfigVO ztable:szhidTableList) {
redisTemplate.opsForValue().set(TemplateConstant.NXGX_ZH_SPLIT_TABLES+ztable.getName(),ztable.getValue());
}
}
}

@ -0,0 +1,42 @@
package com.rootcloud.common;
import java.security.MessageDigest;
public class CheckSumBuilder {
// 计算并获取CheckSum
public static String getCheckSum(String appSecret, String nonce, String curTime) {
return encode("sha1", appSecret + nonce + curTime);
}
// 计算并获取md5值
public static String getMD5(String requestBody) {
return encode("md5", requestBody);
}
private static String encode(String algorithm, String value) {
if (value == null) {
return null;
}
try {
MessageDigest messageDigest
= MessageDigest.getInstance(algorithm);
messageDigest.update(value.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}

@ -0,0 +1,84 @@
package com.rootcloud.common;
import com.rootcloud.common.vo.PrinterWorkBoxSize;
import java.util.HashMap;
import java.util.Map;
public class Constants {
/**
* 租户编号
*/
public static final String CONFIG_CODE_TENANT_ID = "printer_tenant_id";
/**以下尺寸为计算打印效率布图率的尺寸
*/
public static final Map<String, PrinterWorkBoxSize> PRINTER_WORK_BOX_SIZE_MAP = new HashMap<String, PrinterWorkBoxSize>(16) {
{
// put("2215", new PrinterWorkBoxSize().length(22F).width(15F).height(7F));
// put("2218", new PrinterWorkBoxSize().length(22F).width(18F).height(7F));
// put("2515", new PrinterWorkBoxSize().length(25F).width(15F).height(7F));
// put("2518", new PrinterWorkBoxSize().length(25F).width(18F).height(7F));
// put("1800", new PrinterWorkBoxSize().length(18F).width(11F).height(7F));//12F
// put("Max", new PrinterWorkBoxSize().length(18F).width(10F).height(7F));
// put("SDream", new PrinterWorkBoxSize().length(22F).width(12F).height(7.2F));
// put("800", new PrinterWorkBoxSize().length(8F).width(5F).height(4F));
// put("1000", new PrinterWorkBoxSize().length(10F).width(6F).height(5F));
// put("2600", new PrinterWorkBoxSize().length(26F).width(20F).height(10F));
//
// put("2600B", new PrinterWorkBoxSize().length(25F).width(23.5F).height(10F));//24F
// put("2500", new PrinterWorkBoxSize().length(25.24F).width(15.60F).height(10F)); //25F 15F 改为25.24F 15.60F
// put("300", new PrinterWorkBoxSize().length(3F).width(2F).height(10F));
// put("1800E", new PrinterWorkBoxSize().length(18F).width(10F).height(7F));
// put("1200", new PrinterWorkBoxSize().length(12F).width(12F).height(3.5F));
//1200机型参数
//2022-03-02 修改1800Max的长宽参数
put("2215", new PrinterWorkBoxSize().length(22F).width(15F).height(7F));
put("2218", new PrinterWorkBoxSize().length(22F).width(18F).height(7F));
put("2515", new PrinterWorkBoxSize().length(25F).width(15F).height(7F));
put("2518", new PrinterWorkBoxSize().length(25F).width(18F).height(7F));
put("1800", new PrinterWorkBoxSize().length(17.3F).width(10.5F).height(7F));//18f 改为 17.3F 11F改为10.5F
put("Max", new PrinterWorkBoxSize().length(17.3F).width(10F).height(7F)); //18f 改为 17.3F
put("SDream", new PrinterWorkBoxSize().length(22F).width(12F).height(7.2F));
put("800", new PrinterWorkBoxSize().length(8F).width(5F).height(4F));
put("1000", new PrinterWorkBoxSize().length(10F).width(6F).height(5F));
put("2600", new PrinterWorkBoxSize().length(26F).width(20F).height(10F));
put("2600B", new PrinterWorkBoxSize().length(25F).width(23.5F).height(10F));//24F
put("2500", new PrinterWorkBoxSize().length(25.24F).width(15.60F).height(10F)); //25F 15F 改为25.24F 15.60F
put("300", new PrinterWorkBoxSize().length(3F).width(2F).height(10F));
put("1800E", new PrinterWorkBoxSize().length(18F).width(10F).height(7F));
put("1200", new PrinterWorkBoxSize().length(12F).width(12F).height(3.5F));
}
};
/**
* 以下尺寸为运维报告中计算砂利用率的尺寸
*/
public static final Map<String, PrinterWorkBoxSize> PRINTER_WORK_BOX_SIZE_MAP_slyl = new HashMap<String, PrinterWorkBoxSize>(16) {
{
put("2215", new PrinterWorkBoxSize().length(22.6F).width(15.6F).height(7F));
put("2218", new PrinterWorkBoxSize().length(22.6F).width(18.6F).height(7F));
put("2515", new PrinterWorkBoxSize().length(25.6F).width(15.6F).height(7F));
put("2518", new PrinterWorkBoxSize().length(25.6F).width(18.6F).height(7F));
put("1800", new PrinterWorkBoxSize().length(18.6F).width(12F).height(7F));//12.6
put("Max", new PrinterWorkBoxSize().length(18.6F).width(10.6F).height(7F));
put("SDream", new PrinterWorkBoxSize().length(22.6F).width(12.6F).height(7.2F));
put("800", new PrinterWorkBoxSize().length(8.4F).width(5.4F).height(4F));
put("1000", new PrinterWorkBoxSize().length(10.4F).width(6.4F).height(5F));
put("2600", new PrinterWorkBoxSize().length(27.1F).width(20.6F).height(10F));
put("300", new PrinterWorkBoxSize().length(3.2F).width(2.2F).height(10F));
put("2500", new PrinterWorkBoxSize().length(25.24F).width(15.6F).height(10F));
put("2600B", new PrinterWorkBoxSize().length(25.6F).width(24.1F).height(10F));
put("1800E", new PrinterWorkBoxSize().length(18.6F).width(10.6F).height(10F));
put("1200", new PrinterWorkBoxSize().length(12F).width(12F).height(3.5F));
//1200机型参数
}
};
}

@ -0,0 +1,77 @@
package com.rootcloud.common;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
/**
* @author LiPingAn 2022/1/4 14:53
* @version 1.0
**/
public class DESUtil {
private static final String KEY = "cf410f8f9a4a42cc7a7f48fc4134e8f9";
private static final String KEY_ALGORITHM = "DESede";
private static final String DEFAULT_CIPHER_ALGORITHM = "DESede/ECB/PKCS5Padding";// 默认的加密算法
/**
* DESede 加密操作
* @param content 待加密内容
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
// 创建密码器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey());
// 初始化为加密模式的密码器
byte[] result = cipher.doFinal(byteContent);// 加密
return Base64.encodeBase64String(result);// 通过Base64转码返回
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* } } DESede 解密操作
*
* @param content
* @return
*/
public static String decrypt(String content) {
try {
// 实例化
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM); // 使用密钥初始化设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, getSecretKey()); // 执行操作
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, "utf-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* }
* 生成秘钥
* @return
*/
private static SecretKey getSecretKey() {
//返回生成指定算法密钥生成器的KeyGenerator 对象
try {
// --解密的key
final DESedeKeySpec dks = new DESedeKeySpec(KEY.getBytes("UTF-8"));
final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
final SecretKey securekey = keyFactory.generateSecret(dks);
return securekey;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}

@ -0,0 +1,992 @@
package com.rootcloud.common;
import jline.internal.Log;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* @ClassName DateUtil
* @Description TODO
* @Author w-liuyi01
* @Date 2022/4/22 10:49
* @Version 1.0
*/
public class DateUtil {
// Grace style
public static final String PATTERN_GRACE = "yyyy/MM/dd HH:mm:ss";
public static final String PATTERN_GRACE_NORMAL = "yyyy/MM/dd HH:mm";
public static final String PATTERN_GRACE_SIMPLE = "yyyy/MM/dd";// Classical style
public static final String PATTERN_CLASSICAL = "yyyy-MM-dd HH:mm:ss";
public static final String PATTERN_CLASSICAL_ISO = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
public static final String PATTERN_CLASSICAL_ISO_SIMPLE = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String PATTERN_CLASSICAL_NORMAL = "yyyy-MM-dd HH:mm";
public static final String PATTERN_CLASSICAL_SIMPLE = "yyyy-MM-dd";
//CH style
public static final String PATTERN_CH = "yyyy年MM月dd日 HH时mm分ss秒";
public static final String PATTERN_CH_NORMAL = "yyyy年MM月dd日 HH时mm分";
public static final String PATTERN_CH_SIMPLE = "yyyy年MM月dd日";
public static final String PATTERN_MMDD_SIMPLE = "MM-dd";
//把标准世界时转换为北京时间
public static String UTCtoBeijing(String Timestamp_Local)
{
//先去掉格式
Timestamp_Local = DateUtil.reverseHandlerTime(Timestamp_Local);
//转换为北京时间
LocalDateTime date = LocalDateTime.parse(Timestamp_Local, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).plusHours(8);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatedDateStr = date.format(formatter);
return formatedDateStr;
}
public static String UTCtoBeijing_1(String Timestamp_Local)
{
//先去掉格式
Timestamp_Local = DateUtil.reverseHandlerTime_1(Timestamp_Local);
//转换为北京时间
LocalDateTime date = LocalDateTime.parse(Timestamp_Local, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).plusHours(8);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatedDateStr = date.format(formatter);
return formatedDateStr;
}
// 获取当前时间
public static String getCurrentTime(){
Calendar calendar= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat(PATTERN_CLASSICAL);
return dateFormat.format(calendar.getTime());
}
/**
* @Author w-liuyi01
* @Description //带时区的时间格式处理
* @Date 2022/4/22 10:55
* @Param [time]
* @return java.lang.String
**/
public static String handlerTime(String time) {
Date date = null;
try {
date = new SimpleDateFormat(PATTERN_CLASSICAL).parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
//国际时间格式转换东八区-8小时
// calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)-8);
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_CLASSICAL_ISO);
//format将Date型转换为String型parse将String型转换为Date型
String UTCDate = sdf.format(calendar.getTime());
return UTCDate;
}
public static String handlerTimeNoUTC(String time,int timeZone) {
Date date = null;
try {
date = new SimpleDateFormat(PATTERN_CLASSICAL_ISO).parse(time);
} catch (ParseException e) {
try {
date = new SimpleDateFormat(PATTERN_CLASSICAL_ISO_SIMPLE).parse(time);
}catch (ParseException ex) {
e.printStackTrace();
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
//国际时间格式转换东八区-8小时
calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR) + timeZone);
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_CLASSICAL);
//format将Date型转换为String型parse将String型转换为Date型
String UTCDate = sdf.format(calendar.getTime());
return UTCDate;
}
/**
* @Author w-lxf
* @Description 根据string日期获取时间戳
* @return
*/
public static Long getTimesByString(String time){
Long result = 0l;
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_CLASSICAL);
// SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_CLASSICAL_ISO);//yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
// 设置时区为CST中国标准时区
// sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
try {
Date date = sdf.parse(time);
result = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* 根据string日期格式yyyy-MM-dd'T'HH:mm:ss.SSS'Z'转化为long型时间戳
* @param time 日期格式yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
* @return
*/
public static Long timeStringToLong(String time){
Long result = 0l;
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_CLASSICAL_ISO);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
try {
Date date = sdf.parse(time);
result = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
public static Long getTimesByStringType(String time){
Long result = 0l;
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_CLASSICAL);
if (time.contains("Z")){
sdf = new SimpleDateFormat(PATTERN_CLASSICAL_ISO);
}
try {
Date date = sdf.parse(time);
result = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
/**
* 计算两个字符串时间相差天数
* @param date1
* @param date2
* @return
*/
public static float dayDiff(String date1,String date2) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
Date old = sdf.parse(date1);
calendar.setTime(old);
Long oTime = calendar.getTimeInMillis();
Date now = sdf.parse(date2);
calendar.setTime(now);
Long nTime = calendar.getTimeInMillis();
return (nTime - oTime)/(3600F * 1000 * 24);
}
/**
* UCT时间转换成北京时间
* @param time
* @return
*/
public static String getDateByUct(String time){
String result = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date uctDate = null;
try {
//处理平台的utc时间格式统一为yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
String subTime = time.substring(time.indexOf(".")+1,time.length());
String fillTime = "";
if(subTime.length()<4){
time = time.substring(0,time.indexOf(".")+1);
for(int i=0;i<4-subTime.length();i++){
fillTime+="0";
}
time = time+fillTime+subTime;
}
uctDate = sdf.parse(time);
Calendar calendar = Calendar.getInstance();
calendar.setTime(uctDate);
//20220830时间不对去掉+8小时的逻辑
// calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)+8);
// calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR));
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result = simpleDateFormat.format(calendar.getTime());
} catch (ParseException e) {
Log.error("时间转换异常:"+e.getMessage());
//e.printStackTrace();
}
return result;
}
public static String reverseHandlerTimeByType(String time) {
Date date = null;
try {
if (time.contains("Z")){
time = time.replace("Z", " UTC");
date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z").parse(time);
}else{
date = new SimpleDateFormat(PATTERN_CLASSICAL).parse(time);
}
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_CLASSICAL);
//format将Date型转换为String型parse将String型转换为Date型
String UTCDate = sdf.format(date);
return UTCDate;
}
public static String reverseHandlerTime(String time) {
Date date = null;
try {
date = new SimpleDateFormat(PATTERN_CLASSICAL_ISO).parse(time);
} catch (ParseException e) {
try {
date = new SimpleDateFormat(PATTERN_CLASSICAL_ISO_SIMPLE).parse(time);
} catch (ParseException ex) {
ex.printStackTrace();
}
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
//国际时间格式转换东八区+8小时
calendar.set(Calendar.HOUR,calendar.get(Calendar.HOUR)+8);
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_CLASSICAL);
//format将Date型转换为String型parse将String型转换为Date型
String UTCDate = sdf.format(calendar.getTime());
return UTCDate;
}
public static String reverseHandlerTime_1(String time) {
Date date = null;
try {
if(time.length()<= 20)
{
time = time.replace('Z','.')+"000Z"; //2022-05-17T13:15:48Z 2022-05-14T15:00:15Z
date = new SimpleDateFormat(PATTERN_CLASSICAL_ISO).parse(time);
}
else
date = new SimpleDateFormat(PATTERN_CLASSICAL_ISO).parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_CLASSICAL);
//format将Date型转换为String型parse将String型转换为Date型
String UTCDate = sdf.format(date);
return UTCDate;
}
/**
* 根据默认格式将指定字符串解析成日期
*
* @param str
* 指定字符串
* @return 返回解析后的日期
*/
public static Date parse(String str) {
return parse(str, PATTERN_CLASSICAL);
}/**
* 根据指定格式将指定字符串解析成日期
*
* @param str
* 指定日期
* @param pattern
* 指定格式
* @return 返回解析后的日期
*/
public static Date parse(String str, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
try {
return sdf.parse(str);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}/**
* 根据默认格式将日期转格式化成字符串
*
* @param date
* 指定日期
* @return 返回格式化后的字符串
*/
public static String format(Date date) {
return format(date, PATTERN_CLASSICAL);
}
/**
* 根据默认格式将日期转格式化成字符串
*
* @param date
* 指定日期
* @return 返回格式化后的字符串
*/
public static String formatForDate(Date date) {
return format(date, PATTERN_CLASSICAL_SIMPLE);
}
/**
* 根据指定格式将指定日期格式化成字符串
*
* @param date
* 指定日期
* @param pattern
* 指定格式
* @return 返回格式化后的字符串
*/
public static String format(Date date, String pattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
return sdf.format(date);
}/**
* 获取时间date1与date2相差的秒数
*
* @param date1
* 起始时间
* @param date2
* 结束时间
* @return 返回相差的秒数
*/
public static int getOffsetSeconds(Date date1, Date date2) {
int seconds = (int) ((date2.getTime() - date1.getTime()) / 1000);
return seconds;
}/**
* 获取时间date1与date2相差的分钟数
*
* @param date1
* 起始时间
* @param date2
* 结束时间
* @return 返回相差的分钟数
*/
public static int getOffsetMinutes(Date date1, Date date2) {
return getOffsetSeconds(date1, date2) / 60;
}/**
* 获取时间date1与date2相差的小时数
*
* @param date1
* 起始时间
* @param date2
* 结束时间
* @return 返回相差的小时数
*/
public static int getOffsetHours(Date date1, Date date2) {
return getOffsetMinutes(date1, date2) / 60;
}/**
* 获取时间date1与date2相差的天数数
*
* @param date1
* 起始时间
* @param date2
* 结束时间
* @return 返回相差的天数
*/
public static int getOffsetDays(Date date1, Date date2) {
return getOffsetHours(date1, date2) / 24;
}/**
* 获取时间date1与date2相差的周数
*
* @param date1
* 起始时间
* @param date2
* 结束时间
* @return 返回相差的周数
*/
public static int getOffsetWeeks(Date date1, Date date2) {
return getOffsetDays(date1, date2) / 7;
}/**
* 获取重置指定日期的时分秒后的时间
*
* @param date
* 指定日期
* @param hour
* 指定小时
* @param minute
* 指定分钟
* @param second
* 指定秒
* @return 返回重置时分秒后的时间
*/
public static Date getResetTime(Date date, int hour, int minute, int second) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.SECOND, minute);
cal.set(Calendar.MINUTE, second);
return cal.getTime();
}/**
* 返回指定日期的起始时间
*
* @param date
* 指定日期(例如2014-08-01)
* @return 返回起始时间(例如2014-08-01 00:00:00)
*/
public static Date getIntegralStartTime(Date date) {
return getResetTime(date, 0, 0, 0);
}/**
* 返回指定日期的结束时间
*
* @param date
* 指定日期(例如2014-08-01)
* @return 返回结束时间(例如2014-08-01 23:59:59)
*/
public static Date getIntegralEndTime(Date date) {
return getResetTime(date, 23, 59, 59);
}/**
* 获取指定日期累加年月日后的时间
*
* @param date
* 指定日期
* @param year
* 指定年数
* @param month
* 指定月数
* @param day
* 指定天数
* @return 返回累加年月日后的时间
*/
public static Date rollDate(Date date, int year, int month, int day) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
cal.add(Calendar.YEAR, year);
cal.add(Calendar.MONTH, month);
cal.add(Calendar.DAY_OF_MONTH, day);
return cal.getTime();
}/**
* 获取指定日期累加指定月数后的时间
*
* @param date
* 指定日期
* @param month
* 指定月数
* @return 返回累加月数后的时间
*/
public static Date rollMonth(Date date, int month) {
return rollDate(date, 0, month, 0);
}/**
* 获取指定日期累加指定天数后的时间
*
* @param date
* 指定日期
* @param day
* 指定天数
* @return 返回累加天数后的时间
*/
public static Date rollDay(Date date, int day) {
return rollDate(date, 0, 0, day);
}/**
* 计算指定日期所在月份的天数
*
* @param date
* 指定日期
* @return 返回所在月份的天数
*/
public static int getDayOfMonth(Date date) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
int dayOfMonth = cal.getActualMaximum(Calendar.DATE);
return dayOfMonth;
}/**
* 获取当月第一天的起始时间,例如2014-08-01 00:00:00
*
* @return 返回当月第一天的起始时间
*/
public static Date getMonthStartTime() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
return getIntegralStartTime(cal.getTime());
}/**
* 获取当月最后一天的结束时间,例如2014-08-31 23:59:59
*
* @return 返回当月最后一天的结束时间
*/
public static Date getMonthEndTime() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, getDayOfMonth(cal.getTime()));
return getIntegralEndTime(cal.getTime());
}/**
* 获取上个月第一天的起始时间,例如2014-07-01 00:00:00
*
* @return 返回上个月第一天的起始时间
*/
public static Date getLastMonthStartTime() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, 1);
return getIntegralStartTime(cal.getTime());
}/**
* 获取上个月最后一天的结束时间,例如2014-07-31 23:59:59
*
* @return 返回上个月最后一天的结束时间
*/
public static Date getLastMonthEndTime() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, getDayOfMonth(cal.getTime()));
return getIntegralEndTime(cal.getTime());
}/**
* 获取下个月第一天的起始时间,例如2014-09-01 00:00:00
*
* @return 返回下个月第一天的起始时间
*/
public static Date getNextMonthStartTime() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
return getIntegralStartTime(cal.getTime());
}/**
* 获取下个月最后一天的结束时间,例如2014-09-30 23:59:59
*
* @return 返回下个月最后一天的结束时间
*/
public static Date getNextMonthEndTime() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, getDayOfMonth(cal.getTime()));
return getIntegralEndTime(cal.getTime());
}/**
* 获取当前季度第一天的起始时间
*
* @return 返回当前季度第一天的起始时间
*/
public static Date getQuarterStartTime() {
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH);
if (month < 3) {
cal.set(Calendar.MONTH, 0);
} else if (month < 6) {
cal.set(Calendar.MONTH, 3);
} else if (month < 9) {
cal.set(Calendar.MONTH, 6);
} else {
cal.set(Calendar.MONTH, 9);
}
cal.set(Calendar.DAY_OF_MONTH, 1);
return getIntegralStartTime(cal.getTime());
}/**
* 获取当前季度最后一天的结束时间
*
* @return 返回当前季度最后一天的结束时间
*/
public static Date getQuarterEndTime() {
Calendar cal = Calendar.getInstance();
int month = cal.get(Calendar.MONTH);
if (month < 3) {
cal.set(Calendar.MONTH, 2);
} else if (month < 6) {
cal.set(Calendar.MONTH, 5);
} else if (month < 9) {
cal.set(Calendar.MONTH, 8);
} else {
cal.set(Calendar.MONTH, 11);
}
cal.set(Calendar.DAY_OF_MONTH, getDayOfMonth(cal.getTime()));
return getIntegralEndTime(cal.getTime());
}/**
* 获取前一个工作日
*
* @return 返回前一个工作日
*/
public static Date getPrevWorkday() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
cal.add(Calendar.DAY_OF_MONTH, -2);
}
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
return getIntegralStartTime(cal.getTime());
}/**
* 获取下一个工作日
*
* @return 返回下个工作日
*/
public static Date getNextWorkday() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 1);
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
cal.add(Calendar.DAY_OF_MONTH, 2);
}
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
cal.add(Calendar.DAY_OF_MONTH, 1);
}
return getIntegralStartTime(cal.getTime());
}/**
* 获取当周的第一个工作日
*
* @return 返回第一个工作日
*/
public static Date getFirstWorkday() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return getIntegralStartTime(cal.getTime());
}/**
* 获取当周的最后一个工作日
*
* @return 返回最后一个工作日
*/
public static Date getLastWorkday() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
return getIntegralStartTime(cal.getTime());
}/**
* 判断指定日期是否是工作日
*
* @param date
* 指定日期
* @return 如果是工作日返回true,否则返回false
*/
public static boolean isWorkday(Date date) {
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
return !(dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY);
}/**
* 获取指定日期是星期几
*
* @param date
* 指定日期
* @return 返回星期几的描述
*/
public static String getWeekdayDesc(Date date) {
final String[] weeks = new String[]{"星期日", "星期一", "星期二", "星期三", "星期四",
"星期五", "星期六"};
Calendar cal = Calendar.getInstance();
if (date != null) {
cal.setTime(date);
}
return weeks[cal.get(Calendar.DAY_OF_WEEK) - 1];
}/**
* 获取指定日期距离当前时间的时间差描述(如3小时前1天前)
*
* @param date
* 指定日期
* @return 返回时间差的描述
*/
public static String getTimeOffsetDesc(Date date) {
int seconds = getOffsetSeconds(date, new Date());
if (Math.abs(seconds) < 60) {
return Math.abs(seconds) + "" + (seconds > 0 ? "" : "");
}
int minutes = seconds / 60;
if (Math.abs(minutes) < 60) {
return Math.abs(minutes) + "分钟" + (minutes > 0 ? "" : "");
}
int hours = minutes / 60;
if (Math.abs(hours) < 60) {
return Math.abs(hours) + "小时" + (hours > 0 ? "" : "");
}
int days = hours / 24;
if (Math.abs(days) < 7) {
return Math.abs(days) + "" + (days > 0 ? "" : "");
}
int weeks = days / 7;
if (Math.abs(weeks) < 5) {
return Math.abs(weeks) + "" + (weeks > 0 ? "" : "");
}
int monthes = days / 30;
if (Math.abs(monthes) < 12) {
return Math.abs(monthes) + "个月" + (monthes > 0 ? "" : "");
}
int years = monthes / 12;
return Math.abs(years) + "" + (years > 0 ? "" : "");
}
/**
* 根据时间区间获取时间段的所有日期
* @param startTime
* @param endTime
* @return
*/
public static List<Date> getDates(Date startTime, Date endTime) {
startTime = getDateStart(startTime);
endTime = getDateStart(endTime);
List lDate = new ArrayList();
lDate.add(startTime);
Calendar calBegin = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calBegin.setTime(startTime);
Calendar calEnd = Calendar.getInstance();
// 使用给定的 Date 设置此 Calendar 的时间
calEnd.setTime(endTime);
// 测试此日期是否在指定日期之后
while (endTime.after(calBegin.getTime())){
// 根据日历的规则为给定的日历字段添加或减去指定的时间量
calBegin.add(Calendar.DAY_OF_MONTH, 1);
lDate.add(calBegin.getTime());
}
return lDate;
}
/**
* 获取指定日期的开始时间
* @param date
* @return
*/
public static Date getDateStart(Date date){
if(date == null){
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 获取指定日期的结束时间
* @return str
*/
public static Date getDateEnd(Date date){
if(date == null){
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 0);
return calendar.getTime();
}
/**
* 根据格式把date时间转为字符串
* @param date
* @param format
* @return
*/
public static String dateToString(Date date, String format){
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
public static Date stringToDate(String dateStr, String format) {
Date d = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
try {
dateFormat.setLenient(false);
d = dateFormat.parse(dateStr);
} catch (Exception e) {
d = null;
}
return d;
}
/**
* 时间戳转为date
* @param times
* @param format
* @return
*/
public static Date timestampToDate(Long times, String format){
Date date = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
String d = dateFormat.format(times);
date = dateFormat.parse(d);
}catch (Exception e){
date = null;
}
return date;
}
/**
* 时间戳转为date
* @param times
* @return
*/
public static Date timestampToDate(Long times){
Date date = null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String d = dateFormat.format(times);
date = dateFormat.parse(d);
}catch (Exception e){
date = null;
}
return date;
}
/**
* 获取指定小时
* @param date 时间
* @param hours 小时数
* @param minutes 分钟数
* @return Date
*/
public static Date getBeforeHour(Date date, int hours, int minutes){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hours);
calendar.add(Calendar.MINUTE, minutes);
return calendar.getTime();
}
/**
* 时间戳转时间
*/
public static String timeStamp2Time(Long timeStamp) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(timeStamp);
return sdf.format(date);
}
/**
* 得到几天前的时间
* @param date
* @param day
* @return
*/
public static Date getDateBefore(Date date,int day){
Calendar now =Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE,now.get(Calendar.DATE)-day);
return now.getTime();
}
/**
* 得到几天后的时间
* @param date
* @param day
* @return
*/
public static Date getDateAfter(Date date,int day){
Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE,now.get(Calendar.DATE)+day);
return now.getTime();
}
/**
* 得到几天后的时间
* @param date
* @param day
* @return
*/
public static String getDateStringAfter(Date date,int day){
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE,now.get(Calendar.DATE)+day);
return sf.format(now.getTime());
}
public static Boolean isSameYear(String date){
Calendar cal1 = Calendar.getInstance();
cal1.setTime(stringToDate(date, PATTERN_CLASSICAL));
int a = cal1.get(Calendar.YEAR);
Calendar cal2 = Calendar.getInstance();
int b = cal2.get(Calendar.YEAR);
return a == b;
}
public static String getSysdateStr() {
SimpleDateFormat formatter= new SimpleDateFormat(PATTERN_CLASSICAL);
Date date = new Date(System.currentTimeMillis());
return formatter.format(date);
}
public static String specialDate(String spcialString){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date date = null;
try {
date = df.parse(spcialString);
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat df1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
Date date1 = null;
try {
date1 = df1.parse(date.toString());
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return df2.format(date1);
}
/**
* 获取两个日期之间的所有日期
* @param startTime 开始日期
* @param endTime 结束日期
* @return
*/
public static List<String> getDays(String startTime, String endTime) {
// 返回的日期集合
List<String> days = new ArrayList<String>();
DateFormat dateFormat = new SimpleDateFormat(DateUtil.PATTERN_CLASSICAL_SIMPLE);
try {
Date start = dateFormat.parse(startTime);
Date end = dateFormat.parse(endTime);
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
while (tempStart.before(tempEnd)) {
days.add(dateFormat.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
/**
* @param args
*/
public static void main(String[] args) {
String dateString = "2022-09-14T02:12:13Z";
String startDate = "2023-08-08";
String endDate = "2023-08-07";
System.out.println("固定时间段:" + DateUtil.getDays(startDate, endDate));
//System.out.println(DateUtil.handlerTimeNoUTC(dateString,8));
// System.out.println(DateUtil.handlerTime(dateString));
// Date date = new Date();
// Date date1 = rollDay(date, -2);
// Date date2 = rollMonth(date, -3);
// System.out.println(format(date));
// System.out.println(format(date1));
// System.out.println(format(date2));
// System.out.println(getTimeOffsetDesc(date1));
// System.out.println(getTimeOffsetDesc(date2));
// System.out.println("获取下个月第一天的起始时间:"+format(getNextMonthStartTime(),PATTERN_CH));
// System.out.println("获取下个月最后一天的结束时间:"+format(getNextMonthEndTime()));
// System.out.println("获取前一个工作日:"+format(getPrevWorkday(),PATTERN_CLASSICAL_SIMPLE));
System.out.println("获取后一个工作日:"+format(getNextWorkday(),PATTERN_CLASSICAL_SIMPLE));
// System.out.println("获取当前季度第一天的起始时间:"+format(getQuarterStartTime()));
// System.out.println("获取当前季度最后一天的结束时间:"+format(getQuarterEndTime()));
// System.out.println("获取当周的第一个工作日:"+format(getFirstWorkday(),PATTERN_CLASSICAL_SIMPLE));
// System.out.println("获取当周的最后一个工作日:"+format(getLastWorkday(),PATTERN_CLASSICAL_SIMPLE));
// System.out.println(getWeekdayDesc(null));
// System.out.println(getSysdateStr());
}
}

@ -0,0 +1,101 @@
/*
* Licensed Materials - Property of ROOTCLOUD
* THIS MODULE IS "RESTRICTED MATERIALS OF ROOTCLOUD"
* (c) Copyright ROOTCLOUD Inc. 2018 All Rights Reserved
*
* The source code for this program is not published or
* otherwise divested of its trade secrets
*/
package com.rootcloud.common;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
/**
* 解压缩字符串工具.
*/
public class DeflaterUtils {
/*
*/
/**
* 压缩.
* @param unzipString {@code String}
* @return
*//*
public static String zipString(String unzipString) throws UnsupportedEncodingException {
*/
/*
* 0 ~ 9 压缩等级 低到高
* public static final int BEST_COMPRESSION = 9; 最佳压缩的压缩级别
* public static final int BEST_SPEED = 1; 压缩级别最快的压缩
* public static final int DEFAULT_COMPRESSION = -1; 默认压缩级别
* public static final int DEFAULT_STRATEGY = 0; 默认压缩策略
* public static final int DEFLATED = 8; 压缩算法的压缩方法(目前唯一支持的压缩方法)
* public static final int FILTERED = 1; 压缩策略最适用于大部分数值较小且数据分布随机分布的数据
* public static final int FULL_FLUSH = 3; 压缩刷新模式用于清除所有待处理的输出并重置拆卸器
* public static final int HUFFMAN_ONLY = 2; 仅用于霍夫曼编码的压缩策略
* public static final int NO_COMPRESSION = 0; 不压缩的压缩级别
* public static final int NO_FLUSH = 0; 用于实现最佳压缩结果的压缩刷新模式
* public static final int SYNC_FLUSH = 2; 用于清除所有未决输出的压缩刷新模式;
* 可能会降低某些压缩算法的压缩率
*//*
//使用指定的压缩级别创建一个新的压缩器
Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
//设置压缩输入数据
deflater.setInput(unzipString.getBytes("UTF-8"));
//当被调用时表示压缩应该以输入缓冲区的当前内容结束
deflater.finish();
final byte[] bytes = new byte[256];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
while (!deflater.finished()) {
//压缩输入数据并用压缩数据填充指定的缓冲区
int length = deflater.deflate(bytes);
outputStream.write(bytes, 0, length);
}
//关闭压缩器并丢弃任何未处理的输入
deflater.end();
return Base64.encodeToString(outputStream.toByteArray());
}
*/
/**
* 解压.
* @param zipString {@code String}
* @return
*/
public static String unzipString(String zipString) throws UnsupportedEncodingException {
byte[] decode = Base64.getDecoder().decode(zipString.getBytes("UTF-8"));
//创建一个新的解压缩器
Inflater inflater = new Inflater();
//设置解压缩的输入数据
inflater.setInput(decode);
final byte[] bytes = new byte[256];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
try {
//finished() 如果已到达压缩数据流的末尾则返回true
while (!inflater.finished()) {
//将字节解压缩到指定的缓冲区中
int length = inflater.inflate(bytes);
outputStream.write(bytes, 0, length);
}
} catch (DataFormatException e) {
e.printStackTrace();
return null;
} finally {
//关闭解压缩器并丢弃任何未处理的输入
inflater.end();
}
return new String(outputStream.toByteArray(),"UTF-8");
}
}

@ -0,0 +1,302 @@
/**
* Copyright (C), 2016-2019, 树根互联有限公司
* FileName: HttpClientUtil
* Author: yaqiang.zhao
* Date: 2019-9-25 17:22
* Description: 工具类
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package com.rootcloud.common;
import com.alibaba.fastjson.JSON;
import com.rootcloud.common.enums.HttpRequestMethedEnum;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 工具类
*
* @author yaqiang.zhao
* @create 2019-9-25
* @since 1.0.0
*/
public class HttpClientUtil {
private final static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);
/**
* httpclient使用步骤
* 1创建一个HttpClient对象;
* 2创建一个Http请求对象并设置请求的URL比如GET请求就创建一个HttpGet对象POST请求就创建一个HttpPost对象;
* 3如果需要可以设置请求对象的请求头参数也可以往请求对象中添加请求参数;
* 4调用HttpClient对象的execute方法执行请求;
* 5获取请求响应对象和响应Entity;
* 6从响应对象中获取响应状态从响应Entity中获取响应内容;
* 7关闭响应对象;
* 8关闭HttpClient.
*/
private static RequestConfig requestConfig = RequestConfig.custom()
//从连接池中获取连接的超时时间
// 要用连接时尝试从连接池中获取若是在等待了一定的时间后还没有获取到可用连接比如连接池中没有空闲连接了则会抛出获取连接超时异常
.setConnectionRequestTimeout(15000)
//与服务器连接超时时间httpclient会创建一个异步线程用以创建socket连接此处设置该socket的连接超时时间
//连接目标url的连接超时时间即客服端发送请求到与目标url建立起连接的最大时间超时时间3000ms过后系统报出异常
.setConnectTimeout(15000)
//socket读数据超时时间从服务器获取响应数据的超时时间
//连接上一个url后获取response的返回等待时间 即在与目标url建立连接后等待放回response的最大时间在规定时间内没有返回响应的话就抛出SocketTimeout
.setSocketTimeout(30000)
.setContentCompressionEnabled(false)
.build();
/**
* 发送http请求
*
* @param requestMethod 请求方式HttpGetHttpPostHttpPutHttpDelete
* @param url 请求路径
* @param params post请求参数
* @param header 请求头
* @return 响应文本
*/
public static String sendHttp(HttpRequestMethedEnum requestMethod, String url, Map<String, Object> params, Map<String, String> header) {
//1创建一个HttpClient对象;
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
String responseContent = null;
//2创建一个Http请求对象并设置请求的URL比如GET请求就创建一个HttpGet对象POST请求就创建一个HttpPost对象;
HttpRequestBase request = requestMethod.createRequest(url);
request.setConfig(requestConfig);
//3如果需要可以设置请求对象的请求头参数也可以往请求对象中添加请求参数;
if (header != null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
}
// 往对象中添加相关参数
try {
if (params != null) {
((HttpEntityEnclosingRequest) request).setEntity(
new StringEntity(JSON.toJSONString(params),
ContentType.create("application/json", "UTF-8")));
}
//4调用HttpClient对象的execute方法执行请求;
httpResponse = httpClient.execute(request);
//5获取请求响应对象和响应Entity;
HttpEntity httpEntity = httpResponse.getEntity();
//6从响应对象中获取响应状态从响应Entity中获取响应内容;
if (httpEntity != null) {
responseContent = EntityUtils.toString(httpEntity, "UTF-8");
}
} catch (IOException e) {
log.error(e.getMessage(), e);
e.printStackTrace();
} finally {
try {
//7关闭响应对象;
if (httpResponse != null) {
httpResponse.close();
}
//8关闭HttpClient.
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
e.printStackTrace();
}
}
return responseContent;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @return URL 所代表远程资源的响应结果
*/
public static String sendGetUTF8(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
log.info(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.error("sendGetUTF8:" + e.getMessage(), e);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
log.error("sendGetUTF8:" + e2.getMessage(), e2);
}
}
return result;
}
/**
* raw 请求
* @param url
* @param param
* @return
*/
public static String getPostRaw(String url,String param){
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity postingString = new StringEntity(param);// json传递
post.setEntity(postingString);
post.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse response = httpClient.execute(post);
result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
public static String postForm(String url,Map<String, String> param,Map<String, String> header) {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : param.entrySet()) {
formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity uefEntity;
String result = null;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
if (header != null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
httppost.setHeader(entry.getKey(), entry.getValue());
}
}
httppost.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String sendFormPost(String url,String param,Map<String, String> header){
String result = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity postingString = new StringEntity(param);// json传递
post.setEntity(postingString);
if (header != null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
post.setHeader(entry.getKey(), entry.getValue());
}
}
post.setHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
HttpResponse response = httpClient.execute(post);
result = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
/* public static void main(String[] args) {
String url = "https://ifsm.rootcloud.com/saas-gba-device-ledger/api/openapi/device/get-device";
Map<String, Object> map = new HashMap<>();
map.put("tId", "5UYBI01");
map.put("cId", "db34744a-4716-4b2e-9079-21cb307f6313");
map.put("key", MD5Utils.getSecret());
map.put("page",1);
map.put("size",100);
String res = HttpClientUtil.sendHttp(HttpRequestMethedEnum.HttpPost, url, map, new HashMap<>());
System.out.println(res);
}*/
}

@ -0,0 +1,453 @@
package com.rootcloud.common;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpUtils {
private static final int REQUEST_TIMEOUT = 3 * 1000; // 设置请求超时10秒钟
private static final int CONNECT_TIMEOUT = 5 * 1000; // 连接超时时间
private static final int SO_TIMEOUT = 10 * 1000; // 数据传输超时
private static final String ENCODING = "UTF-8";
// 务必单例
private static CloseableHttpClient client;
static {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setConnectionRequestTimeout(REQUEST_TIMEOUT)
.setSocketTimeout(SO_TIMEOUT)
.build();
client = HttpClients.custom().setDefaultRequestConfig(requestConfig).setMaxConnTotal(50).build();
}
public static String get(String url, Map<String, String> paramsMap) {
return send(RequestBuilder.get(url), paramsMap);
}
public static String post(String url, Map<String, String> paramsMap) {
return send(RequestBuilder.post(url), paramsMap);
}
public static String send(RequestBuilder requestBuilder, Map<String, String> paramsMap){
requestBuilder.setCharset(Charset.forName(ENCODING));
String responseText = "";
if (paramsMap != null) {
for (Map.Entry<String, String> param : paramsMap.entrySet()) {
requestBuilder.addParameter(param.getKey(), param.getValue());
}
CloseableHttpResponse response = null;
try {
response = client.execute(requestBuilder.build());
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
responseText = EntityUtils.toString(entity, ENCODING);
}
}
} catch (Exception e) {
//throw new PlatformException("HTTP请求工具类发送请求异常", PlatformExceptionEnum.JE_CORE_UTIL_HTTP_SEND_ERROR,new Object[]{requestBuilder.getUri().getPath(),paramsMap},e);
}finally {
try {
response.close();
} catch (Exception e) {
//throw new PlatformException("HTTP请求工具类关闭请求链接异常", PlatformExceptionEnum.JE_CORE_UTIL_HTTP_SEND_ERROR,new Object[]{requestBuilder.getUri().getPath(),paramsMap},e);
}
}
}
return responseText;
}
/**
* get
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doGet(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpGet request = new HttpGet(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
/**
* post form
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
Map<String, String> bodys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (bodys != null) {
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
for (String key : bodys.keySet()) {
nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
request.setEntity(formEntity);
}
return httpClient.execute(request);
}
/**
* Post String
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (StringUtils.isNotBlank(body)) {
StringEntity entity = new StringEntity(body, "utf-8");
entity.setContentType("application/json; charset=utf-8");
request.setEntity(entity);
}
return httpClient.execute(request);
}
/**
* Post stream
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPost(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPost request = new HttpPost(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Put String
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
String body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
// if (StringUtils.isNotBlank(body)) {
// request.setEntity(new StringEntity(body, "utf-8"));
// }
return httpClient.execute(request);
}
/**
* Put stream
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @param body
* @return
* @throws Exception
*/
public static HttpResponse doPut(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys,
byte[] body)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpPut request = new HttpPut(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
if (body != null) {
request.setEntity(new ByteArrayEntity(body));
}
return httpClient.execute(request);
}
/**
* Delete
*
* @param host
* @param path
* @param method
* @param headers
* @param querys
* @return
* @throws Exception
*/
public static HttpResponse doDelete(String host, String path, String method,
Map<String, String> headers,
Map<String, String> querys)
throws Exception {
HttpClient httpClient = wrapClient(host);
HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
for (Map.Entry<String, String> e : headers.entrySet()) {
request.addHeader(e.getKey(), e.getValue());
}
return httpClient.execute(request);
}
private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
StringBuilder sbUrl = new StringBuilder();
sbUrl.append(host);
// if (!StringUtils.isBlank(path)) {
// sbUrl.append(path);
// }
if (null != querys) {
StringBuilder sbQuery = new StringBuilder();
for (Map.Entry<String, String> query : querys.entrySet()) {
if (0 < sbQuery.length()) {
sbQuery.append("&");
}
// if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
// sbQuery.append(query.getValue());
// }
// if (!StringUtils.isBlank(query.getKey())) {
// sbQuery.append(query.getKey());
// if (!StringUtils.isBlank(query.getValue())) {
// sbQuery.append("=");
// sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
// }
// }
}
if (0 < sbQuery.length()) {
sbUrl.append("?").append(sbQuery);
}
}
return sbUrl.toString();
}
private static HttpClient wrapClient(String host) {
HttpClient httpClient = new DefaultHttpClient();
if (host.startsWith("https://")) {
sslClient(httpClient);
}
return httpClient;
}
private static void sslClient(HttpClient httpClient) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(X509Certificate[] xcs, String str) {
}
@Override
public void checkServerTrusted(X509Certificate[] xcs, String str) {
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = httpClient.getConnectionManager();
SchemeRegistry registry = ccm.getSchemeRegistry();
registry.register(new Scheme("https", 443, ssf));
} catch (KeyManagementException ex) {
//throw new PlatformException("HTTP请求工具类SLL请求异常", PlatformExceptionEnum.JE_CORE_UTIL_HTTP_SSLCLIENT_ERROR,ex);
} catch (NoSuchAlgorithmException ex) {
//throw new PlatformException("HTTP请求工具类SLL请求异常", PlatformExceptionEnum.JE_CORE_UTIL_HTTP_SSLCLIENT_ERROR,ex);
}
}
public static String responseText(HttpResponse response) {
String responseText = "";
try {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null) {
responseText = EntityUtils.toString(entity, "UTF-8");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return responseText;
}
/**
* RAW请求
* @param url
* @param stringJson
* @param headers
* @param encode
* @return
*/
public static String httpPostRaw(String url, String stringJson, Map<String,String> headers, String encode){
String str="";
if(encode == null){
encode = "utf-8";
}
//HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPost httpost = new HttpPost(url);
//设置header
httpost.setHeader("Content-type", "application/json");
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpost.setHeader(entry.getKey(),entry.getValue());
}
}
//组织请求参数
StringEntity stringEntity = new StringEntity(stringJson, encode);
httpost.setEntity(stringEntity);
String content = null;
CloseableHttpResponse httpResponse = null;
try {
//响应信息
httpResponse = closeableHttpClient.execute(httpost);
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity, encode);
str=content;
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try { //关闭连接释放资源
closeableHttpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}

@ -0,0 +1,21 @@
package com.rootcloud.common;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
public final class I18nUtil {
public static Locale localeEn = new Locale("en","US");
public static Locale localeCn = new Locale("zh","CN");
public static ReloadableResourceBundleMessageSource messageSource;
static {
messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setCacheSeconds(-1);
messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
messageSource.setBasenames("i18n/messages/messages");
}
}

@ -0,0 +1,18 @@
package com.rootcloud.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* TODO
*
* @author wei.liao
* @version 1.0
* @date 2022/4/7 19:33
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreSecurity {
}

@ -0,0 +1,152 @@
package com.rootcloud.common;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class JEUuidUtil {
final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z'};
final static Map<Character, Integer> digitMap = new HashMap<Character, Integer>();
static {
for (int i = 0; i < digits.length; i++) {
digitMap.put(digits[i], (int) i);
}
}
/**
* 支持的最大进制数
*/
public static final int MAX_RADIX = digits.length;
/**
* 支持的最小进制数
*/
public static final int MIN_RADIX = 2;
/**
* 将长整型数值转换为指定的进制数最大支持62进制字母数字已经用尽
*/
public static String toString(long i, int radix) {
if (radix < MIN_RADIX || radix > MAX_RADIX)
radix = 10;
if (radix == 10)
return Long.toString(i);
final int size = 65;
int charPos = 64;
char[] buf = new char[size];
boolean negative = (i < 0);
if (!negative) {
i = -i;
}
while (i <= -radix) {
buf[charPos--] = digits[(int) (-(i % radix))];
i = i / radix;
}
buf[charPos] = digits[(int) (-i)];
if (negative) {
buf[--charPos] = '-';
}
return new String(buf, charPos, (size - charPos));
}
static NumberFormatException forInputString(String s) {
return new NumberFormatException("For input string: \"" + s + "\"");
}
/**
* 将字符串转换为长整型数字
*
* @param s 数字字符串
* @param radix 进制数
*/
public static long toNumber(String s, int radix) {
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < MIN_RADIX) {
throw new NumberFormatException("radix " + radix
+ " less than Numbers.MIN_RADIX");
}
if (radix > MAX_RADIX) {
throw new NumberFormatException("radix " + radix
+ " greater than Numbers.MAX_RADIX");
}
long result = 0;
boolean negative = false;
int i = 0, len = s.length();
long limit = -Long.MAX_VALUE;
long multmin;
Integer digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') {
if (firstChar == '-') {
negative = true;
limit = Long.MIN_VALUE;
} else if (firstChar != '+')
throw forInputString(s);
if (len == 1) {
throw forInputString(s);
}
i++;
}
multmin = limit / radix;
while (i < len) {
digit = digitMap.get(s.charAt(i++));
if (digit == null) {
throw forInputString(s);
}
if (digit < 0) {
throw forInputString(s);
}
if (result < multmin) {
throw forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw forInputString(s);
}
result -= digit;
}
} else {
throw forInputString(s);
}
return negative ? result : -result;
}
private static String digits(long val, int digits) {
long hi = 1L << (digits * 4);
return toString(hi | (val & (hi - 1)), MAX_RADIX).substring(1);
}
/**
* 以62进制字母加数字生成19位UUID最短的UUID
*/
public static String uuid() {
UUID uuid = UUID.randomUUID();
StringBuilder sb = new StringBuilder();
sb.append(digits(uuid.getMostSignificantBits() >> 32, 8));
sb.append(digits(uuid.getMostSignificantBits() >> 16, 4));
sb.append(digits(uuid.getMostSignificantBits(), 4));
sb.append(digits(uuid.getLeastSignificantBits() >> 48, 4));
sb.append(digits(uuid.getLeastSignificantBits(), 12));
return sb.toString();
}
}

@ -0,0 +1,45 @@
package com.rootcloud.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* 通用返回对象
*/
@Getter
@Setter
@ToString
@ApiModel("接口调用结果")
public class JsonPageResult<T> extends JsonResult<T> {
/**
* 提示信息
*/
@ApiModelProperty(notes = "记录总数")
private long total;
public JsonPageResult(String code) {
super(code);
}
public JsonPageResult(String code, T data) {
super(code, data);
}
public JsonPageResult(String code, T data, String message) {
super(code, data, message);
}
/**
* 成功返回结果
*
* @param data 获取的数据
*/
public static <T> JsonPageResult<T> success(T data, long total) {
JsonPageResult<T> result = new JsonPageResult<>(CODE_SUCCESS, data);
result.setTotal(total);
return result;
}
}

@ -0,0 +1,78 @@
package com.rootcloud.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* 通用返回对象
*/
@Getter
@Setter
@ToString
@ApiModel("接口调用结果")
public class JsonResult<T> {
protected static final String CODE_SUCCESS = "200";
private static final String CODE_CLIENT_ERROR = "450";
/**
* 状态码
*/
@ApiModelProperty(notes = "返回码")
private String code;
/**
* 数据封装
*/
@ApiModelProperty(notes = "数据")
private T data;
/**
* 提示信息
*/
@ApiModelProperty(notes = "提示信息")
private String message;
public JsonResult(String code) {
this(code, null);
}
public JsonResult(String code, T data) {
this(code, data, null);
}
public JsonResult(String code, T data, String message) {
this.code = code;
this.message = message;
this.data = data;
}
public static <T> JsonResult<T> success() {
return new JsonResult<T>(CODE_SUCCESS, null, null);
}
public static <T> JsonResult<T> success(T data) {
return new JsonResult<T>(CODE_SUCCESS, data, null);
}
public static <T> JsonResult<T> successOK(T data,String message) {
return new JsonResult<T>("OK", data, message);
}
public static <T> JsonResult<T> clientFailed(String message) {
return new JsonResult<T>(CODE_CLIENT_ERROR, null, message);
}
public static <T> JsonResult<T> failed(String code, String message) {
return new JsonResult<T>(code, null, message);
}
/**
* 失败返回结果
*
* @param message 提示信息
*/
public static <T> JsonResult<T> failed(String code, String message, T data) {
return new JsonResult(code, data, message);
}
}

@ -0,0 +1,105 @@
package com.rootcloud.common;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
/**
* 2.0系统JSON输出类
* */
public class JsonResult2 extends HashMap<String, Object> {
private static final long serialVersionUID = 1648637553048061990L;
public JsonResult2(){
this.put("ret", JsonResultStatus.SUCCESS.getRet());
this.put("msg", JsonResultStatus.SUCCESS.getMsg());
this.put("data", new ArrayList<String>());
}
public JsonResult2(Object data){
this.put("ret", JsonResultStatus.SUCCESS.getRet());
this.put("msg", JsonResultStatus.SUCCESS.getMsg());
this.put("data", data);
}
// public JsonResult2(Page page) {
// this.put("ret", JsonResultStatus.SUCCESS.getRet());
// this.put("msg", JsonResultStatus.SUCCESS.getMsg());
// this.put("data", new ArrayList<String>());
// this.put("pageNo", page.getPageNo());
// this.put("count", page.getPageNo());
// this.put("pageSize", page.getPageSize());
// }
public JsonResult2(String ret,String msg){
this.put("ret", ret);
this.put("msg", msg);
this.put("data", new ArrayList<String>());
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Override
public Object put(String key, Object value) {
if(null != key){
if("ret".equals(key.toLowerCase()) || "msg".equals(key.toLowerCase())){
if(!(value instanceof String)){
return this.get(key);
}
}
if("data".equals(key.toLowerCase())){
if(null == value){
super.put("data", new ArrayList());
return null;
}else if(!(value instanceof Collection || value instanceof Array
|| value.getClass().isArray())){
ArrayList list = new ArrayList();
list.add(value);
super.put("data", list);
return list;
}
}
}
return super.put(key, value);
}
public String getRet() {
return (String)this.get("ret");
}
public void setRet(String ret) {
this.put("ret", ret);
}
public String getMsg() {
return (String)this.get("msg");
}
public void setMsg(String msg) {
this.put("msg", msg);
}
public void putRetMsg(String ret,String msg){
this.put("msg", msg);
this.put("ret", ret);
}
public <T> T getData() {
return (T) this.get("data");
}
public boolean isSucceed() {
return getRet().startsWith("2");
}
public boolean isFailed() {
return !isSucceed();
}
public void setData(Object data) {
this.put("data", data);
}
}

@ -0,0 +1,67 @@
package com.rootcloud.common;
public enum JsonResultStatus {
SUCCESS("200", "执行成功"),
REQ_REDIRECT("301", "请求已被永久移动到新位置"),
REQ_GRAMMAR_ERROR("400", "服务器不理解请求的语法"),
REQ_UN_AUTHORIZED( "401", "API访问资源未授权"),
REQ_REFUSE("403", "访问被服务器拒绝"),
REQ_NOT_FOUND("404", "请求地址不存在"),
REQ_EMPTY_PARAMS( "406", "请求参数错误或为空"),
REQ_NOT_OVERTIME("408", "服务器等候请求时超时"),
SYS_EXCEPTION("500", "系统服务存在异常"),
SYS_UNENFORCED( "501", "服务器不具备完成请求的功能"),
SYS_GATEWAY_ERROR("502", "服务器作为网关或代理,从后续服务收到了无效的响应"),
SYS_UNAVAILABLE_ERROR("503","目前无法使用服务(由于超载或进行停机维护)"),
SYS_GATEWAY_TIMEOUT("504", "服务器作为网关或代理,未及时从后续服务接收请求"),
SYS_VERSION_ERROR("505","HTTP版本不被支持"),
NO_LOGIN("600", "用户未登录或登录已失效"),
NO_RECORDS("691", "记录不存在"),
HTTP_REQ_ERROR("900", "服务请求失败"),
USER_TENANT_MATCHING_ERROR( "902", "用户请求与所属租户不匹配"),
HTTP_URL_ERROR("903", "请求地址非法或为空"),
USER_TENANT_LOST_ERROR("904", "用户所属租户序号丢失"),
/*业务状态码*/
DEVICE_UN_AUTHORIZED("50060001", "用户无权限操作"),
DEVICE_FAIL("50060002", "执行失败"),
DEVICE_ENQUIRE("50060003", "询问状态"),
PARAM_REP_TYPE_NULL("50060004", "报表类型不能为空"),
PARAM_REP_YEAR_NULL("50060005", "报表年份不能为空"),
PARAM_DATE_NULL("50060008", "日期参数不能为空"),
REST_GET_DEVICES_BY_OFFICE_NULL("50060006", "调用Base服务根据机构编号获取设备清单返回为空请联系管理员"),
REST_REQUEST_FAILED("50060007", "内部服务请求失败,请联系管理员"),
PRINTER_HEALTH_CHECK_CONFIG_NOT_EXISTS("50060009", "健康度检查配置项不存在"),
WORK_DATA_QUERY_CONFIG_NOT_EXISTS("50060010", "工况查询配置信息不存在,请联系管理员"),
WORK_DATA_READ_PROPERTY_VALUE_FAILED("50060011", "读取工况结果属性值失败,请联系管理员")
;
private String ret;
private String msg;
private JsonResultStatus(String ret, String msg) {
this.ret = ret;
this.msg = msg;
}
public String getRet() {
return ret;
}
public void setRet(String ret) {
this.ret = ret;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}

@ -0,0 +1,462 @@
package com.rootcloud.common;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.rootcloud.common.constant.LappLiveConstant;
import com.rootcloud.common.net.JsonHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* 用于调取萤石api实现视频直播操作
* @author fandi
*
*/
@Component
public class LappLiveClient {
private static Logger log = LoggerFactory.getLogger(LappLiveClient.class);
private static CloseableHttpClient httpClient = HttpClients.createDefault();
/**
* 获取
* @param //url 萤石接口
* @param //appKey
* @param //appSecret
* @return String
*/
public String getAccessToken() throws Exception{
if(StringUtils.isBlank(LappLiveConstant.GET_TOKEN_URL) || StringUtils.isBlank(LappLiveConstant.APP_KEY) || StringUtils.isBlank(LappLiveConstant.APP_SECRET)) {
log.info("getAccessToken param can not be null| getAccessTokenUrl:{}|appKey:{}|appSecret:{}", LappLiveConstant.GET_TOKEN_URL, LappLiveConstant.APP_KEY, LappLiveConstant.APP_SECRET);
return null;
}
log.info("getAccessTokenparam is | getAccessTokenUrl:{} | appKey:{} | appSecret:{} ", LappLiveConstant.GET_TOKEN_URL, LappLiveConstant.APP_KEY, LappLiveConstant.APP_SECRET);
String getTokenUri = LappLiveConstant.GET_TOKEN_URL + "?appKey=" + LappLiveConstant.APP_KEY + "&appSecret=" + LappLiveConstant.APP_SECRET;
HttpPost post = new HttpPost(getTokenUri);
String message = "";
post.setHeader("Content-type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(post);
message = EntityUtils.toString(response.getEntity(), "utf-8");
// 首先获取data数据然后获取data中的accessToken中的数据
String data = "";
if(JsonHelper.getJsonObject(message).get("code").toString().equals("200")) {
data = JsonHelper.getJsonObject(message).get("data").toString();
}else {
return null;
}
if(StringUtils.isBlank(data)) {
return null;
}
// 获取accessToken的有效地址
String accessToken = JsonHelper.getJsonObject(data).get("accessToken").toString();
return accessToken;
}
/**
* 获取
* @param //url 乐橙接口
* @param //appKey
* @param //appSecret
* @return String
*/
public String getAccessTokenLeCheng() throws Exception{
if(StringUtils.isBlank(LappLiveConstant.GET_TOKEN_LECHENG_URL) || StringUtils.isBlank(LappLiveConstant.APP_KEY_LECHENG) || StringUtils.isBlank(LappLiveConstant.APP_SECRET_LECHENG)) {
log.error("getAccessToken param can not be null| getAccessTokenUrl:{}|appKey:{}|appSecret:{}", LappLiveConstant.GET_TOKEN_LECHENG_URL, LappLiveConstant.APP_KEY_LECHENG, LappLiveConstant.APP_SECRET_LECHENG);
return null;
}
Map<String, Object> map = paramsInit();
log.error("getAccessTokenparam is | getAccessTokenUrl:{} | appKey:{} | appSecret:{} ", LappLiveConstant.GET_TOKEN_LECHENG_URL, LappLiveConstant.APP_KEY_LECHENG, LappLiveConstant.APP_SECRET_LECHENG);
//String getTokenUri = LappLiveConstant.GET_TOKEN_LECHENG_URL + "?appKey=" + LappLiveConstant.APP_KEY_LECHENG + "&appSecret=" + LappLiveConstant.APP_SECRET_LECHENG;
String getTokenUri = LappLiveConstant.GET_TOKEN_LECHENG_URL;
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(getTokenUri);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
long time = System.currentTimeMillis() / 1000;
String nonce = UUID.randomUUID().toString();
String id = UUID.randomUUID().toString();
StringBuilder paramString = new StringBuilder();
paramString.append("time:").append(time).append(",");
paramString.append("nonce:").append(nonce).append(",");
paramString.append("appSecret:").append(LappLiveConstant.APP_SECRET_LECHENG); //SECRET
String sign = "";
// 计算MD5得值
try {
//System.out.println("传入参数:" + paramString.toString().trim());
sign = DigestUtils.md5Hex(paramString.toString().trim().getBytes("UTF-8"));
} catch (Exception e) {
log.error("md5 exception:"+e.toString());
e.printStackTrace();
}
log.error("sign:"+sign);
Map<String, Object> systemMap = new HashMap<String, Object>();
systemMap.put("ver", "1.0");
systemMap.put("sign", sign);
systemMap.put("appId", LappLiveConstant.APP_KEY_LECHENG); //AppID
systemMap.put("nonce", nonce);
systemMap.put("time", time);
// 构建JSON对象
JsonObject systemObject = new JsonObject();
systemObject.addProperty("ver", "1.0");
systemObject.addProperty("appId", LappLiveConstant.APP_KEY_LECHENG);
systemObject.addProperty("sign", sign);
systemObject.addProperty("time", time);
systemObject.addProperty("nonce", nonce);
JsonObject jsonObject = new JsonObject();
jsonObject.add("system", systemObject);
jsonObject.addProperty("id", id);
jsonObject.add("params", new JsonObject());
String json = jsonObject.toString();
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
// 发送请求并获取响应
HttpResponse response = client.execute(post);
// 获取响应状态码
int statusCode = response.getStatusLine().getStatusCode();
String result = "";
// 获取accessToken的有效地址
String accessToken = "";
try{
if (statusCode == 200) {
// 获取响应内容
result = EntityUtils.toString(response.getEntity());
//System.out.println("响应内容: " + result);
} else {
//System.err.println("HTTP请求失败状态码: " + statusCode);
}
if(JsonHelper.getJsonObject(JsonHelper.getJsonObject(result).get("result")).get("code").toString().equals("0")){
String data = JsonHelper.getJsonObject(JsonHelper.getJsonObject(result).get("result")).get("data").toString();
//accessToken = JsonHelper.getJsonObject(JsonHelper.getJsonObject(JsonHelper.getJsonObject(result).get("result")).get("data")).get("accessToken");
accessToken = JsonHelper.getJsonObject(data).get("accessToken").toString();
}else {
return null;
}
log.error("accessToken="+accessToken);
}catch (Exception ex){
log.error("accessToken exception:"+ex.toString());
}
return accessToken;
}
protected static Map<String, Object> paramsInit() {
long time = System.currentTimeMillis() / 1000;
String nonce = UUID.randomUUID().toString();
String id = UUID.randomUUID().toString();
StringBuilder paramString = new StringBuilder();
paramString.append("time:").append(time).append(",");
paramString.append("nonce:").append(nonce).append(",");
paramString.append("appSecret:").append(LappLiveConstant.APP_SECRET_LECHENG); //SECRET
String sign = "";
// 计算MD5得值
try {
System.out.println("传入参数:" + paramString.toString().trim());
sign = DigestUtils.md5Hex(paramString.toString().trim().getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
Map<String, Object> systemMap = new HashMap<String, Object>();
systemMap.put("ver", "1.0");
systemMap.put("sign", sign);
systemMap.put("appId", LappLiveConstant.APP_KEY_LECHENG); //AppID
systemMap.put("nonce", nonce);
systemMap.put("time", time);
Map<String, Object> paramsMap = new HashMap<>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("system", systemMap);
map.put("params", paramsMap);
map.put("id", id);
return map;
}
/**
* 开通直播功能
* @param accessToken 令牌号
* @param //String url 萤石接口url
* @param //String deviceSerial 设备序列号
* @param //String channelNo 通道号
* @return boolean (true表示成功false表示失败)
* @throws IOException
* @throws ParseException
*/
public String openLive(String url, String accessToken, String deviceSerial, String channelNo) throws ParseException, IOException {
if(StringUtils.isBlank(url) || StringUtils.isBlank(deviceSerial) || StringUtils.isBlank(accessToken) || StringUtils.isBlank(channelNo)) {
log.info("openLive parame can not be null| accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
return null;
}
log.info("openLive parame is |accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
// 获取直播源格式为[设备序列号]:[通道号]
String source = deviceSerial + ":" + channelNo;
String openLiveUri = url + "?accessToken=" + accessToken + "&source=" + source;
HttpPost post = new HttpPost(openLiveUri);
String message = "";
post.setHeader("Content-type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(post);
message = EntityUtils.toString(response.getEntity(), "utf-8");
return message;
}
/**
* 获取直播地址
* @return
* @throws IOException
* @throws ClientProtocolException
*/
public String getLiveAddress(String url, String accessToken, String deviceSerial, String channelNo) throws ClientProtocolException, IOException{
if(StringUtils.isBlank(url) || StringUtils.isBlank(deviceSerial) || StringUtils.isBlank(accessToken) || StringUtils.isBlank(channelNo)) {
log.info("getLiveAddress parame can not be null| accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
return null;
}
log.info("getLiveAddress parame is |accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
// 获取直播源格式为[设备序列号]:[通道号]
String source = deviceSerial + ":" + channelNo;
String getLiveAddressUri = url + "?accessToken="+ accessToken + "&source=" + source;
HttpPost post = new HttpPost(getLiveAddressUri);
String message = "";
post.setHeader("Content-type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(post);
message = EntityUtils.toString(response.getEntity(), "utf-8");
return message;
}
public String getLiveAddressLeCheng0(String url, String accessToken, String deviceSerial, String channelNo) throws ClientProtocolException, IOException{
if(StringUtils.isBlank(url) || StringUtils.isBlank(deviceSerial) || StringUtils.isBlank(accessToken) || StringUtils.isBlank(channelNo)) {
log.info("getLiveAddress parame can not be null| accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
return null;
}
log.info("getLiveAddress parame is |accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
//查询设备通道下创建的直播信息
String getLiveAddressUri = "https://openapi.lechange.cn/openapi/getLiveStreamInfo";
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(getLiveAddressUri);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
long time = System.currentTimeMillis() / 1000;
String nonce = UUID.randomUUID().toString();
String id = UUID.randomUUID().toString();
StringBuilder paramString = new StringBuilder();
paramString.append("time:").append(time).append(",");
paramString.append("nonce:").append(nonce).append(",");
paramString.append("appSecret:").append(LappLiveConstant.APP_SECRET_LECHENG); //SECRET
String sign = "";
// 计算MD5得值
try {
//System.out.println("传入参数:" + paramString.toString().trim());
sign = DigestUtils.md5Hex(paramString.toString().trim().getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
Map<String, Object> systemMap = new HashMap<String, Object>();
systemMap.put("ver", "1.0");
systemMap.put("sign", sign);
systemMap.put("appId", LappLiveConstant.APP_KEY_LECHENG); //AppID
systemMap.put("nonce", nonce);
systemMap.put("time", time);
// 构建JSON对象
JsonObject systemObject = new JsonObject();
systemObject.addProperty("ver", "1.0");
systemObject.addProperty("appId", LappLiveConstant.APP_KEY_LECHENG);
systemObject.addProperty("sign", sign);
systemObject.addProperty("time", time);
systemObject.addProperty("nonce", nonce);
JsonObject jsonObject = new JsonObject();
jsonObject.add("system", systemObject);
jsonObject.addProperty("id", id);
JsonObject paramsObject = new JsonObject();
paramsObject.addProperty("deviceId", deviceSerial);
paramsObject.addProperty("channelId", channelNo);
paramsObject.addProperty("token", accessToken);
jsonObject.add("params", paramsObject);
String json = jsonObject.toString();
StringEntity entity = new StringEntity(json);
post.setEntity(entity);
HttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
String result = "";
String message = "";
if (statusCode == 200) {
result = EntityUtils.toString(response.getEntity());
System.out.println("响应内容: " + result);
log.info("响应内容: " + result);
} else {
System.err.println("HTTP请求失败状态码: " + statusCode);
log.info("HTTP请求失败状态码: " + statusCode);
}
return result;
}
public String getLiveAddressLeCheng1(String url, String accessToken, String deviceSerial, String channelNo) throws ClientProtocolException, IOException{
if(StringUtils.isBlank(url) || StringUtils.isBlank(deviceSerial) || StringUtils.isBlank(accessToken) || StringUtils.isBlank(channelNo)) {
log.info("getLiveAddress parame can not be null| accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
return null;
}
log.info("getLiveAddress parame is |accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
// 获取直播源格式为[设备序列号]:[通道号]
String getLiveAddressUri = url;
HttpPost post = new HttpPost(getLiveAddressUri);
Map<String, Object> map1 = paramsLiveInit1(deviceSerial,channelNo,accessToken);
StringEntity entity = new StringEntity(map1.toString(), ContentType.APPLICATION_JSON);
post.setEntity(entity);
String message = "";
post.setHeader("Content-type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(post);
message = EntityUtils.toString(response.getEntity(), "utf-8");
return message;
}
protected static Map<String, Object> paramsLiveInit1(String deviceSerial,String channelNo,String accessToken) {
long time = System.currentTimeMillis() / 1000;
String nonce = UUID.randomUUID().toString();
String id = UUID.randomUUID().toString();
StringBuilder paramString = new StringBuilder();
paramString.append("time:").append(time).append(",");
paramString.append("nonce:").append(nonce).append(",");
paramString.append("appSecret:").append(LappLiveConstant.APP_SECRET_LECHENG); //SECRET
String sign = "";
// 计算MD5得值
try {
System.out.println("传入参数:" + paramString.toString().trim());
sign = DigestUtils.md5Hex(paramString.toString().trim().getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
Map<String, Object> systemMap = new HashMap<String, Object>();
systemMap.put("ver", "1.0");
systemMap.put("sign", sign);
systemMap.put("appId", LappLiveConstant.APP_KEY_LECHENG); //AppID
systemMap.put("nonce", nonce);
systemMap.put("time", time);
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("streamId", "0"); //0:高清主码流 1:标清辅码流
paramsMap.put("deviceId", deviceSerial); //设备序列号
paramsMap.put("channelId", channelNo); //通道号
paramsMap.put("token", accessToken);//管理员accessToken
Map<String, Object> map = new HashMap<String, Object>();
map.put("system", systemMap);
map.put("params", paramsMap);
map.put("id", id);
return map;
}
protected static Map<String, Object> paramsLiveInit2(String deviceSerial,String channelNo,String accessToken) {
long time = System.currentTimeMillis() / 1000;
String nonce = UUID.randomUUID().toString();
String id = UUID.randomUUID().toString();
StringBuilder paramString = new StringBuilder();
paramString.append("time:").append(time).append(",");
paramString.append("nonce:").append(nonce).append(",");
paramString.append("appSecret:").append(LappLiveConstant.APP_SECRET_LECHENG); //SECRET
String sign = "";
// 计算MD5得值
try {
System.out.println("传入参数:" + paramString.toString().trim());
sign = DigestUtils.md5Hex(paramString.toString().trim().getBytes("UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
Map<String, Object> systemMap = new HashMap<String, Object>();
systemMap.put("ver", "1.0");
systemMap.put("sign", sign);
systemMap.put("appId", LappLiveConstant.APP_KEY_LECHENG); //AppID
systemMap.put("nonce", nonce);
systemMap.put("time", time);
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("streamId", "1"); //0:高清主码流 1:标清辅码流
paramsMap.put("deviceId", deviceSerial); //设备序列号
paramsMap.put("channelId", channelNo); //通道号
paramsMap.put("token", accessToken);//管理员accessToken
Map<String, Object> map = new HashMap<String, Object>();
map.put("system", systemMap);
map.put("params", paramsMap);
map.put("id", id);
return map;
}
public String getLiveAddressLeCheng2(String url, String accessToken, String deviceSerial, String channelNo) throws ClientProtocolException, IOException{
if(StringUtils.isBlank(url) || StringUtils.isBlank(deviceSerial) || StringUtils.isBlank(accessToken) || StringUtils.isBlank(channelNo)) {
log.info("getLiveAddress parame can not be null| accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
return null;
}
log.info("getLiveAddress parame is |accessToken:{}|deviceSerial:{}|channelNo:{}|url:{}", accessToken, deviceSerial, channelNo, url);
// 获取直播源格式为[设备序列号]:[通道号]
String getLiveAddressUri = url;
HttpPost post = new HttpPost(getLiveAddressUri);
Map<String, Object> map2 = paramsLiveInit2(deviceSerial,channelNo,accessToken);
StringEntity entity = new StringEntity(map2.toString(), ContentType.APPLICATION_JSON);
post.setEntity(entity);
String message = "";
post.setHeader("Content-type", "application/x-www-form-urlencoded");
CloseableHttpResponse response = httpClient.execute(post);
message = EntityUtils.toString(response.getEntity(), "utf-8");
return message;
}
}

@ -0,0 +1,21 @@
package com.rootcloud.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 效验属性不可以为空
* @author yang yin bo
*
*2017年4月17日 下午2:47:02
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotBlank {
String message() default "参数不可以为空";
}

@ -0,0 +1,148 @@
package com.rootcloud.common;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* OAuth2 properties define properties for OAuth2-based microservices.
*/
@Component
@ConfigurationProperties(prefix = "oauth2", ignoreUnknownFields = false)
public class OAuth2Properties {
private WebClientConfiguration webClientConfiguration = new WebClientConfiguration();
private SignatureVerification signatureVerification = new SignatureVerification();
public WebClientConfiguration getWebClientConfiguration() {
return webClientConfiguration;
}
public SignatureVerification getSignatureVerification() {
return signatureVerification;
}
public static class WebClientConfiguration {
private String clientId = "web_app";
private String secret = "changeit";
private String phoenixClientId;
private String phoenixSecret;
/**
* Holds the session timeout in seconds for non-remember-me sessions.
* After so many seconds of inactivity, the session will be terminated.
* Only checked during token refresh, so long access token validity may
* delay the session timeout accordingly.
*/
private int sessionTimeoutInSeconds = 1800;
/**
* Defines the cookie domain. If specified, cookies will be set on this domain.
* If not configured, then cookies will be set on the top-level domain of the
* request you sent, i.e. if you send a request to <code>app1.your-domain.com</code>,
* then cookies will be set <code>on .your-domain.com</code>, such that they
* are also valid for <code>app2.your-domain.com</code>.
*/
private String cookieDomain;
private String serverApiPrefix = "";
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public int getSessionTimeoutInSeconds() {
return sessionTimeoutInSeconds;
}
public void setSessionTimeoutInSeconds(int sessionTimeoutInSeconds) {
this.sessionTimeoutInSeconds = sessionTimeoutInSeconds;
}
public String getCookieDomain() {
return cookieDomain;
}
public void setCookieDomain(String cookieDomain) {
this.cookieDomain = cookieDomain;
}
public String getServerApiPrefix() {
return serverApiPrefix;
}
public void setServerApiPrefix(String serverApiPrefix) {
this.serverApiPrefix = serverApiPrefix;
}
public String getPhoenixClientId() {
return phoenixClientId;
}
public void setPhoenixClientId(String phoenixClientId) {
this.phoenixClientId = phoenixClientId;
}
public String getPhoenixSecret() {
return phoenixSecret;
}
public void setPhoenixSecret(String phoenixSecret) {
this.phoenixSecret = phoenixSecret;
}
}
public static class SignatureVerification {
/**
* Maximum refresh rate for public keys in ms.
* We won't fetch new public keys any faster than that to avoid spamming UAA in case
* we receive a lot of "illegal" tokens.
*/
private long publicKeyRefreshRateLimit = 10 * 1000L;
/**
* Maximum TTL for the public key in ms.
* The public key will be fetched again from UAA if it gets older than that.
* That way, we make sure that we get the newest keys always in case they are updated there.
*/
private long ttl = 24 * 60 * 60 * 1000L;
/**
* Endpoint where to retrieve the public key used to verify token signatures.
*/
private String publicKeyEndpointUri = "http://uaa/oauth/token_key";
public long getPublicKeyRefreshRateLimit() {
return publicKeyRefreshRateLimit;
}
public void setPublicKeyRefreshRateLimit(long publicKeyRefreshRateLimit) {
this.publicKeyRefreshRateLimit = publicKeyRefreshRateLimit;
}
public long getTtl() {
return ttl;
}
public void setTtl(long ttl) {
this.ttl = ttl;
}
public String getPublicKeyEndpointUri() {
return publicKeyEndpointUri;
}
public void setPublicKeyEndpointUri(String publicKeyEndpointUri) {
this.publicKeyEndpointUri = publicKeyEndpointUri;
}
}
}

@ -0,0 +1,156 @@
package com.rootcloud.common;
import com.alibaba.fastjson.JSONObject;
import java.io.Serializable;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
public class OAuthResult implements Serializable {
private String access_token;
private Integer expires_in;
private String refresh_token;
private String code;
private String value;
private String message;
private HashMap additionalInformation;
//契合云杉登录的相关属性赋默认值
private Boolean isSystemAdmin;
private String scope;
private String tenantId;
private String token_type;
public OAuthResult() {
}
public OAuthResult(JSONObject res) {
this.access_token = res.getString("access_token");
this.refresh_token = res.getString("refresh_token");
this.expires_in = res.getIntValue("expires_in");
this.isSystemAdmin = false;
this.scope = "read";
this.tenantId = "";
this.token_type = "bearer";
}
public OAuthResult(String auth) {
this.access_token = auth;
this.refresh_token = "";
this.expires_in = 3000;
this.isSystemAdmin = false;
this.scope = "read";
this.tenantId = "";
this.token_type = "bearer";
}
public OAuthResult(String accessToken, Integer expiresIn, String refreshToken) {
this.access_token = accessToken;
this.expires_in = expiresIn;
this.refresh_token = refreshToken;
}
public String getExpiresAt() {
Instant instant = Instant.now();
Instant plus = instant.plus(expires_in, ChronoUnit.SECONDS);
return String.valueOf(plus.getEpochSecond());
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public Integer getExpires_in() {
return expires_in;
}
public void setExpires_in(Integer expires_in) {
this.expires_in = expires_in;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public HashMap getAdditionalInformation() {
return additionalInformation;
}
public void setAdditionalInformation(HashMap additionalInformation) {
this.additionalInformation = additionalInformation;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Boolean getSystemAdmin() {
return isSystemAdmin;
}
public void setSystemAdmin(Boolean systemAdmin) {
isSystemAdmin = systemAdmin;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

@ -0,0 +1,47 @@
package com.rootcloud.common;
import io.swagger.annotations.ApiModelProperty;
import javax.validation.constraints.NotNull;
public class PageAO {
@ApiModelProperty("当前页数")
@NotNull(message = "当前页数不能为空")
private Integer pageNum;
@ApiModelProperty("分页大小")
@NotNull(message = "分页大小不能为空")
private Integer pageSize;
/**
* 默认页
*/
private static final int DEFAULT_PAGE = 1;
/**
* 每页大小
*/
private static final int DEFAULT_SIZE = 12;
public Integer getPageNum() {
if (this.pageNum == null){
return DEFAULT_PAGE;
}
return Math.max(DEFAULT_PAGE, pageNum);
}
public Integer getPageSize() {
if (this.pageSize == null){
return DEFAULT_SIZE;
}
// 检验pageSize小于等于0时给默认大小
if (pageSize <= 0){
return Math.max(pageSize, DEFAULT_SIZE);
}
// 校验页面大小不能大于DEFAULT_SIZE
return Math.min(pageSize, DEFAULT_SIZE);
}
}

@ -0,0 +1,41 @@
package com.rootcloud.common;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @Author: jun2.wang
* @Date: 2021/5/28
*/
@Data
@ApiModel("查询分页参数")
public class PageRequest {
@ApiModelProperty(value = "一页大小")
private Integer size;
@ApiModelProperty(value = "页数")
private Integer page;
private static PageRequest defaultPaging = new PageRequest(0, 20);
private static int MAX_PAGESIZE = 2000;
public static PageRequest normalize(PageRequest paging) {
if (paging == null) {
paging = defaultPaging;
}
if (paging.page < 0) {
paging.setPage(0);
}
if (paging.size > MAX_PAGESIZE) {
paging.setSize(MAX_PAGESIZE);
}
return paging;
}
public PageRequest() {
}
public PageRequest(Integer size, Integer page) {
this.size = size;
this.page = page;
}
}

@ -0,0 +1,181 @@
package com.rootcloud.common;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Component
public class Request {
private final Logger log = LoggerFactory.getLogger(Request.class);
/**
* 4.0 需要修改密码返回的token
*/
public static final String X_ROOTCLOUD_SETPW_TOKEN = "x-rootcloud-setpw-token";
private static RestTemplate restTemplate = new RestTemplate();
public ResponseEntity<String> requestForJP(String uri, HttpEntity<String> httpMethod) {
return restTemplate.postForEntity(uri, httpMethod, String.class);
}
public JSONObject request(String uri, HttpMethod httpMethod, MultiValueMap<String, String> headers, Object t) {
HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null) {
headers.forEach((k, v) -> {
httpHeaders.add(k, v.get(0));
});
}
if (log.isDebugEnabled()) {
log.debug("请求地址:{},请求 参数:{} , 请求headers:{}", uri,
JSONObject.toJSONString(t), JSONObject.toJSONString(httpHeaders));
}
HttpEntity request = new HttpEntity<>(t, httpHeaders);
ResponseEntity<JSONObject> responseEntity = restTemplate
.exchange(uri, httpMethod, request, JSONObject.class);
if (!responseEntity.getStatusCode().is2xxSuccessful()) {
log.error("request error result Code :{} , result: {}", responseEntity.getStatusCodeValue()
, JSONObject.toJSONString(responseEntity.getBody()));
return null;
}
JSONObject jsonResult = responseEntity.getBody();
if (log.isDebugEnabled()) {
log.debug("请求返回: {}", JSONObject.toJSONString(jsonResult));
}
return jsonResult;
}
public JSONObject requestPost(String url, Map<String, String> map) {
if (log.isDebugEnabled()) {
log.debug("请求地址:{},请求 参数:{} ", url, JSONObject.toJSONString(map));
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
headers.setAccept(Stream.of(MediaType.APPLICATION_JSON_UTF8).collect(Collectors.toList()));
HttpEntity<String> request = new HttpEntity<>(JSONObject.toJSONString(map), headers);
try {
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);
if (!responseEntity.getStatusCode().is2xxSuccessful()) {
log.error("request error result Code :{} , result: {}", responseEntity.getStatusCodeValue()
, JSONObject.toJSONString(responseEntity.getBody()));
return null;
}
JSONObject jsonResult = responseEntity.getBody();
if (log.isDebugEnabled()) {
log.debug("请求返回: {}", JSONObject.toJSONString(jsonResult));
}
return jsonResult;
} catch (HttpClientErrorException e) {
log.error("请求发生异常", e);
log.error("请求地址:{},请求 参数:{} ", url, JSONObject.toJSONString(map));
String bodyString = e.getResponseBodyAsString();
if ("".equals(bodyString)) {
return null;
}
log.error("异常返回结果:{}", bodyString);
//IAM-1003 password need to be changed
try {
JSONObject object = JSONObject.parseObject(bodyString);
String code = object.getString("code");
//IAM-1003
if ("IAM-1003".equals(code)) {
//4.0 出现这个错误码 说明密码需要重置 返回xtoken 作为给前端 重置密码
HttpHeaders httpHeaders = e.getResponseHeaders();
String setpwToken = httpHeaders.getFirst(X_ROOTCLOUD_SETPW_TOKEN);
object.put(X_ROOTCLOUD_SETPW_TOKEN, setpwToken);
return object;
}
} catch (Exception e1) {
log.error("异常结果转化异常", e1);
}
}
return null;
}
/**
* sany cas 是get 请求
*
* @param url
* @param map
* @return
*/
public JSONObject requestCasGet(String url, Map<String, String> map) {
if (log.isDebugEnabled()) {
log.debug("请求地址:{},请求 参数:{} ", url, JSONObject.toJSONString(map));
}
StringBuilder sb = new StringBuilder(url);
if (map != null) {
sb.append("?");
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
ResponseEntity<JSONObject> responseEntity = restTemplate.getForEntity(sb.toString(), JSONObject.class);
if (!responseEntity.getStatusCode().is2xxSuccessful()) {
log.error("request error result Code :{} , result: {}", responseEntity.getStatusCodeValue()
, JSONObject.toJSONString(responseEntity.getBody()));
return new JSONObject();
}
JSONObject jsonResult = responseEntity.getBody();
if (log.isDebugEnabled()) {
log.debug("请求返回: {}", JSONObject.toJSONString(jsonResult));
}
return jsonResult;
}
/**
* 发送 application from 请求
*
* @param url
* @param head
* @param map
* @return
*/
public JSONObject requestCasPost(String url, Map<String, String> head, Map<String, String> map) {
MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();
if (log.isDebugEnabled()) {
log.debug("请求地址:{},请求 参数:{} ,请求头部信息{}", url, JSONObject.toJSONString(map), head);
}
if (map != null) {
for (Map.Entry<String, String> entry : map.entrySet()) {
multiValueMap.add(entry.getKey(), entry.getValue());
}
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
if (head != null) {
head.forEach((k, v) -> headers.add(k, v));
}
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(multiValueMap, headers);
ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);
if (!responseEntity.getStatusCode().is2xxSuccessful()) {
log.error("request error result Code :{} , result: {}", responseEntity.getStatusCodeValue()
, JSONObject.toJSONString(responseEntity.getBody()));
return null;
}
JSONObject jsonResult = responseEntity.getBody();
if (log.isDebugEnabled()) {
log.debug("请求返回: {}", JSONObject.toJSONString(jsonResult));
}
return jsonResult;
}
}

@ -0,0 +1,27 @@
package com.rootcloud.common;
import com.rootcloud.config.auth.LoginUserInfo;
import com.rootcloud.config.auth.UserContext;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
public class ResourceUtil {
public static String getI18nMessage(String code) {
Locale locale ;
LoginUserInfo current = UserContext.current();
if("en".equals(current.getLanguage())){
locale = I18nUtil.localeEn;
}else {
locale = I18nUtil.localeCn;
}
// ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
// messageSource.setCacheSeconds(-1);
// messageSource.setDefaultEncoding(StandardCharsets.UTF_8.name());
// messageSource.setBasenames("i18n/messages/messages");
String message = I18nUtil.messageSource.getMessage(code, null, locale);
//I18nUtil.clear();
return message;
}
}

@ -0,0 +1,78 @@
package com.rootcloud.common;
import com.alibaba.fastjson.JSONObject;
import com.ejlchina.http.HTTP;
import com.rootcloud.common.constant.DeviceConstant;
import com.rootcloud.common.constant.RootCloudApi;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* TODO
*
* @author wei.liao
* @version 1.0
* @date 2022/4/23 16:26
*/
@Component
@Slf4j
public class RootCloudOpenAPIUtil {
@Value("${os.iam.domain}")
private String reqUrl;
@Value("${os.iam.superToken}")
private String superToken;
@Autowired
private TokenUtil tokenUtil;
@Value("${os.iam.uri:http://iothub-historian.rootcloud-platform-pre.rootcloudapp.com}")
private String openAPIUri;
protected Map<String, String> defaultHeader() {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "Bearer " + tokenUtil.getToken());
return headers;
}
protected HTTP httpClient(String baseUrl) {
return HTTP.builder().config((OkHttpClient.Builder builder) -> {
// 连接超时时间默认10秒
builder.connectTimeout(5, TimeUnit.SECONDS);
// 写入超时时间默认10秒
builder.writeTimeout(5, TimeUnit.SECONDS);
// 读取超时时间默认10秒
builder.readTimeout(5, TimeUnit.SECONDS);
}).baseUrl(baseUrl).build();
}
public Integer getDeviceCurrentStatus(String thingId) {
JSONObject device = this.httpClient(reqUrl).sync(RootCloudApi.DEVICE_CURRENT_STATUS_URI).addHeader(this.defaultHeader()).addUrlParam("thingId", thingId).get().getBody().toJsonObject();
log.info("平台设备信息:[{}]", device);
Object online = device.get("online");
if (online != null) {
if (online instanceof Boolean) {
return (Boolean) online ? DeviceConstant.ONLINE_STATUS_CODE : DeviceConstant.OFFLINE_STATUS_CODE;
}
}
return DeviceConstant.OFFLINE_STATUS_CODE;
}
public Integer getCountUnclosedDevice() {
JSONObject device = this.httpClient(openAPIUri).sync(RootCloudApi.DEVICE_UNCLOSE_COUNT_URI).addHeader(this.defaultHeader()).get().getBody().toJsonObject();
log.info("平台设备信息:[{}]", device);
Object count = device.get("count");
if (count != null) {
return Integer.parseInt((String) count);
}
return 0;
}
}

@ -0,0 +1,95 @@
package com.rootcloud.common;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.alibaba.fastjson.JSONArray;
//import jline.internal.Log;
import jline.internal.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class SendMessageUtils {
@Value(value = "${sms.server-url}")
private String SERVER_URL;
@Value(value = "${sms.app-key}")
private String APP_KEY;
@Value(value = "${sms.app-secret}")
private String APP_SECRET;
@Value(value = "${sms.nonce}")
private String NONCE;
@Value(value = "${sms.templateid}")
private String TEMPLATEID;
public void send(List<String> mobiles,List<String> params) {
this.send(mobiles,params,null);
}
public void send(List<String> mobiles,List<String> params,String templateId) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(SERVER_URL);
String curTime = String.valueOf((new Date()).getTime() / 1000L);
/*
* 参考计算CheckSum的java代码在上述文档的参数列表中有CheckSum的计算文档示例
*/
String checkSum = CheckSumBuilder.getCheckSum(APP_SECRET, NONCE, curTime);
// 设置请求的header
httpPost.addHeader("AppKey", APP_KEY);
httpPost.addHeader("Nonce", NONCE);
httpPost.addHeader("CurTime", curTime);
httpPost.addHeader("CheckSum", checkSum);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 设置请求的的参数requestBody参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
/*
* 1.如果是模板短信请注意参数mobile是有s的详细参数配置请参考发送模板短信文档
* 2.参数格式是jsonArray的格式例如 "['13888888888','13666666666']"
* 3.params是根据你模板里面有几个参数那里面的参数也是jsonArray格式
*/
if (StringUtils.isNotEmpty(templateId)){
nvps.add(new BasicNameValuePair("templateid", templateId));
}else {
nvps.add(new BasicNameValuePair("templateid", TEMPLATEID));
}
nvps.add(new BasicNameValuePair("mobiles", JSONArray.toJSONString(mobiles)));
nvps.add(new BasicNameValuePair("params", JSONArray.toJSONString(params)));
try{
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
// 执行请求
HttpResponse response = httpClient.execute(httpPost);
/*
* 1.打印执行结果打印结果一般会200315403404413414500
* 2.具体的code有问题的可以参考官网的Code状态表
*/
//System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
log.info("调用网易云信接口参数:{},返回值:{}",httpPost.getEntity(),EntityUtils.toString(response.getEntity(), "utf-8"));
// Log.info(EntityUtils.toString(response.getEntity(), "utf-8"));
}catch (IOException e){
e.printStackTrace();
log.error("发送短信失败!");
}
}
}

@ -0,0 +1,28 @@
package com.rootcloud.common;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 获取sprintBean
*/
@Component
public class SprintBeanUtils implements ApplicationContextAware {
private static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static <T> T getBean(String beanName) {
if (context.containsBean(beanName)) {
return (T) context.getBean(beanName);
} else {
return null;
}
}
}

@ -0,0 +1,211 @@
package com.rootcloud.common;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.rootcloud.config.auth.UserContext;
import com.rootcloud.domain.mapper.CommonMapper;
import jline.internal.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Component
public class TokenUtil {
@Resource
private RedisTemplate redisTemplate;
@Value(value = "${os.iam.clientid}")
private String clientId;
@Value(value = "${os.iam.clientsecret}")
private String clientSecret;
@Value(value = "${os.iam.domain}")
private String domain;
@Value(value = "${os.iam.loginuri}")
private String loginUri;
// public String superToken(){
// return "aHViLXN1cGVyLXVzZXI";
// }
@Autowired
private CommonMapper commonMapper;
public String getToken(String clientId, String clientSecret) {
String result = "";
JSONObject json = new JSONObject();
json.set("grant_type", "client_credentials");
json.set("client_id", clientId);
json.set("client_secret", clientSecret);
HttpRequest request = HttpUtil.createPost(domain + loginUri);
request.body(json.toString(), "application/json");
HttpResponse response = request.execute();
result = response.body();
JSONObject json2 = new JSONObject(result);
result = json2.get("access_token").toString();
return result;
}
public String getToken(String tenantId) {
String rediskey = "common_accessToken";
if (StringUtils.isNotBlank(tenantId)) {
rediskey = tenantId + "_accessToken";
}
Object token = null;
try {
token = redisTemplate.opsForValue().get(rediskey);
} catch (Exception e) {
redisTemplate.delete(rediskey);
}
if (token != null) {
return token.toString();
} else {
String result = "";
Map<String, String> rootClient = commonMapper.getRootClient(tenantId);
if (rootClient != null) {
clientId = rootClient.get("CLIENT_ID");
clientSecret = rootClient.get("CLIENT_SECRET");
JSONObject json = new JSONObject();
json.set("grant_type", "client_credentials");
json.set("client_id", clientId);
json.set("client_secret", clientSecret);
HttpRequest request = HttpUtil.createPost(domain + loginUri);
request.body(json.toString(), "application/json");
HttpResponse response = request.execute();
result = response.body();
JSONObject json2 = new JSONObject(result);
result = json2.get("access_token").toString();
redisTemplate.opsForValue().set(rediskey, result, 3500, TimeUnit.SECONDS);
} else {
Log.error("查询clientId为null,租户id" + tenantId);
}
return result;
}
}
/*public String getToken() {
String tenantId = UserContext.getTenantId(); //获取当前租户
String rediskey = "common_accessToken";
if (StringUtils.isNotBlank(tenantId)) {
rediskey = tenantId + "_accessToken";
}
Object token = null;
try {
token = redisTemplate.opsForValue().get(rediskey);
} catch (Exception e) {
redisTemplate.delete(rediskey);
}
if (token != null) {
return token.toString();
} else {
String result = "";
Map<String, String> rootClient = commonMapper.getRootClient(tenantId);
// rootClient = new HashMap<>(); 测试使用
// rootClient.put("CLIENT_ID","2022041578413b61ae181695");
// rootClient.put("CLIENT_SECRET","a7ed2906927805a0f6d4fa0019ea017f");
if (rootClient != null) {
clientId = rootClient.get("CLIENT_ID");
clientSecret = rootClient.get("CLIENT_SECRET");
JSONObject json = new JSONObject();
json.set("grant_type", "client_credentials");
json.set("client_id", clientId);
json.set("client_secret", clientSecret);
Log.info("获取参数:" + json.toString());
HttpRequest request = HttpUtil.createPost(domain + loginUri);
Log.info("获取路径:" + domain + loginUri);
request.body(json.toString(), "application/json");
try {
HttpResponse response = request.execute();
result = response.body();
JSONObject json2 = new JSONObject(result);
result = json2.get("access_token").toString();
redisTemplate.opsForValue().set(rediskey, result, 3500, TimeUnit.SECONDS);
} catch (Exception e) {
Log.error("获取access_token失败失败原因" + e.getMessage());
}
} else {
Log.error("查询clientId为null,租户id" + tenantId);
}
return result;
}
}*/
public String getToken() {
String tenantId = UserContext.getTenantId(); //获取当前租户
String rediskey = "common_accessToken";
if(StringUtils.isNotBlank(tenantId)){
rediskey= tenantId+"_accessToken";
}
Object token = null;
try{
token = redisTemplate.opsForValue().get(rediskey);
}catch (Exception e){
redisTemplate.delete(rediskey);
}
if (token != null) {
return token.toString();
} else {
String result = "";
Map<String,String> rootClient = commonMapper.getRootClient(tenantId);
/*Map<String,String> rootClient = new HashMap<>(); //测试使用
rootClient.put("CLIENT_ID","20221206c509e669fe968c13");
rootClient.put("CLIENT_SECRET","b9ad3dddce304e311439ee8ad7202a36");*/
if(rootClient!=null) {
clientId = rootClient.get("CLIENT_ID");
clientSecret = rootClient.get("CLIENT_SECRET");
JSONObject json = new JSONObject();
json.set("grant_type", "client_credentials");
json.set("client_id", clientId);
json.set("client_secret", clientSecret);
HttpRequest request = HttpUtil.createPost(domain + loginUri);
Log.info("访问路径:"+domain + loginUri+",访问参数:"+json);
request.body(json.toString(), "application/json");
HttpResponse response = request.execute();
result = response.body();
JSONObject json2 = new JSONObject(result);
result = json2.get("access_token").toString();
redisTemplate.opsForValue().set(rediskey, result, 3500, TimeUnit.SECONDS);
}else{
Log.error("查询clientId为null,租户id"+tenantId);
}
return result;
}
}
public static void main(String[] args) {
Map<String, String> rootClient = new HashMap<>(); //测试使用
rootClient.put("CLIENT_ID", "20221029150bbb6e7936972d");
rootClient.put("CLIENT_SECRET", "a76b4a99495e8b94154b499e88f13d00");
if (rootClient != null) {
String clientId = rootClient.get("CLIENT_ID");
String clientSecret = rootClient.get("CLIENT_SECRET");
JSONObject json = new JSONObject();
json.set("grant_type", "client_credentials");
json.set("client_id", clientId);
json.set("client_secret", clientSecret);
Log.info("获取参数:" + json.toString());
HttpRequest request = HttpUtil.createPost("https://openapi.zengcaicloud.com/account-manage/v1/auth/login");
request.body(json.toString(), "application/json");
try {
HttpResponse response = request.execute();
String result = response.body();
JSONObject json2 = new JSONObject(result);
result = json2.get("access_token").toString();
System.out.println(result);
} catch (Exception e) {
Log.error("获取access_token失败失败原因" + e.getMessage());
}
}
}
}

@ -0,0 +1,26 @@
package com.rootcloud.common;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @Author: jun2.wang
* @Date: 2021/5/25
*/
@Getter
@Setter
@ToString
public class UserOperationContext {
private String userId;
private String userName;
private String tenantId;
/**
* 浏览器
*/
private String browser;
/**
* ip
*/
private String ip;
}

@ -0,0 +1,18 @@
package com.rootcloud.common;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标记该类是否需要效验参数
* @author yang yin bo
*
*2017年4月17日 下午3:14:12
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Validate {
}

@ -0,0 +1,505 @@
package com.rootcloud.common;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rootcloud.domain.entity.NxPartFileEntity;
import com.rootcloud.domain.entity.NxPartRespEntity;
import com.rootcloud.domain.entity.Part;
import jline.internal.Log;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPMessage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WebServiceClient {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private String wsdlLocation;// webservice地址
private String action;// 命名空间
private String methodName;// 调用方法
private Map<String, String> params;// 参数键值对
/**
* 初始化调用webservice参数
*
* @param wsdlLocation webservice地址
* @param namespace 命名空间
* @param methodName 调用方法
* @param params 参数键值对
*/
public WebServiceClient(String wsdlLocation, String action, String methodName, Map<String, String> params) {
this.wsdlLocation = wsdlLocation;
this.action = action;
this.methodName = methodName;
this.params = params;
}
/**
* 获取SOAP的请求头并替换其中的标志符号为用户输入的参数及数据
*
* @param params 用户输入的参数键值对
* @return 客户将要发送给服务器的SOAP请求
*/
private String getSoapRequestSap() {
StringBuilder soapRequestData = new StringBuilder();
soapRequestData = new StringBuilder();
soapRequestData.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:rfc:functions\">");
soapRequestData.append("<soapenv:Header/>");
soapRequestData.append("<soapenv:Body>");
soapRequestData.append("<urn:" + methodName + ">");
Set<String> nameSet = params.keySet();
for (String name : nameSet) {
soapRequestData.append("<" + name + ">" + params.get(name) + "</" + name + ">");
}
soapRequestData.append("</urn:" + methodName + ">");
soapRequestData.append("</soapenv:Body>");
soapRequestData.append("</soapenv:Envelope>");
return soapRequestData.toString();
}
/**
* 用户把SOAP请求发送给服务器端并返回服务器点返回的输入流
*
* @return 服务器端返回的输入流供客户端读取
* @throws Exception
*/
public InputStream getSoapInputStreamBySap() throws Exception {
try {
String soap = getSoapRequestSap();
if (logger.isDebugEnabled()) {
logger.debug("调用SAP请求报文内容: {}", soap);
}
URL url = new URL(wsdlLocation);
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Length", Integer.toString(soap.length()));
conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
conn.setConnectTimeout(100000000);
conn.setReadTimeout(100000000);
conn.setRequestProperty("SOAPAction", action);
//认证 用户名:密码 base64
conn.setRequestProperty("Authorization", "Basic cHJkX3Bpc3VwZXI6aGFuZGhhbmQw");
OutputStream os = conn.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
osw.write(soap);
osw.flush();
osw.close();
InputStream is = conn.getInputStream();
return is;
} catch (Exception e) {
logger.info("服务端返回异常", e);
e.printStackTrace();
return null;
}
}
/**
* 对服务器端返回的XML进行解析
*/
public List<NxPartFileEntity> getPartData() {
List<NxPartFileEntity> partList = new ArrayList<NxPartFileEntity>();
try {
// InputStream is = getSoapInputStreamBySap();
//出入流直接传承xml字符串
// String result = convertStreamToString(is);
// logger.info("获取xml数据{}",result);
//String ji = "<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'><SOAP:Header/><SOAP:Body><ns0:ZDM_INVENTORYINFResponse xmlns:ns0='urn:sap-com:document:sap:rfc:functions'><ZTDM_INVENTORYINF><item><MATNR>000000000001165762</MATNR><MAKTX>三元乙丙橡胶发泡硬度20\\415*87*25</MAKTX><MTART>Z01</MTART><GROES>415*87*25</GROES><MATKL>D01004</MATKL><MEINS>EA</MEINS><NTGEW>0</NTGEW><GEWEI>KG</GEWEI><ZEINR/><BISMT/><CHARG/><WERKS>1430</WERKS><LGORT>1004</LGORT><LABST>50.000</LABST><LVORM/><ADD1> 973.45</ADD1><ADD2/><ADD3/><ADD4>000000</ADD4><ADD5/><ADD6/><ADD7/><ADD8> 19.47</ADD8><ADD9/><ADD10/></item><item><MATNR>000000000001096794</MATNR><MAKTX>气1缸\\MGPM25-125Z-XC22</MAKTX><MTART>Z01</MTART><GROES>MGPM25-125Z-XC22</GROES><MATKL>D04000</MATKL><MEINS>EA</MEINS><NTGEW>0</NTGEW><GEWEI>KG</GEWEI><ZEINR/><BISMT/><CHARG/><WERKS>1430</WERKS><LGORT>1004</LGORT><LABST>3.000</LABST><LVORM/><ADD1> 4348.67</ADD1><ADD2/><ADD3/><ADD4>000000</ADD4><ADD5/><ADD6/><ADD7/><ADD8> 724.78</ADD8><ADD9/><ADD10/></item><item><MATNR>000000000001102941</MATNR><MAKTX>压力传感器\\ZSE30AF-01-D-MGA2K-X580</MAKTX><MTART>Z01</MTART><GROES>ZSE30AF-01-D-MGA2K-X580</GROES><MATKL>D01004</MATKL><MEINS>EA</MEINS><NTGEW>0</NTGEW><GEWEI>KG</GEWEI><ZEINR/><BISMT/><CHARG/><WERKS>1430</WERKS><LGORT>1004</LGORT><LABST>4.000</LABST><LVORM/><ADD1> 68134.48</ADD1><ADD2/><ADD3/><ADD4>000000</ADD4><ADD5/><ADD6/><ADD7/><ADD8> 2129.20</ADD8><ADD9/><ADD10/></item></ZTDM_INVENTORYINF></ns0:ZDM_INVENTORYINFResponse></SOAP:Body></SOAP:Envelope>";
//logger.info("获取xml数据{}",result);
//SOAPMessage msg = formatSoapString(new ByteArrayInputStream(ji.getBytes(StandardCharsets.UTF_8)));
SOAPMessage msg = formatSoapString(getSoapInputStreamBySap());
if (msg == null) {
return new ArrayList<>();
}
SOAPBody body = msg.getSOAPBody();
if (logger.isTraceEnabled()) {
logger.trace("调用SAP获取配件结果: {}", body);
}
NodeList nodes = body.getFirstChild().getFirstChild().getChildNodes();
if (logger.isDebugEnabled()) {
logger.debug("调用SAP获取配件结果: {}", nodes);
}
for (int count = 0; count < nodes.getLength(); count++) {
Node node = nodes.item(count);
NodeList childNodes = node.getChildNodes();
NxPartFileEntity part = new NxPartFileEntity();
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
String NodeName = childNode.getNodeName();
if (null == childNode.getFirstChild()) {
continue;
}
// logger.info("配件数据======={}", childNode.getFirstChild().getTextContent());
part.setNxPartFileId(JEUuidUtil.uuid());
part.setSyCreatetime(DateUtil.getCurrentTime());
part.setSyCreateuser("system");
part.setFileSfsgjpj("0");
if ("MATNR".equals(NodeName)) { //物料编号
String code = childNode.getFirstChild().getTextContent();
code = code.replaceFirst("^0*", "");
part.setFilePjbm(code);
} else if ("MEINS".equals(NodeName)) {//基本计量单位 ==> 单位
part.setFileDw(childNode.getFirstChild().getTextContent());
} else if ("LABST".equals(NodeName)) {//库存数量
String strSl = childNode.getFirstChild().getTextContent();
if (strSl == null) break;
String replace = strSl.replace(" ", "");
BigDecimal kcsl = new BigDecimal(replace);
part.setFileKcsl(kcsl);
} else if ("ADD8".equals(NodeName)) {//实际价格==> 单位
String strPrice = childNode.getFirstChild().getTextContent();
if (strPrice == null) break;
String replace = strPrice.replace(" ", "");
BigDecimal price = new BigDecimal(replace);
part.setFileDj(price);
} else if ("MAKTX".equals(NodeName)) {//规格型号和配件名称
String content = childNode.getFirstChild().getTextContent();
String[] split = content.split("\\\\");
part.setFilePjmc(split[0]);
part.setFileGgxh(content);
} else if ("WERKS".equals(NodeName)) {//仓库名称和编码
String content = childNode.getFirstChild().getTextContent();
part.setFileCkbm(content);
part.setFileCkmc(content);
} else if ("LGORT".equals(NodeName)) {//库位编码
String content = childNode.getFirstChild().getTextContent();
part.setFileKwbm(content);
}
}
// if (!"1004".equals(part.getFileCkbm())) {
// continue;
// }
logger.info("规格型号配件名称======={}", JSONObject.toJSON(part));
if (StringUtils.isNotBlank(part.getFilePjbm())) {
partList.add(part);
}
}
} catch (Exception e) {
logger.info("解析异常", e);
e.printStackTrace();
}
if (logger.isDebugEnabled()) {
logger.debug("处理结果: {}", JSONObject.toJSONString(partList));
}
logger.info("获取数据大小为{}", partList.size());
return partList;
}
public List<Part> getPartData2() {
List<Part> partList = new ArrayList<Part>();
try {
InputStream is = getSoapInputStreamBySap();
//出入流直接传承xml字符串
//String result = convertStreamToString(is);
//logger.info("获取xml数据{}",result);
SOAPMessage msg = formatSoapString(is);
SOAPBody body = msg.getSOAPBody();
logger.info("调用SAP获取配件xml:" + body);
if (logger.isTraceEnabled()) {
logger.trace("调用SAP获取配件结果: {}", body);
}
NodeList nodes = body.getFirstChild().getFirstChild().getChildNodes();
if (logger.isDebugEnabled()) {
logger.debug("调用SAP获取配件结果: {}", nodes);
}
for (int count = 0; count < nodes.getLength(); count++) {
Node node = nodes.item(count);
NodeList childNodes = node.getChildNodes();
Part part = new Part();
String MATNR_code = "";
String MEINS = "";
String ZENDME = "";
double a = 0.0;
BigDecimal ZSJJG_price = new BigDecimal(a);
String LWEDT = "";
String WERKS = "";
String LGORT = "";
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
String NodeName = childNode.getNodeName();
if (null == childNode.getFirstChild()) {
continue;
}
if ("MATNR".equals(NodeName)) { //物料编号
String code = childNode.getFirstChild().getTextContent();
MATNR_code = code.replaceFirst("^0*", "");
} else if ("MEINS".equals(NodeName)) {//基本计量单位 ==> 单位
MEINS = childNode.getFirstChild().getTextContent();
} else if ("ZENDME".equals(NodeName)) {//库存数量 => 单位说明
ZENDME = childNode.getFirstChild().getTextContent();
} else if ("ZSJJG".equals(NodeName)) {//实际价格==> 单位
String strPrice = childNode.getFirstChild().getTextContent();
ZSJJG_price = new BigDecimal(strPrice);
} else if ("LWEDT".equals(NodeName)) {//入库日期 ==> 重量单位说明
LWEDT = childNode.getFirstChild().getTextContent();
} else if ("WERKS".equals(NodeName)) {
WERKS = childNode.getFirstChild().getTextContent();
//logger.info("工厂编号:"+WERKS);
} else if ("LGORT".equals(NodeName)) {
LGORT = childNode.getFirstChild().getTextContent();
//logger.info("库房编号:"+LGORT);
}
}
//判断当前item集合中是否出现1430库下面的1004
if (WERKS.equals("1430")) {
if (LGORT.equals("1004")) {
part.setPartCode(MATNR_code);
part.setCode(MATNR_code + ".0");
part.setUnit(MEINS); //单位
part.setUnitDesc("");//单位说明
try {
float countValue = Float.parseFloat(ZENDME);//库存数量
part.setPartInventoryCount((int) countValue);
} catch (Exception ex) {
logger.info("库存转换异常..." + ex.toString());
}
part.setPrice(ZSJJG_price);
part.setWeightUnitDesc(LWEDT);
logger.info("1430工厂编号1004 库房编号找到了...");
}
} else {
part.setPartCode(MATNR_code);
part.setCode(MATNR_code + ".0");
part.setUnit(MEINS); //单位
part.setUnitDesc("");//单位说明
try {
float countValue = Float.parseFloat(ZENDME);//库存数量
part.setPartInventoryCount((int) countValue);
} catch (Exception ex) {
logger.info("库存转换异常..." + ex.toString());
}
part.setPrice(ZSJJG_price);
part.setWeightUnitDesc(LWEDT);
// logger.info("工厂编号:"+WERKS);
// logger.info("库房编号:"+LGORT);
}
if (StringUtils.isNotBlank(part.getPartCode())) {
partList.add(part);
}
}
} catch (Exception e) {
logger.info("解析异常", e);
e.printStackTrace();
}
if (logger.isDebugEnabled()) {
logger.debug("处理结果: {}", JSONObject.toJSONString(partList));
}
logger.info("获取数据大小为{}", partList.size());
return partList;
}
//专门刷新1430/1004库存数据
public List<Part> getPartData3() {
List<Part> partList = new ArrayList<Part>();
try {
InputStream is = getSoapInputStreamBySap();
//出入流直接传承xml字符串
//String result = convertStreamToString(is);
//logger.info("获取xml数据{}",result);
SOAPMessage msg = formatSoapString(is);
SOAPBody body = msg.getSOAPBody();
logger.info("调用SAP获取配件xml:" + body);
if (logger.isTraceEnabled()) {
logger.trace("调用SAP获取配件结果: {}", body);
}
NodeList nodes = body.getFirstChild().getFirstChild().getChildNodes();
if (logger.isDebugEnabled()) {
logger.debug("调用SAP获取配件结果: {}", nodes);
}
for (int count = 0; count < nodes.getLength(); count++) {
Node node = nodes.item(count);
NodeList childNodes = node.getChildNodes();
Part part = new Part();
String MATNR_code = "";
String MEINS = "";
String ZENDME = "";
double a = 0.0;
BigDecimal ZSJJG_price = new BigDecimal(a);
String LWEDT = "";
String WERKS = "";
String LGORT = "";
for (int i = 0; i < childNodes.getLength(); i++) {
Node childNode = childNodes.item(i);
String NodeName = childNode.getNodeName();
if (null == childNode.getFirstChild()) {
continue;
}
if ("MATNR".equals(NodeName)) { //物料编号
String code = childNode.getFirstChild().getTextContent();
MATNR_code = code.replaceFirst("^0*", "");
} else if ("MEINS".equals(NodeName)) {//基本计量单位 ==> 单位
MEINS = childNode.getFirstChild().getTextContent();
} else if ("ZENDME".equals(NodeName)) {//库存数量 => 单位说明
ZENDME = childNode.getFirstChild().getTextContent();
} else if ("ZSJJG".equals(NodeName)) {//实际价格==> 单位
String strPrice = childNode.getFirstChild().getTextContent();
ZSJJG_price = new BigDecimal(strPrice);
} else if ("LWEDT".equals(NodeName)) {//入库日期 ==> 重量单位说明
LWEDT = childNode.getFirstChild().getTextContent();
} else if ("WERKS".equals(NodeName)) {
WERKS = childNode.getFirstChild().getTextContent();
//logger.info("工厂编号:"+WERKS);
} else if ("LGORT".equals(NodeName)) {
LGORT = childNode.getFirstChild().getTextContent();
//logger.info("库房编号:"+LGORT);
}
}
//判断当前item集合中是否出现1430库下面的1004
if (WERKS.equals("1430")) {
if (LGORT.equals("1004")) {
part.setPartCode(MATNR_code);
part.setCode(MATNR_code + ".0");
part.setUnit(MEINS); //单位
part.setUnitDesc("");//单位说明
try {
float countValue = Float.parseFloat(ZENDME);//库存数量
part.setPartInventoryCount((int) countValue);
} catch (Exception ex) {
logger.info("库存转换异常..." + ex.toString());
}
part.setPrice(ZSJJG_price);
part.setWeightUnitDesc(LWEDT);
logger.info("1430工厂编号1004 库房编号找到了...");
}
}
// else
// {
// part.setPartCode(MATNR_code);
// part.setCode(MATNR_code+".0");
// part.setUnit(MEINS); //单位
// part.setUnitDesc("");//单位说明
// try
// {
// float countValue = Float.parseFloat(ZENDME);//库存数量
// part.setPartInventoryCount((int) countValue);
// }catch (Exception ex)
// {
// logger.info("库存转换异常..."+ex.toString());
// }
// part.setPrice(ZSJJG_price);
// part.setWeightUnitDesc(LWEDT);
//// logger.info("工厂编号:"+WERKS);
//// logger.info("库房编号:"+LGORT);
// }
if (StringUtils.isNotBlank(part.getPartCode())) {
partList.add(part);
}
}
} catch (Exception e) {
logger.info("解析异常", e);
e.printStackTrace();
}
if (logger.isDebugEnabled()) {
logger.debug("处理结果: {}", JSONObject.toJSONString(partList));
}
logger.info("获取数据大小为{}", partList.size());
return partList;
}
@SuppressWarnings("unused")
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
private static SOAPMessage formatSoapString(InputStream is) {
MessageFactory msgFactory;
try {
msgFactory = MessageFactory.newInstance();
SOAPMessage reqMsg = msgFactory.createMessage(new MimeHeaders(), is);
reqMsg.saveChanges();
return reqMsg;
} catch (Exception e) {
Log.error("获取数据失败,失败原因:" + e.getMessage());
e.printStackTrace();
}
return null;
}
/**
* 判断是否为数字
*
* @param str
* @return
*/
public boolean isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
/**
* 测试
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// String action = "http://sap.com/xi/WebService/soap1.1";
// String methodName = "ZMM_RP002";
// String wsdlLocation = "http://61.133.215.5:50000/XISOAPAdapter/MessageServlet?senderParty=&senderService=BS_LIMS_PRD&receiverParty=&receiverService=&interface=SI_ZMM_RP002&interfaceNamespace=http://www.kocel.com/lims/zmm_rp002";
// Map<String, String> params = new ConcurrentHashMap<String, String>();
// WebServiceClient client = new WebServiceClient(wsdlLocation, action, methodName, params);
// List<Part> partList = client.getPartData();
// System.out.println(partList.size());
}
}

@ -0,0 +1,22 @@
package com.rootcloud.common.constant;
/**
* TODO
*
* @author wei.liao
* @version 1.0
* @date 2022/4/27 21:35
*/
public interface BusinessConstant {
String NETWORK_USER_STATUS_FREE = "0";
String NETWORK_USER_STATUS_BUSY = "1";
String NETWORK_USER_STATUS_UNKNOWN = "2";
//管理角色
String CUSTOMER_ROLE_MANGE = "1";
//网点角色
String CUSTOMER_ROLE_OUTLETS = "2";
//客户角色
String CUSTOMER_ROLE_CUSTOMER = "3";
}

@ -0,0 +1,19 @@
package com.rootcloud.common.constant;
/**
* TODO
*
* @author wei.liao
* @version 1.0
* @date 2022/4/19 10:21
*/
public interface DeviceConstant {
Integer OFFLINE_STATUS_CODE = 0;
Integer ONLINE_STATUS_CODE = 1;
Integer ALARM_STATUS_CODE = 2;
Integer RUN_STATUS_CODE = 3;
Integer READY_STATUS_CODE = 4;
String DEVICE_SOURCE_PLATFORM = "1";
}

@ -0,0 +1,30 @@
package com.rootcloud.common.constant;
/***
* JSON数据返回状态码
* @author Adams.huang
*
*/
public class JsonResultStatusBpm {
/***
* 系统异常
*/
public final static String RET_EXCEPTION = "50230000";
public final static String RET_EXCEPTION_CN = "系统异常";
/**
* 您没有发起此流程权限
*/
public final static String RET_UN_AUTH_START_PROC = "50230001";
public final static String RET_UN_AUTH_START_PROC_CN = "您没有发起此流程权限,请联系管理员!";
public final static String RET_SUCCESS = "200";
public final static String MSG_SUCCESS = "维修流程执行成功";
public final static String MSG_SUCCESS2 = "保养流程执行成功";
}

@ -0,0 +1,56 @@
package com.rootcloud.common.constant;
public class LappLiveConstant {
/**
* 获取token的appkey
*/
public static final String APP_KEY = "b35eae0c68324019abf3907b478f27b3";
/**
* 获取token的appsecret
*/
public static final String APP_SECRET = "121b4ca1fe8a2f9e55e6ccdcf831e91c";
/**
* 获取token的url
*/
public static final String GET_TOKEN_URL = "https://open.ys7.com/api/lapp/token/get";
/**
*打开视频直播url
*/
public static final String OPEN_LIVE_URL = "https://open.ys7.com/api/lapp/live/video/open";
/**
* 获取视频直播的url
*/
public static final String GET_LIVE_URL = "https://open.ys7.com/api/lapp/live/address/get";
//------------------乐橙---------------------------
/**
* 获取token的url
*/
public static final String GET_TOKEN_LECHENG_URL = "https://openapi.lechange.cn/openapi/accessToken";
/**
* 获取token的appkey
*/
public static final String APP_KEY_LECHENG = "lcb32eb75e1bde4003"; //AppId
/**
* 获取token的appsecret
*/
public static final String APP_SECRET_LECHENG = "c30348803e59403eb86e15bdcd00a5"; //AppSecret
/**
*打开视频直播url
*/
public static final String OPEN_LIVE_LECHENG_URL = "https://open.ys7.com/api/lapp/live/video/open";
/**
* 获取视频直播的url
*/
public static final String GET_LIVE_LECHENG_URL = "https://open.ys7.com/api/lapp/live/address/get";
public static final String LIVE_LECHENG_URL ="https://openapi.lechange.cn/openapi/bindDeviceLive";
}

@ -0,0 +1,22 @@
package com.rootcloud.common.constant;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@Data
@ConfigurationProperties(prefix = "application.jeboot")
public class Properties {
/**
* JP地址
*/
private String wfHost;
/**
* JP推送站内信接口
*/
public static final String dwr_sender_uri = "/je/dwr/sender";
}

@ -0,0 +1,17 @@
package com.rootcloud.common.constant;
/**
* @author LiPingAn 2022/6/13 20:13
* @version 1.0
**/
public class RoleIdConstant {
public final static String GLY = "10125632";
public final static String SHLD = "lEsw0MgJDhyW0S8iC3q";
public final static String FWJL = "wq3AoijXFmkUWUrKgUl";
public final static String GCS = "10125563";
public final static String KHLD = "TWybnV3LWjHEWk7DugF";
public final static String KH = "10125624";
public final static String XTGLY = "I51DPB2JBOjvtwCXZ2a";
}

@ -0,0 +1,16 @@
package com.rootcloud.common.constant;
/**
* TODO
*
* @author wei.liao
* @version 1.0
* @date 2022/4/23 16:23
*/
public interface RootCloudApi {
String DEVICE_CURRENT_STATUS_URI = "/thing-instance/v1/device/device-instances/status";
String DEVICE_UNCLOSE_COUNT_URI = "/alarms/alarm/count-unclosed-device";
}

@ -0,0 +1,32 @@
package com.rootcloud.common.constant;
import java.text.FieldPosition;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* <p>线程安全的DateFormat</p>
* @author Adams.huang
*
*/
public class SyncSimpleDateFormat extends SimpleDateFormat {
/**
*
*/
private static final long serialVersionUID = -446222332706658395L;
public SyncSimpleDateFormat(String pattern) {
super(pattern);
}
@Override
public synchronized Date parse(String source) throws ParseException {
return super.parse(source);
}
@Override
public synchronized StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
return super.format(date, toAppendTo, pos);
}
}

@ -0,0 +1,11 @@
package com.rootcloud.common.constant;
public class TemplateConstant {
public final static String TEMPLATE_ORDRE = "SY_DD1086EE";
public final static String TEMPLATE_AFTER_ORDRE = "SY_SH1086EE";
public final static String TEMPLATE_SPARE = "SY_BJ1086EE";
public final static String TEMPLATE_JSHT = "SY_JS1086EE";
public final static String TEMPLATE_FWHT = "SY_FW1086EE";
public final static String NXGX_ZH_SPLIT_TABLES = "NXGX_ZH_SPLIT_TABLES:";//宁夏共享租户数据权限隔离key
}

@ -0,0 +1,50 @@
package com.rootcloud.common.constant;
/**
* 星期几转换
* @author Adams.huang
*
*/
public enum WeekTypeEnum {
SUN(1, ""),
MON(2, ""),
TUES(3, ""),
WEDNES(4, ""),
THURS(5, ""),
FRI(6, ""),
SAT(7, "");
private WeekTypeEnum(int key, String display) {
this.key = key;
this.display = display;
}
private int key;
private String display;
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public String getDisplay() {
return display;
}
public void setDisplay(String display) {
this.display = display;
}
public static String getDisplay(int key) {
for (WeekTypeEnum item : WeekTypeEnum.values()) {
if (item.getKey() == key) {
return item.getDisplay();
}
}
return null;
}
}

@ -0,0 +1,13 @@
package com.rootcloud.common.enums;
/**
* @Author lujin
* @Description 社区基础枚举接口
* @Date on 2019/1/17.
*/
public interface BaseEnums<K,V> {
K getCode();
V getDesc();
}

@ -0,0 +1,73 @@
package com.rootcloud.common.enums;
import com.rootcloud.common.ResourceUtil;
import lombok.Getter;
/**
* <p>
* 设备打印状态
* </p>
* @author HeJia
* @since 2022/5/12
*/
public enum DeviceOnlineStatus implements BaseEnums<Integer, String> {
/**
* 离线待机打印中
*/
OFFLINE(1,"离线", ""),
ONLINE(2,"待机", "__online__.connected"),
READY(3,"待机", "SB_ZT_Ready"),
RUNNING(4,"打印中", "SB_ZT_Running");
private final Integer code;
private final String desc;
@Getter
private final String propertyId;
DeviceOnlineStatus(Integer code, String desc, String propertyId) {
this.code = code;
this.desc = desc;
this.propertyId = propertyId;
}
@Override
public Integer getCode() {
return code;
}
@Override
public String getDesc() {
switch (code){
case 1:
return ResourceUtil.getI18nMessage("60018");
case 2:
return ResourceUtil.getI18nMessage("60019");
case 3:
return ResourceUtil.getI18nMessage("60019");
case 4:
return ResourceUtil.getI18nMessage("60020");
default:
return "";
}
}
public static DeviceOnlineStatus getByPropertyId(String propertyId) {
for (DeviceOnlineStatus instance : values()) {
if (instance.propertyId.equals(propertyId)) {
return instance;
}
}
return null;
}
public static DeviceOnlineStatus getByCode(Integer code) {
for (DeviceOnlineStatus instance : values()) {
if (instance.code.equals(code)) {
return instance;
}
}
return null;
}
}

@ -0,0 +1,42 @@
package com.rootcloud.common.enums;
import org.apache.http.client.methods.*;
/**
* @Author: M
* @Date: 2019-6-27 13:19
* @Version 1.0
*/
public enum HttpRequestMethedEnum {
// HttpGet请求
HttpGet {
@Override
public HttpRequestBase createRequest(String url) {
return new HttpGet(url);
}
},
// HttpPost 请求
HttpPost {
@Override
public HttpRequestBase createRequest(String url) {
return new HttpPost(url);
}
},
// HttpPut 请求
HttpPut {
@Override
public HttpRequestBase createRequest(String url) {
return new HttpPut(url);
}
},
// HttpDelete 请求
HttpDelete {
@Override
public HttpRequestBase createRequest(String url) {
return new HttpDelete(url);
}
};
public HttpRequestBase createRequest(String url) { return null; }
}

@ -0,0 +1,68 @@
package com.rootcloud.common.enums;
/**
* @Author yangyijun
* @Description 订单枚举
* @Date on 2022/5/18
*/
public interface OrderEnums {
enum OrderStatus implements BaseEnums<String, String>{
WORKERS_TO_BE_DISPATCHED("1", "待派工"),
PENDING_ORDERS("2", "待接单"),
PENDING_CHECK_IN("3", "待签到"),
PENDING_REPORTING("4", "待报工"),
PENDING_REVIEW("5", "待审核"),
TO_BE_RETURNED("6", "待回访"),
DONE("7", "已完成"),
REJECTED("8", "已拒绝"),
TRANSFERRED("9", "已转派"),
DEPRECATED("10", "已废弃"),
DELETED("11", "已删除");
private String code;
private String desc;
OrderStatus(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
enum TodoStatus implements BaseEnums<String, String>{
UNRESOLVED("0", "未解决"),
RESOLVED("1", "已经解决");
private String code;
private String desc;
TodoStatus(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
}

@ -0,0 +1,72 @@
package com.rootcloud.common.enums;
/**
* @Author yangyijun
* @Description 订单枚举
* @Date on 2022/5/18
*/
public interface ReportStatisticsEnums {
enum DataStatus implements BaseEnums<String, String>{
NEARLY_SEVEN_DAYS("1", "近七天"),
NEARLY_A_MONTH("2", "近30天"),
MONTH("3", "当月"),
THAT_YEAR("4", "当年");
private String code;
private String desc;
DataStatus(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
enum DeviceStatus implements BaseEnums<String, String>{
HIRE("1", "出租"),
SOLD("2", "变卖"),
IDLE("3", "闲置"),
SEALED("4", "封存"),
ENABLE("5", "启用"),
SCRAP("6", "报废"),
IN_USE("7", "在用");
private String code;
private String desc;
DeviceStatus(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
}

@ -0,0 +1,372 @@
package com.rootcloud.common.enums;
/**
* @Author lujin
* @Description 社区枚举
* @Date on 2019/1/17.
*/
public interface ServicePlanEnums {
/**
* 计划周期1日2周3月4
*/
enum PlanCycle implements BaseEnums<Integer, String> {
DAY(1, ""),
WEEK(2, ""),
MONTH(3, ""),
YEAR(4, "");
private Integer code;
private String desc;
PlanCycle(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public Integer getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
// 计划类型 1维修2保养3交机4技改
enum PlanType implements BaseEnums<Integer, String> {
REPAIR(1, "维修"),
MAINTAIN(2, "保养"),
HANDOVER(3, "交机"),
TECHNICAL_TRANSFORMATION(4, "技改");
private Integer code;
private String desc;
PlanType(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public Integer getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
//计划状态0待启动1进行中2已完成3已暂停
enum PlanStatus implements BaseEnums<Integer, String> {
TO_BE_STARTED(0, "待启动"),
IN_PROGRESS(1, "进行中"),
FINISHED(2, "已完成"),
PAUSED(3, "已暂停");
private Integer code;
private String desc;
PlanStatus(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public Integer getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
// 是否超时0未超时 1已超时
enum IsTimeout implements BaseEnums<Integer, String> {
NO_TIMEOUT(0, "未超时"),
TIMED_OUT(1, "已超时");
private Integer code;
private String desc;
IsTimeout(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public Integer getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
// 提醒方式0邮件1短信 2站内信
enum RemindWay implements BaseEnums<Integer, String> {
EMAIL(0, "邮件"),
MSG(1, "短信"),
STATION_MSG(2, "站内信");
private Integer code;
private String desc;
RemindWay(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public Integer getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
/**
* 触发条件 1.系统时间 2.工况3.报警
*/
enum TriggerType implements BaseEnums<String, String> {
YSY_TIME("1", "系统时间"),
WORK_CONDITION("2", "工况"),
ALARM("3", "报警");
private final String code;
private final String desc;
TriggerType(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
/**
* 触发条件
*/
enum Condition implements BaseEnums<String, String> {
EQ("1", "等于"),
GT("2", "大于"),
GEQ("3", "大于等于"),
LT("4", "小于"),
LEQ("5", "小于等于");
private final String code;
private final String desc;
Condition(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
enum CheckType implements BaseEnums<String, String>{
CHECK_FALSE("0", ""),
CHECK_TURE("1", "");
private String code;
private String desc;
CheckType(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
enum DetailStatus implements BaseEnums<Integer, String> {
DEFAULT(0, "默认的"),
DETAIL(1, "需要处理的");
private final Integer code;
private final String desc;
DetailStatus(Integer code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public Integer getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
enum PrintStatus implements BaseEnums<String, String>{
PRINTING("1", "打印中"),
STANDBY("2", "待机"),
OFFLINE("3", "离线");
private String code;
private String desc;
PrintStatus(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
enum MessageType implements BaseEnums<String, String>{
FAULT_ALARM("1", "故障报警"),
PARAMETER_ALARM("2", "参数报警"),
MAINTENANCE_REMINDERS("3", "保养提醒"),
DEVICE_STATUS_REMINDER("4", "设备状态提醒"),
SPARE_PARTS_LIFE_WARNING_REMINDER("5", "备件寿命预警提醒"),
CONTRACT_SETTLEMENT("6", "合同及结算消息通知"),
REPAIR("001", "维修"),
MAINTENANCE("002", "保养"),
HANDOVER("003", "交机"),
TRANSFORMATION("004", "技改"),
INSPECTION("005", "巡检");
private String code;
private String desc;
MessageType(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
enum MessageCodeType implements BaseEnums<String, String>{
ORDER_MESSAGE("1", "订单消息通知"),
MAINTENANCE_MESSAGE("2", "保养计划通知"),
CONDITION_ALARM("3", "工况报警通知"),
CONTRACTS_SETTLEMENTS("4", "合同以及结算消息通知"),
SPARE_PARTS_LIFE("5", "备件寿命预警消息通知"),
REPAIR_ORDER_MESSAGE("6", "维修单消息通知");
private String code;
private String desc;
MessageCodeType(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
enum MaintenanceType implements BaseEnums<String, String>{
STATUS_NO_LAUNCH("1", "未发起状态灰色"),
STATUS_LAUNCH("2", "已发起状态蓝色"),
STATUS_FINISH("3", "正常完成绿色"),
STATUS_EXTENDED_NO_FINISH("4", "延期未完成-浅绿色"),
STATUS_EXTENDED_FINISH("5", "拖期完成橙色"),
STATUS_NO_FINISH("6", "未完成红色");
private String code;
private String desc;
MaintenanceType(String code, String desc) {
this.code = code;
this.desc = desc;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDesc() {
return this.desc;
}
}
}

@ -0,0 +1,41 @@
package com.rootcloud.common.enums;
import com.rootcloud.common.ResourceUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
@AllArgsConstructor
@Getter
public enum StatusCodeEnum {
SUCCESS("200", ResourceUtil.getI18nMessage("200")),
IMPORT_ERROR("409", ResourceUtil.getI18nMessage("409")),
EXCEPTION("13500", ResourceUtil.getI18nMessage("13500")),
INBOUND_SUCCESS("13501", ResourceUtil.getI18nMessage("13501")),
OUTBOUND_SUCCESS("13512", ResourceUtil.getI18nMessage("13512")),
OUTBOUND_FAIL("13503", ResourceUtil.getI18nMessage("13503")),
OUTBOUND_NOT_ENOUGH("13514", ResourceUtil.getI18nMessage("13514")),
USER_NOT_EXIST("13505", ResourceUtil.getI18nMessage("13505")),
OUTBOUND_SOLD_SUCCESS("13502", ResourceUtil.getI18nMessage("13502")),
PART_NOT_EXIST("13504", ResourceUtil.getI18nMessage("13504")),
DEVICE_NOT_EXIST("13506", ResourceUtil.getI18nMessage("13506")),
DEVICE_WORK_STATUS_NOT_EXIST("13508", ResourceUtil.getI18nMessage("13508")),
HISTORY_DEVICE_NOT_EXIST("14001", ResourceUtil.getI18nMessage("14001")),
ORDER_NOT_EXIST("15001", ResourceUtil.getI18nMessage("15001")),
SING_IN_ONLY_STATUS("15002", ResourceUtil.getI18nMessage("15002")),
SERVICE_PLAN_NOT_EXIST("16001", ResourceUtil.getI18nMessage("16001")),
SERVICE_PLAN_NOT_DELETE("16002", ResourceUtil.getI18nMessage("16002")),
SERVICE_PLAN_NOT_STOP("16003", ResourceUtil.getI18nMessage("16003")),
SERVICE_PLAN_NOT_FINISH("16004", ResourceUtil.getI18nMessage("16004")),
SERVICE_PLAN_NOT_STAR("16005", ResourceUtil.getI18nMessage("16005")),
SERVICE_PLAN_NOT_CALENDAR("16006", ResourceUtil.getI18nMessage("16006")),
SING_IN_NOT_PASS("17001", ResourceUtil.getI18nMessage("17001")),
TODO_NOT_EXIST("18001", ResourceUtil.getI18nMessage("18001")),
TODO_NOT_STATUS("18002", ResourceUtil.getI18nMessage("18002")),
FAIL_CALL_INTERFACE("40000", ResourceUtil.getI18nMessage("40000")),
ALARM_TYPE_REQUIRED("13507",ResourceUtil.getI18nMessage("13507")),
ABNORMAL_CHECK_IN("60021",ResourceUtil.getI18nMessage("60021")),
GET_CURRENT_LOCATION_EXCEPTION("60022",ResourceUtil.getI18nMessage("60022"))
;
private String ret;
private String message;
}

@ -0,0 +1,264 @@
package com.rootcloud.common.intercept;
import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.alibaba.druid.util.JdbcConstants;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.handlers.AbstractSqlParserHandler;
import com.rootcloud.common.constant.TemplateConstant;
import com.rootcloud.config.auth.UserContext;
import jline.internal.Log;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.*;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.io.StringReader;
import java.sql.Connection;
import java.util.*;
@Slf4j
@AllArgsConstructor
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
@Component
public class DataScopeInterceptor extends AbstractSqlParserHandler implements Interceptor {
private DataSource dataSource;
@Autowired
private RedisTemplate redisTemplate;
private static final List NO_STATEMENT_SQL = new ArrayList();
static {
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.orderStatisticByDay");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.orderStatisticByDayMonth");
NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.ConfigDao.listTable_zhid");
NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.ConfigDao.listTable_syzhid");
NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.JeCoreEnduserDao.getTenantInfoNOSQL");
NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.gkjk.NxJeDeviceDao.devicePage");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.checkPersonStatistic");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxTodoLibraryMapper.getPage");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.ServicePlanMapper.getCustomerAndRoles");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.ServicePlanMapper.selectOutletsIdByCustomerId");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.ServicePlanMapper.selectListXMBY");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.ServicePlanMapper.selectByParams");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.ServicePlanMapper.selectSysTimeList");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.ServicePlanMapper.selectOne");
NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.gkjk.NxJeDeviceDao.selectOne");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.getSpartPartList");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.countSpartPartList");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxUserInfoMapper.selectBySeviceCode");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.SpareFilerMapper.getSparePartByAzwh");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.SpareFilerMapper.getxtmkBypjbm2");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.SpareFilerMapper.getSparePartBySbbmAndPjbm");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.SpareFilerMapper.getSparePartByAzwh");
NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.SpareFilerMapper.getSparePartBySbbm");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.JeCoreEnduserDao.getUser");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.JeCoreEnduserDao.getSiteByUserId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.JeCoreEnduserDao.getCustomsByUserId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.JeCoreEnduserDao.getCustomsBySiteAreaName");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.JeCoreEnduserDao.selectList");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxJeDeviceDao.selectByUserId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxJeDeviceDao.countByUserId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.ServicePlanMapper.selectByUserId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.ServicePlanMapper.countByUserId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.selectByUserId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.countByUserId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.getSpartPartList");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.countSpartPartList");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.getNxgxJcdaFwryByUserId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.getCoreEnduserByUsrId");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.getfwwd");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.mapper.NxOrderMapper.getKhBykhdzs");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.ds.selectBykhmc");
// NO_STATEMENT_SQL.add("com.rootcloud.domain.dao.ds.selectByUserId");
}
//不拦截sql
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
this.sqlParser(metaObject);
// 先判断是不是SELECT操作 不是直接过滤
MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
return invocation.proceed();
}
BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
String sql = boundSql.getSql();
// Log.info("原sql:" + sql);
if(NO_STATEMENT_SQL.contains(mappedStatement.getId())){ //不拦截sql
return invocation.proceed();
}
//判断是否在表名列表
String zhid = UserContext.getUserTenantId(); //需要进行租户ID过滤
//zhid = "aaa"; //TODO
if(StringUtils.isBlank(zhid)){
return invocation.proceed();
}
// Log.info("需要进行租户ID过滤"+zhid);
CCJSqlParserManager parserManager = new CCJSqlParserManager();
Select select = (Select) parserManager.parse(new StringReader(sql));
PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
addWhere(plainSelect,null, zhid);
if (plainSelect.getJoins() != null) { // 是否存关联连接, 主表已经加了过滤条件了,除非特殊情况才进行处理.
List<Join> joins = plainSelect.getJoins();
for (Join join : joins){
addWhere(plainSelect,join,zhid);
}
}
//获取select列项,判断是否有子查询
if (plainSelect.getSelectItems() != null) {
List<SelectItem> subSelectItem = plainSelect.getSelectItems();
for (SelectItem subSelect :
subSelectItem) {
if (subSelect instanceof SelectExpressionItem) {
SelectExpressionItem selectExpressionItem = (SelectExpressionItem) subSelect;
if (!(selectExpressionItem.getExpression() instanceof Column)) {
//如果子列是一个子查询
Expression expression_col = selectExpressionItem.getExpression();
if (expression_col instanceof SubSelect) {
SubSelect subselect = (SubSelect) expression_col;
PlainSelect subPlainSelect = (PlainSelect)subselect.getSelectBody();
addWhere(subPlainSelect,null,zhid);
}
}
}
}
}
//Log.info("改造sql:" + select.toString());
metaObject.setValue("delegate.boundSql.sql", select.toString());
return invocation.proceed();
}
/**
* 增加 where条件
* @param plainSelect
*/
private void addWhere(PlainSelect plainSelect,Join join,String zhid) throws JSQLParserException {
String tableName = "";
String alias = "";
if (join == null) {
tableName = plainSelect.getFromItem().toString().toLowerCase();
alias = plainSelect.getFromItem().getAlias()!=null?plainSelect.getFromItem().getAlias().getName():"";
} else {
tableName = join.getRightItem().toString().toLowerCase();
alias = join.getRightItem().getAlias()!=null?join.getRightItem().getAlias().getName():"";
}
if (tableName.indexOf(" ") != -1) {
tableName = tableName.substring(0, tableName.indexOf(" "));
}
// 判断表明是否存在ZHID或者SY_ZHID字段 从redis获取,如果为null,直接return
Object obj = redisTemplate.opsForValue().get(TemplateConstant.NXGX_ZH_SPLIT_TABLES + tableName);
// obj = "aa";//TODO
//System.out.println(tableName + "表获取resids换缓存:" + obj);
if (obj != null && StringUtils.isNotBlank(obj.toString())) {
StringBuffer whereSql = new StringBuffer();
if (StringUtils.isNotBlank(alias)) {
//存在别名
whereSql.append(alias + "." + obj.toString() + " = '" + zhid + "'");
} else {
whereSql.append(obj.toString() + " = '" + zhid + "'"); //需要进行租户ID过滤
}
Expression where = plainSelect.getWhere();
if (where == null) {
if (whereSql.length() > 0) {
Expression expression = CCJSqlParserUtil
.parseCondExpression(whereSql.toString());
Expression whereExpression = (Expression) expression;
plainSelect.setWhere(whereExpression);
}
} else {
if (whereSql.length() > 0) {
//where条件之前存在需要重新进行拼接
whereSql.append(" and " + where.toString());
} else {
//新增片段不存在使用之前的sql
whereSql.append(where.toString());
}
Expression expression = CCJSqlParserUtil
.parseCondExpression(whereSql.toString());
plainSelect.setWhere(expression);
}
}
}
/**
* 获取sql中所有的表名
* @param boundSql
* @return
*/
private List<String> getTableName(BoundSql boundSql) {
List<SQLStatement> stmtList = SQLUtils.parseStatements(boundSql.getSql(), JdbcConstants.MYSQL);
List<String> tableNameList = new ArrayList<>();
for (SQLStatement stmt : stmtList) {
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
visitor.getTables().keySet().forEach(s -> tableNameList.add(s.getName()));
}
return tableNameList;
}
/**
* 生成拦截对象的代理
*
* @param target 目标对象
* @return 代理对象
*/
@Override
public Object plugin(Object target) {
if (target instanceof StatementHandler) {
return Plugin.wrap(target, this);
}
return target;
}
/**
* mybatis配置的属性
*
* @param properties mybatis配置的属性
*/
@Override
public void setProperties(Properties properties) {
}
}

@ -0,0 +1,30 @@
package com.rootcloud.common.intercept;
import com.rootcloud.common.I18nUtil;
import com.rootcloud.config.auth.LoginUserInfo;
import com.rootcloud.config.auth.UserContext;
import groovy.util.logging.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 语言全局拦截器
*/
@Slf4j
public class LanguageIntercept extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
// Object language = redisTemplate.opsForValue().get("user_id~language");
// LoginUserInfo current = UserContext.current();
// if("en".equals(current.getLanguage())){
// I18nUtil.setLocale("en","US");
// }else{
// I18nUtil.setLocale("zh","CN");
// }
return true;
}
}

@ -0,0 +1,65 @@
package com.rootcloud.common.live;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 使用ConcurrentHashMap做一个简易的缓存目前只是添加如需其他的方法可自行添加
* @author fandi
*
*/
public class CacheMap {
// 设置过期时间为5天
public static int EXPIRE_DAY = 5;
/**
* 数据缓存map
*/
public static Map<String, String> dataMap = new ConcurrentHashMap<String, String>();
/**
* 数据缓存过期map
*/
public static Map<String, Date> dataExpireMap = new ConcurrentHashMap<String, Date>();
/**
* 将一个keyvalue值放入内存缓存,并设置过期天数
*
* @param key
* @param val
* @param EXPIRE_DAY
*/
public static void put(String key, String val) {
dataMap.put(key, val);
dataExpireMap.put(key, DateUtil.getAfterDate(new Date(), EXPIRE_DAY));
}
/**
* 从缓存中获取一个key的数据(若过期返回null)
*
* @param key
* @return
*/
public static String get(String cacheKey) {
String obj = "";
Date expireDate = CacheMap.dataExpireMap.get(cacheKey);
//如果过期时间不为空或者当前时间与过期时间的差小于0则说明当前的缓存有效
if (expireDate != null && DateUtil.getDateSpace(expireDate, new Date()) < 0) {
obj = CacheMap.dataMap.get(cacheKey);
}
return obj;
}
/**
* 判断是否存在一个key
* @param key
* @return
*/
public static boolean hasCache(String key) {
return CacheMap.dataMap.containsKey(key);
}
}

@ -0,0 +1,65 @@
package com.rootcloud.common.live;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* 使用ConcurrentHashMap做一个简易的缓存目前只是添加如需其他的方法可自行添加
* @author fandi
*
*/
public class CacheMap2 {
// 设置过期时间为3天
public static int EXPIRE_DAY = 3;
/**
* 数据缓存map
*/
public static Map<String, String> dataMap = new ConcurrentHashMap<String, String>();
/**
* 数据缓存过期map
*/
public static Map<String, Date> dataExpireMap = new ConcurrentHashMap<String, Date>();
/**
* 将一个keyvalue值放入内存缓存,并设置过期天数
*
* @param key
* @param val
* @param EXPIRE_DAY
*/
public static void put(String key, String val) {
dataMap.put(key, val);
dataExpireMap.put(key, DateUtil.getAfterDate(new Date(), EXPIRE_DAY));
}
/**
* 从缓存中获取一个key的数据(若过期返回null)
*
* @param key
* @return
*/
public static String get(String cacheKey) {
String obj = "";
Date expireDate = CacheMap2.dataExpireMap.get(cacheKey);
//如果过期时间不为空或者当前时间与过期时间的差小于0则说明当前的缓存有效
if (expireDate != null && DateUtil.getDateSpace(expireDate, new Date()) < 0) {
obj = CacheMap2.dataMap.get(cacheKey);
}
return obj;
}
/**
* 判断是否存在一个key
* @param key
* @return
*/
public static boolean hasCache(String key) {
return CacheMap2.dataMap.containsKey(key);
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,54 @@
package com.rootcloud.common.net;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
import org.apache.commons.lang3.StringUtils;
import java.text.SimpleDateFormat;
/**
* json日期转化工具类
*
* @version 1.0
* @author WuXiaoJun
* @date 2015年9月22日 下午10:01:08
*/
public class DateJsonValueProcessor implements JsonValueProcessor {
private String format;
public DateJsonValueProcessor() {
}
public DateJsonValueProcessor(String format) {
this.format = format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig) {
return null;
}
public Object processObjectValue(String key, Object value,
JsonConfig jsonConfig) {
if (value == null) {
return "";
}
if (value instanceof java.sql.Timestamp) {
String str = new SimpleDateFormat(format)
.format((java.sql.Timestamp) value);
return str;
}
if (value instanceof java.util.Date) {
if(StringUtils.isNotBlank(format)){
String str = new SimpleDateFormat(format)
.format((java.sql.Timestamp) value);
return str;
}else{
Long time = ((java.util.Date) value).getTime();
return time;
}
}
return value.toString();
}
}

@ -0,0 +1,474 @@
package com.rootcloud.common.net;
import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.JSONUtils;
import net.sf.json.util.PropertyFilter;
import org.apache.commons.lang3.StringUtils;
import java.io.*;
import java.util.Collection;
import java.util.Date;
import java.util.List;
/**
* JSON数据转换工具
* @version 1.0
* @author Adams Fum
* @date 2015年7月31日 下午10:05:17
*/
public class JsonHelper {
private static final String ENCODING = "UTF-8";
// 输出配置
static JsonConfig toJsonConfig = new JsonConfig();
// 输入配置
static JsonConfig getJsonConfig = new JsonConfig();
static PropertyFilter filter = new PropertyFilter(){
@SuppressWarnings("rawtypes")
public boolean apply(Object source, String name, Object value) {
if ( JSONUtils.isNull( value )) {
return true; // 返回 true, 表示这个属性将被过滤掉
}else if(JSONUtils.isString(value) && StringUtils.isBlank((String)value)){
return true;
}else if(value instanceof String[] && ((String[])value).length == 0){
return true;
}else if(value instanceof Collection && ((Collection)value).size() == 0){
return true;
}
return false;
}
};
static{
getJsonConfig.setJsonPropertyFilter(filter);
toJsonConfig.setJsonPropertyFilter(filter);
toJsonConfig.registerJsonValueProcessor(Date.class, new DateJsonValueProcessor());
JSONUtils.getMorpherRegistry().registerMorpher(new TimestampToDateMorpher());
String[] InputFormats = new String[] {"yyyy-MM-dd HH:mm:ss","yyyyMMddHHmmss","yyyy-MM-dd"};
JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(InputFormats));
}
/**
*
* 从普通的Bean转换为字符串
* @param o
* @return
* @author Administrator
* @date 2014-1-9
*/
public static String getJson(Object o){
JSONObject jo=JSONObject.fromObject(o,toJsonConfig);
return jo.toString();
}
/**
*
* 从普通的Bean转换为Json对象
* @param o
* @return
* @author Administrator
* @date 2014-1-9
*/
public static JSONObject getJsonObject(Object o){
JSONObject jo=JSONObject.fromObject(o,toJsonConfig);
return jo;
}
/**
* 从Java的列表转换为字符串
*
* @param list
* @return
* @author Administrator
* @date 2014-1-9
*/
public static <T> String getJson(List<T> list){
JSONArray ja=JSONArray.fromObject(list,toJsonConfig);
return ja.toString();
}
/**
* 从Java的列表转换为Json数组
*
* @param list
* @return
* @author Administrator
* @date 2014-1-9
*/
public static <T> JSONArray getJsonArray(List<T> list){
JSONArray ja=JSONArray.fromObject(list,toJsonConfig);
return ja;
}
/**
* 从Java对象数组转换为字符串
* @param arry
* @return
* @author Administrator
* @date 2014-1-9
*/
public static String getJson(Object[] arry){
JSONArray ja=JSONArray.fromObject(arry,toJsonConfig);
return ja.toString();
}
/**
* 从Java对象数组转换为Json数组
* @param arry
* @return
* @author Administrator
* @date 2014-1-9
*/
public static JSONArray getJsonArray(Object[] arry){
JSONArray ja=JSONArray.fromObject(arry,toJsonConfig);
return ja;
}
/**
* 从Json对象转换为Java对象
* @param jsonObject
* @return
* @author Administrator
* @date 2014-1-9
*/
public static Object toBean(JSONObject jsonObject){
return JSONObject.toBean(jsonObject);
}
/**
* 从Json对象转换为Java对象
*
* @param jsonObject
* @param beanClass
* @return
* @author Administrator
* @date 2014-1-9
*/
public static <T> Object toBean(JSONObject jsonObject,Class<T> beanClass){
return JSONObject.toBean(jsonObject, beanClass);
}
/**
* 从json格式的字符串转换为Map对象
* @param s
* @return
* @author Administrator
* @date 2014-1-9
*/
public static Object toBean(String s){
return JSONObject.fromObject(s, getJsonConfig);
}
/**
* 从json格式的字符串转换为某个Bean
*
* @param s
* @param cls
* @return
* @author Administrator
* @date 2014-1-9
*/
public static <T> Object toBean(String s,Class<T> cls){
JSONObject jo=JSONObject.fromObject(s, getJsonConfig);
return JSONObject.toBean(jo, cls);
}
/**
* 从json字符串格式转换为Collection
*
* @param jsonArray
* @return
* @author Administrator
* @date 2014-1-9
*/
@SuppressWarnings("unchecked")
public static <T> Collection<T> toCollection(String s){
return JSONArray.toCollection(JSONArray.fromObject(s,getJsonConfig));
}
/**
* 从json字符串格式转换为Collection
*
* @param jsonArray
* @param cls
* @return
* @author Administrator
* @date 2014-1-9
*/
@SuppressWarnings("unchecked")
public static <T> Collection<T> toCollection(String s,Class<T> cls){
return JSONArray.toCollection(JSONArray.fromObject(s,getJsonConfig),cls);
}
/**
* 从json数组格式转换为Collection
*
* @param jsonArray
* @param cls
* @return
* @author Administrator
* @date 2014-1-9
*/
@SuppressWarnings("unchecked")
public static <T> Collection<T> toCollection(JSONArray jsonArray,Class<T> cls){
return JSONArray.toCollection(jsonArray, cls);
}
/**
* 从json数组格式转换为Collection
*
* @param jsonArray
* @return
* @author Administrator
* @date 2014-1-9
*/
@SuppressWarnings("unchecked")
public static <T>Collection<T> toCollection(JSONArray jsonArray){
return JSONArray.toCollection(jsonArray);
}
/**
* 从json格式的字符串转换为JSONArray数组
*
* @param s
* @return
* @author Administrator
* @date 2014-1-9
*/
public static JSONArray getJsonArray(String s){
return JSONArray.fromObject(s,toJsonConfig);
}
/**
* 从json格式的字符串转换为某类对象的数组
*
* @param s
* @param cls
* @return
* @author Administrator
* @date 2014-1-9
*/
@SuppressWarnings("rawtypes")
public static Object getArray(String s,Class cls){
JSONArray ja=JSONArray.fromObject(s,toJsonConfig);
return JSONArray.toArray(ja, cls);
}
/**
* 读取json文件
*
* @param filePath 文件路+文件名称d:\\json\myfile.json
* @return
* @author Adams Fum
* @date 2014年12月16日
*/
public static JSONObject readJsonObject(String filePath) {
BufferedReader reader = null;
// 返回值,使用StringBuffer
StringBuffer data = new StringBuffer();
try {
// 指定读取文件的编码格式要和写入的格式一致以免出现中文乱码
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),
ENCODING));
String str = null;
while ((str = reader.readLine()) != null) {
data.append(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭文件流
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return getJsonObject(data.toString());
}
/**
* 读取json文件
*
* @param filePath 文件路+文件名称d:\\json\myfile.json
* @param beanClass
* @return
* @author Adams Fum
* @date 2014年12月16日
*/
public static <T> Object readJsonToBean(String filePath,Class<T> beanClass) {
return toBean(readJsonObject(filePath), beanClass);
}
/**
* 读取json文件
*
* @param filePath 文件路+文件名称d:\\json\myfile.json
* @return
* @author Adams Fum
* @date 2014年12月16日
*/
public static Object readJsonToBean(String filePath) {
return toBean(readJsonObject(filePath));
}
/**
* 读取json文件
*
* @param filePath 文件路+文件名称d:\\json\myfile.json
* @return
* @author Adams Fum
* @date 2014年12月16日
*/
public static JSONArray readJsonArray(String filePath) {
BufferedReader reader = null;
// 返回值,使用StringBuffer
StringBuffer data = new StringBuffer();
try {
// 指定读取文件的编码格式要和写入的格式一致以免出现中文乱码
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath),
ENCODING));
String str = null;
while ((str = reader.readLine()) != null) {
data.append(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭文件流
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return getJsonArray(data.toString());
}
/**
* 读取json文件
*
* @param filePath 文件路+文件名称d:\\json\myfile.json
* @param beanClass
* @return
* @author Adams Fum
* @date 2014年12月16日
*/
public static <T> Collection<T> readJsonToCollection(String filePath,Class<T> beanClass) {
return toCollection(readJsonArray(filePath),beanClass);
}
/**
* 读取json文件
*
* @param filePath 文件路+文件名称d:\\json\myfile.json
* @return
* @author Adams Fum
* @date 2014年12月16日
*/
public static <T> Collection<T> readJsonToCollection(String filePath) {
return toCollection(readJsonArray(filePath));
}
/**
* 给定路径与Json文件存储到硬盘
*
* @param path 文件路徑不包括文件名
* @param json
* @param fileName myfile.json
* @author Adams Fum
* @date 2014年12月16日
*/
public static void writeJson(String path, Object json, String fileName) {
writeJson(path+fileName,json);
}
/**
* 给定路径与Json文件存储到硬盘
*
* @param filePath 文件路+文件名称d:\\json\myfile.json
* @param json
* @author Adams Fum
* @date 2014年12月16日
*/
public static void writeJson(String filePath, Object json) {
BufferedWriter writer = null;
File file = new File(filePath);
// 如果文件不存在则新建一个
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// 写入
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(json.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 读取json文件
*
* @param filePath 文件路+文件名称d:\\json\myfile.json
* @return
* @author Adams Fum
* @date 2014年12月16日
*/
public static JSONObject readJsonToObject(InputStream is) {
BufferedReader reader = null;
// 返回值,使用StringBuffer
StringBuffer data = new StringBuffer();
try {
// 指定读取文件的编码格式要和写入的格式一致以免出现中文乱码
reader = new BufferedReader(new InputStreamReader(is,
ENCODING));
String str = null;
while ((str = reader.readLine()) != null) {
data.append(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭文件流
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return getJsonObject(data.toString());
}
public static void main(String [] args){
System.out.println(JsonHelper.readJsonObject("D://json/domain/loginPage_zh_TW.json"));
}
}

@ -0,0 +1,296 @@
package com.rootcloud.common.net;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
/**
* 测试网络连通性
*
*/
public class NetworkHelper {
private static Logger log = LoggerFactory.getLogger(NetworkHelper.class);
private static NetworkHelper instance = null;
public static synchronized NetworkHelper getInstance(){
if(instance == null){
instance = new NetworkHelper();
}
return instance;
}
/**
* 测试本地能否ping ip
*
* @param ip
* @return
*/
public boolean isReachIp(String ip) {
boolean isReach = false;
try {
InetAddress address = InetAddress.getByName(ip);// ping this IP
if (address instanceof java.net.Inet4Address) {
log.info(ip + " is ipv4 address");
} else if (address instanceof java.net.Inet6Address) {
log.info(ip + " is ipv6 address");
} else {
log.info(ip + " is unrecongized");
}
if (address.isReachable(5000)) {
isReach = true;
log.info("SUCCESS - ping " + ip
+ " with no interface specified");
} else {
isReach = false;
log.info("FAILURE - ping " + ip
+ " with no interface specified");
}
} catch (Exception e) {
log.error("error occurs:" + e.getMessage());
}
return isReach;
}
/**
* 测试本地所有的网卡地址都能ping通 ip
*
* @param ip
* @return
*/
public boolean isReachNetworkInterfaces(String ip) {
boolean isReach = false;
try {
InetAddress address = InetAddress.getByName(ip);// ping this IP
if (address instanceof java.net.Inet4Address) {
log.info(ip + " is ipv4 address");
} else if (address instanceof java.net.Inet6Address) {
log.info(ip + " is ipv6 address");
} else {
log.info(ip + " is unrecongized");
}
if (address.isReachable(5000)) {
isReach = true;
log.info("SUCCESS - ping " + ip
+ " with no interface specified");
} else {
isReach = false;
log.info("FAILURE - ping " + ip
+ " with no interface specified");
}
if (isReach) {
log.info("-------Trying different interfaces--------");
Enumeration<NetworkInterface> netInterfaces = NetworkInterface
.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
log.info("Checking interface, DisplayName:"
+ ni.getDisplayName() + ", Name:" + ni.getName());
if (address.isReachable(ni, 0, 5000)) {
isReach = true;
log.info("SUCCESS - ping " + ip);
} else {
isReach = false;
log.info("FAILURE - ping " + ip);
}
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
log.info("IP: " + ips.nextElement().getHostAddress());
}
log.info("-----------------check now NetworkInterface is done--------------------------");
}
}
} catch (Exception e) {
log.error("error occurs:" + e.getMessage());
}
return isReach;
}
/**
* 获取能与远程主机指定端口建立连接的本机ip地址
* @param remoteAddr
* @param port
* @return
*/
public String getReachableIP(InetAddress remoteAddr, int port) {
String retIP = null;
Enumeration<NetworkInterface> netInterfaces;
try {
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> localAddrs = ni.getInetAddresses();
while (localAddrs.hasMoreElements()) {
InetAddress localAddr = localAddrs.nextElement();
if (isReachable(localAddr, remoteAddr, port, 5000)) {
retIP = localAddr.getHostAddress();
break;
}
}
}
} catch (SocketException e) {
log.error("Error occurred while listing all the local network addresses:"
+ e.getMessage());
}
if (retIP == null) {
log.info("NULL reachable local IP is found!");
} else {
log.info("Reachable local IP is found, it is " + retIP);
}
return retIP;
}
/**
* 获取能与远程主机指定端口建立连接的本机ip地址
* @param remoteIp
* @param port
* @return
*/
public String getReachableIP(String remoteIp, int port) {
String retIP = null;
InetAddress remoteAddr = null;
Enumeration<NetworkInterface> netInterfaces;
try {
remoteAddr = InetAddress.getByName(remoteIp);
netInterfaces = NetworkInterface.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> localAddrs = ni.getInetAddresses();
while (localAddrs.hasMoreElements()) {
InetAddress localAddr = localAddrs.nextElement();
if (isReachable(localAddr, remoteAddr, port, 5000)) {
retIP = localAddr.getHostAddress();
break;
}
}
}
} catch (UnknownHostException e) {
log.error("Error occurred while listing all the local network addresses:"+ e.getMessage());
}catch (SocketException e) {
log.error("Error occurred while listing all the local network addresses:"+ e.getMessage());
}
if (retIP == null) {
log.info("NULL reachable local IP is found!");
} else {
log.info("Reachable local IP is found, it is " + retIP);
}
return retIP;
}
/**
* 测试localInetAddr能否与远程的主机指定端口建立连接相连
*
* @param localInetAddr
* @param remoteInetAddr
* @param port
* @param timeout
* @return
*/
public boolean isReachable(InetAddress localInetAddr,
InetAddress remoteInetAddr, int port, int timeout) {
boolean isReachable = false;
Socket socket = null;
try {
socket = new Socket();
// 端口号设置为 0 表示在本地挑选一个可用端口进行连接
SocketAddress localSocketAddr = new InetSocketAddress(
localInetAddr, 0);
socket.bind(localSocketAddr);
InetSocketAddress endpointSocketAddr = new InetSocketAddress(
remoteInetAddr, port);
socket.connect(endpointSocketAddr, timeout);
log.info("SUCCESS - connection established! Local: "
+ localInetAddr.getHostAddress() + " remote: "
+ remoteInetAddr.getHostAddress() + " port" + port);
isReachable = true;
} catch (IOException e) {
log.error("FAILRE - CAN not connect! Local: "
+ localInetAddr.getHostAddress() + " remote: "
+ remoteInetAddr.getHostAddress() + " port" + port);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
log.error("Error occurred while closing socket:"
+ e.getMessage());
}
}
}
return isReachable;
}
/**
* 测试localIp能否与远程的主机指定端口建立连接相连
*
* @param localIp
* @param remoteIp
* @param port
* @param timeout
* @return
*/
public boolean isReachable(String localIp, String remoteIp,
int port, int timeout) {
boolean isReachable = false;
Socket socket = null;
InetAddress localInetAddr = null;
InetAddress remoteInetAddr = null;
try {
localInetAddr = InetAddress.getByName(localIp);
remoteInetAddr = InetAddress.getByName(remoteIp);
socket = new Socket();
// 端口号设置为 0 表示在本地挑选一个可用端口进行连接
SocketAddress localSocketAddr = new InetSocketAddress(
localInetAddr, 0);
socket.bind(localSocketAddr);
InetSocketAddress endpointSocketAddr = new InetSocketAddress(
remoteInetAddr, port);
socket.connect(endpointSocketAddr, timeout);
log.info("SUCCESS - connection established! Local: "
+ localInetAddr.getHostAddress() + " remote: "
+ remoteInetAddr.getHostAddress() + " port" + port);
isReachable = true;
} catch (IOException e) {
log.error("FAILRE - CAN not connect! Local: "
+ localInetAddr.getHostAddress() + " remote: "
+ remoteInetAddr.getHostAddress() + " port" + port);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
log.error("Error occurred while closing socket:"
+ e.getMessage());
}
}
}
return isReachable;
}
public static void main(String[] args) {
if(NetworkHelper.getInstance().isReachIp("61.133.215.5")){
System.out.println("=======本机可以ping通ip"+"61.133.215.5");
}
else{
System.out.println("=======本机ping不通ip"+"61.133.215.5");
}
if(NetworkHelper.getInstance().isReachNetworkInterfaces("61.133.215.5")){
System.out.println("=======本机所有网卡可以ping通ip"+"61.133.215.5");
}
else{
System.out.println("=======本机所有网卡ping不通ip"+"61.133.215.5");
}
String localIp = NetworkHelper.getInstance().getReachableIP("61.133.215.5",50000);
if(!StringUtils.isBlank(localIp)){
System.out.println("=======本机可以与ip"+"61.133.215.5"+",port:"+50000+"建立连接的IP"+localIp);
}
else{
System.out.println("=======本机不能与ip"+"61.133.215.5"+",port:"+50000+"建立连接的IP");
}
}
}

@ -0,0 +1,31 @@
package com.rootcloud.common.net;
import net.sf.ezmorph.object.AbstractObjectMorpher;
import java.util.Date;
/**
* @version 1.0
* @author WuXiaoJun
* @date 2015年9月23日 上午11:51:54
*/
public class TimestampToDateMorpher extends AbstractObjectMorpher {
public Object morph(Object value) {
if( value != null){
return new Date(Long.parseLong(String.valueOf(value)));
}
return null;
}
@Override
public Class<Date> morphsTo() {
return Date.class;
}
@SuppressWarnings("rawtypes")
public boolean supports(Class clazz ){
return Long.class.isAssignableFrom( clazz );
}
}

@ -0,0 +1,148 @@
package com.rootcloud.common.util;
import com.rootcloud.common.enums.ServicePlanEnums;
import com.rootcloud.domain.entity.sp.ServicePlanEntity;
import jline.internal.Log;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @Auther poppy.lu
* @Date 2023/01/10
* @Version 1.0
* @Describe:
*/
public class CommonUtils {
/**
* 生成固定长度随机码
*
* @param n 长度
*/
public static String getRandom(long n) {
long min = 1, max = 9;
for (int i = 1; i < n; i++) {
min *= 10;
max *= 10;
}
long rangeLong = (((long) (new Random().nextDouble() * (max - min)))) + min;
return String.valueOf(rangeLong);
}
//length用户要求产生字符串的长度
public static String getRandomString(int length) {
String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(62);
sb.append(str.charAt(number));
}
return sb.toString();
}
public static int get_random(int start, int end) {
return (int) (Math.random() * (end - start + 1) + start);
}
/**
* Object转BigDecimal类型-王雷-2018年5月14日09:56:26
*
* @param value 要转的object类型
* @return 转成的BigDecimal类型数据
*/
public static BigDecimal getBigDecimal(Object value) {
BigDecimal ret = null;
if (value != null) {
if (value instanceof BigDecimal) {
ret = (BigDecimal) value;
} else if (value instanceof String) {
ret = new BigDecimal((String) value);
} else if (value instanceof BigInteger) {
ret = new BigDecimal((BigInteger) value);
} else if (value instanceof Number) {
ret = new BigDecimal(((Number) value).doubleValue());
} else {
throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
}
}
return ret;
}
public static String uuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
/**
* 获取下一个周期时间
*
* @param servicePlan
* @return
*/
public String getNextDateByStartDateNew(ServicePlanEntity servicePlan) {
Date endDate = null;
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//获取当前日期
String current = df.format(new Date());
Date currentDate = df.parse(current);
//获取计划开始日期
endDate = df.parse(servicePlan.getPlanStartTime());
Integer planCycle = servicePlan.getPlanCycle();
Integer planInterval = servicePlan.getPlanInterval();
do {
Calendar calendar = Calendar.getInstance();
calendar.setTime(endDate);
//
if (ServicePlanEnums.PlanCycle.DAY.getCode().equals(planCycle)) {
calendar.add(Calendar.DATE, planInterval);
}
//
if (ServicePlanEnums.PlanCycle.WEEK.getCode().equals(planCycle)) {
calendar.add(Calendar.DATE, 7 * planInterval);
}
//
if (ServicePlanEnums.PlanCycle.MONTH.getCode().equals(planCycle)) {
calendar.add(Calendar.MONTH, planInterval);
}
//
if (ServicePlanEnums.PlanCycle.YEAR.getCode().equals(planCycle)) {
calendar.add(Calendar.YEAR, planInterval);
}
endDate = calendar.getTime();
System.out.println("下一周期时间:" + df.format(endDate));
} while (endDate.getTime()<=currentDate.getTime());
return df.format(endDate);
} catch (Exception e) {
Log.error("获取数据失败,失败原因:" + e.getMessage());
return null;
}
}
public static void main(String[] args) {
CommonUtils commonUtils = new CommonUtils();
ServicePlanEntity servicePlan = new ServicePlanEntity();
servicePlan.setPlanStartTime("2023-02-04");
servicePlan.setPlanCycle(1);
servicePlan.setPlanInterval(3);
String endData = commonUtils.getNextDateByStartDateNew(servicePlan);
System.out.println(endData);
}
}

@ -0,0 +1,43 @@
package com.rootcloud.common.util;
public class DateConstant {
/**
* 中文日期格式
*/
public static final String FMT_CH_DATE = "yyyy-MM-dd";
/**
* 中文时间格式
*/
public static final String FMT_CH_TIME = "HH:mm:ss";
/**
* 中文日期时间格式
*/
public static final String FMT_CH_DATETIME = "yyyy-MM-dd HH:mm:ss";
/**
* 中文日期时间格式带毫秒
*/
public static final String FMT_CH_DATETIMEMS = "yyyy-MM-dd HH:mm:ss.sss";
/**
* yyyyMMddHHmmss日期时间格式
*/
public static final String FMT_JOIN_DATETIME = "yyyyMMddHHmmss";
/**
* yyyyMMddHHmmss日期格式
*/
public static final String FMT_JOIN_DATE = "yyyyMMdd";
/**
* 中文年月格式
*/
public static final String FMT_CH_YEARMON = "yyyy-MM";
/**
* 中文年格式
*/
public static final String FMT_CH_YEAR = "yyyy";
}

@ -0,0 +1,525 @@
package com.rootcloud.common.util;
import org.apache.commons.lang3.StringUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* 2.0系统中的时间转换工具类
* */
public class DateUtils {
public static final String C_DATE_DIVISION = "-";
public static final String C_TIME_PATTON_DEFAULT = "yyyy-MM-dd HH:mm:ss";
public static final String C_DATE_PATTON_DEFAULT = "yyyy-MM-dd";
public static final String C_DATA_PATTON_YYYYMMDD = "yyyyMMdd";
public static final String C_TIME_PATTON_HHMMSS = "HH:mm:ss";
public static final int C_ONE_SECOND = 1000;
public static final int C_ONE_MINUTE = 60 * C_ONE_SECOND;
public static final int C_ONE_HOUR = 60 * C_ONE_MINUTE;
public static final long C_ONE_DAY = 24 * C_ONE_HOUR;
/**
* 按指定类型将字符类型转为日期类型
*
* @param strFormat
* @param dateValue
* @return Date
*/
public static Date parseDate(String strFormat, String dateValue) {
strFormat = StringUtils.trimToNull(strFormat);
dateValue = StringUtils.trimToNull(dateValue);
if (dateValue == null)
return null;
if (strFormat == null) {
strFormat = C_TIME_PATTON_DEFAULT;
}
SimpleDateFormat dateFormat = new SimpleDateFormat(strFormat);
Date newDate = null;
try {
newDate = dateFormat.parse(dateValue);
} catch (ParseException pe) {
newDate = null;
}
return newDate;
}
/**
* 获取两日期的天数差
*
* @param fDate
* 开始时间
* @param oDate
* 结束时间
* @return 天数差
*/
public static int daysOfTwo(Date fDate, Date oDate) {
Calendar aCalendar = Calendar.getInstance();
aCalendar.setTime(fDate);
int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
aCalendar.setTime(oDate);
int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
return day2 - day1;
}
/**
* 获取时间的日
*
* @param nowDate
* @return
*/
public static int getDay(Date nowDate) {
Calendar nowCalendar = Calendar.getInstance();
nowCalendar.setTime(nowDate);
return nowCalendar.get(Calendar.DATE);
}
/**
* 获取本周的开始时间
*
* @return
*/
public static Date getBeginDayOfWeek(Date nowdate) {
Calendar cal = Calendar.getInstance();
cal.setTime(nowdate);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
if (dayofweek == 1) {
dayofweek += 7;
}
cal.add(Calendar.DATE, 2 - dayofweek);
return cal.getTime();
}
/**
* 获取本周的结束时间
*
* @return
*/
public static Date getEndDayOfWeek(Date nowdate) {
return addDays(getBeginDayOfWeek(nowdate), 6);
}
/**
* 将Date类型的日期转换为指定格式的字符串
*
* @param aTs_Datetime
* @param as_Pattern
* @return
*/
public static String format(Date aTs_Datetime, String as_Pattern) {
if (aTs_Datetime == null || as_Pattern == null)
return null;
SimpleDateFormat dateFromat = new SimpleDateFormat();
dateFromat.applyPattern(as_Pattern);
return dateFromat.format(aTs_Datetime);
}
/**
* 取得指定日期N天后的日期
*
* @param date
* @param days
* @return
*/
public static Date addDays(Date date, int days) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days);
return cal.getTime();
}
/**
* 获取时间的月份
*
* @param nowDate
* @return
*/
public static int getMonth(Date nowDate) {
int re = 0;
Calendar nowCalendar = Calendar.getInstance();
nowCalendar.setTime(nowDate);
re = nowCalendar.get(2) + 1;
return re;
}
/**
* 获取时间的年份
*
* @param nowDate
* @return
*/
public static int getYear(Date nowDate) {
int re = 0;
Calendar nowCalendar = Calendar.getInstance();
nowCalendar.setTime(nowDate);
re = nowCalendar.get(1);
return re;
}
/***
*
* @Title: getCurrentMonthDays
* @Description: 获取当月天数
* @Author: gw_renwm2
* @Datetime: Mar 9, 2017 2:51:19 PM
* @param year 4位数
* @param month 2位数
* @return
*/
public static int getCurrentMonthDays(String year, String month) {
Date date = DateUtils.parseDate(DateConstant.FMT_CH_YEARMON, year+"-"+month);
return getCurrentMonthDays(date);
}
/***
*
* @Title: getCurrentMonthDays
* @Description: 获取当月天数
* @Author: gw_renwm2
* @Datetime: Mar 9, 2017 2:51:19 PM
* @param date 日期
* @return
*/
public static int getCurrentMonthDays(Date date) {
if (date == null) {
return 0;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DATE, 1);
c.roll(Calendar.DATE, -1);
return c.get(Calendar.DATE);
}
/***
* 获取当前月的最后一天
* params:年月2017-02
* return:本月的最后一天日期2017-02-28
*/
public static String getCurMonLastDay(String yearMonth) {
SimpleDateFormat sdf = new SimpleDateFormat(DateConstant.FMT_CH_DATE);
Calendar ca = Calendar.getInstance();
String d = yearMonth;
ca.setTime(DateUtils.parseDate(DateConstant.FMT_CH_YEARMON, d));
ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
String last = sdf.format(ca.getTime());
return last;
}
/**
*
* @Title: getTheMonLastDay
* @Description: 获取某月的最后一天如果是当年当月则是当天
* @param year
* @param mon
* @return
*/
public static int getTheMonLastDay(String year, String month) {
SimpleDateFormat sdf = new SimpleDateFormat(DateConstant.FMT_CH_DATE);
String strNow = sdf.format(new Date());
String curYear = strNow.substring(0,4);
String curMonth = strNow.substring(5,7);
if(curYear.equals(year) && curMonth.equals(month)) {
String curDay = strNow.substring(8);
return Integer.parseInt(curDay);
} else {
return getCurrentMonthDays(year, month);
}
}
/**
* 获取指定年月的最后一天如果是当前月那么取当前日期
*/
public static int getLastDay(int year, int month) {
return getTheMonLastDay(String.valueOf(year), String.valueOf(month));
}
/**
*
* @Title: getTheYearLastMon
* @Description: 获取某年的最后一月如果是当年则是当月
* @param year
* @param mon
* @return
*/
public static int getTheYearLastMon(String year) {
SimpleDateFormat sdf = new SimpleDateFormat(DateConstant.FMT_CH_DATE);
String strNow = sdf.format(new Date());
String curYear = strNow.substring(0,4);
String curMonth = strNow.substring(5,7);
if(curYear.equals(year)) {
return Integer.parseInt(curMonth);
} else {
return 12;
}
}
/**
* 获得指定季度月份
* @param quarter
* @return
*/
public static Integer[] getQuarterMonths(int quarter){
if( 1==quarter ){
return new Integer[]{1,2,3};
}else if( 2==quarter ){
return new Integer[]{4,5,6};
}else if( 3==quarter ){
return new Integer[]{7,8,9};
}else{
return new Integer[]{10,11,12};
}
}
/**
* 获得指定周开始日期和结束日期
* 需要注意跨年和跨月
* @param quarter
* @return
*/
public static List<Map<String,Object >> getWeekDays(int year, int week){
List<Map<String,Object >> result = new ArrayList<Map<String,Object >>();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Calendar cal=Calendar.getInstance();
// 设置每周的开始日期
cal.setFirstDayOfWeek(Calendar.MONDAY);
cal.set(Calendar.YEAR, year);
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
String beginDate = sdf.format(cal.getTime());
int beginYear = cal.get(Calendar.YEAR);
int beginMonth = cal.get(Calendar.MONTH)+1;
int beginDay = cal.get(Calendar.DAY_OF_MONTH);
int beginLastDay = 0 ;
cal.add(Calendar.DAY_OF_WEEK, 6);
String endDate = sdf.format(cal.getTime());
int endYear = cal.get(Calendar.YEAR);
int endMonth = cal.get(Calendar.MONTH)+1;
int endDay = cal.get(Calendar.DAY_OF_MONTH);
Integer[] beginDays = null ;
Integer[] endDays = null ;
if( beginMonth!=endMonth ){//跨月
beginLastDay = getLastDay(beginYear,beginMonth) ;
beginDays = new Integer[beginLastDay-beginDay+1];
int j=0;
for(int i= beginDay;i<=beginLastDay; i++ ){
beginDays[j]=i;
j++;
}
endDays = new Integer[endDay];
for(int i= 1;i<=endDay; i++ ){
endDays[i-1] = i;
}
}
if( beginMonth!=endMonth ){//跨月
Map<String,Object> beginData = new HashMap<String, Object>();
beginData.put("year", beginYear);
beginData.put("month", beginMonth);
beginData.put("day", beginDays);
result.add(beginData);
Map<String,Object> endData = new HashMap<String, Object>();
endData.put("year", endYear);
endData.put("month", endMonth);
endData.put("day", endDays);
result.add(endData);
}else{
beginDays = new Integer[endDay-beginDay+1];
int j = 0;
for(int i= beginDay;i<=endDay; i++ ){
beginDays[j]=i;
j++;
}
Map<String,Object> beginData = new HashMap<String, Object>();
beginData.put("year", beginYear);
beginData.put("month", beginMonth);
beginData.put("day", beginDays);
result.add(beginData);
}
System.out.println( result );
System.out.println( beginDate );
System.out.println( endDate );
return result ;
}
/**
* 根据年份和月份获得当前月的开始日期
*
* @param year
* 年份
* @param month
* 月份
*
* @return 所属月份的开始日期(java.util.Date)
*/
public static Date getMonthBegin(int year, int month) {
if (month <= 0 || month > 12)
throw new IllegalArgumentException("month must from 1 to 12");
GregorianCalendar gCal = new GregorianCalendar(year, month - 1, 1);
return gCal.getTime();
}
/**
* 根据日期获得当前月的结束日期
*
* @param month
* 日期
*
* @return 所属月份的结束日期(java.util.Date)
*/
public static Date getMonthEnd(Date month) {
GregorianCalendar ca = new GregorianCalendar();
ca.setTime(month);
int year = ca.get(GregorianCalendar.YEAR);
int mon = ca.get(GregorianCalendar.MONTH);
int lastDay = ca.getActualMaximum(GregorianCalendar.DAY_OF_MONTH);
GregorianCalendar gCal = new GregorianCalendar(year, mon, lastDay);
return gCal.getTime();
}
/**
* 根据年份和月份获得当前月的结束日期
*
* @param year
* 年份
* @param month
* 月份
*
* @return 所属月份的结束日期(java.util.Date)
*/
public static Date getMonthEnd(int year, int month) {
Date start = getMonthBegin(year, month);
return getMonthEnd(start);
}
/**
* 根据日期参数获取当前周的起始日期(周日)
*
* @param date
* 日期
*
* @return 所属星期的起始日期(java.util.Date)
*/
public static Date getWeekBegin(Date date) {
GregorianCalendar gCal = new GregorianCalendar();
gCal.setTime(date);
int startDay = gCal.getActualMinimum(GregorianCalendar.DAY_OF_WEEK);
gCal.set(GregorianCalendar.DAY_OF_WEEK, startDay);
return gCal.getTime();
}
/**
* 根据日期参数获取当前周的结束日期(周六)
*
* @param date
* 日期
*
* @return 所属星期的结束日期(java.util.Date)
*/
public static Date getWeekEnd(Date date) {
GregorianCalendar gCal = new GregorianCalendar();
gCal.setTime(date);
int lastDay = gCal.getActualMaximum(GregorianCalendar.DAY_OF_WEEK);
gCal.set(GregorianCalendar.DAY_OF_WEEK, lastDay);
return gCal.getTime();
}
/**
* 获取两个日期相差几个月
* @param startDate
* @param endDate
* @return
*/
public static int getMonthsOfTime(Date startDate,Date endDate){
Calendar c = Calendar.getInstance();
c.setTime(startDate);
c.add(Calendar.YEAR, 1); //年份加一年
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
c.setTime(endDate);
int year1 = c.get(Calendar.YEAR);
int month1 = c.get(Calendar.MONTH);
return 12*(year1-year)+month1-month;
}
/**
* 计算两个日期的多少天数(d1-d2+1)
* @param startDate
* @param endDate
* @return
* @throws ParseException
*/
public static int getDayDifference(String startDateStr,String endDateStr) throws ParseException{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
Date d1=sdf.parse(startDateStr);
Date d2=sdf.parse(endDateStr);
long num = (d1.getTime()-d2.getTime())/1000;
long days = num/(3600*24);
if(days<0)days=days*-1;
return Integer.parseInt(days+"")+1;
}
public static final String YYYY_MM_DD = "yyyy-MM-dd";
/**
* 将java.util.Date格式转换成日期字符串(yyyy-MM-dd)
*
* @return String
*/
public static String formatDate(Date date) {
SimpleDateFormat dateFromat = new SimpleDateFormat();
SimpleDateFormat df =new SimpleDateFormat("");
return df.format(date);
}
}

@ -0,0 +1,306 @@
package com.rootcloud.common.util;
//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import cn.hutool.core.codec.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
public class EncryptUtil {
public static final String MD5 = "MD5";
public static final String SHA1 = "SHA1";
public static final String HmacMD5 = "HmacMD5";
public static final String HmacSHA1 = "HmacSHA1";
public static final String DES = "DES";
public static final String AES = "AES";
/**编码格式默认使用uft-8*/
public String charset = "utf-8";
/**DES*/
public int keysizeDES = 0;
/**AES*/
public int keysizeAES = 128;
public static EncryptUtil me;
private EncryptUtil(){
//单例
}
//双重锁
public static EncryptUtil getInstance(){
if (me==null) {
synchronized (EncryptUtil.class) {
if(me == null){
me = new EncryptUtil();
}
}
}
return me;
}
/**
* 使用MessageDigest进行单向加密无密码
* @param res 被加密的文本
* @param algorithm 加密算法名称
* @return
*/
private String messageDigest(String res,String algorithm){
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] resBytes = charset==null?res.getBytes():res.getBytes(charset);
return base64(md.digest(resBytes));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 使用KeyGenerator进行单向/双向加密可设密码
* @param res 被加密的原文
* @param algorithm 加密使用的算法名称
* @param key 加密使用的秘钥
* @return
*/
private String keyGeneratorMac(String res,String algorithm,String key){
try {
SecretKey sk = null;
if (key==null) {
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
sk = kg.generateKey();
}else {
byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
sk = new SecretKeySpec(keyBytes, algorithm);
}
Mac mac = Mac.getInstance(algorithm);
mac.init(sk);
byte[] result = mac.doFinal(res.getBytes());
return base64(result);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 使用KeyGenerator双向加密DES/AES注意这里转化为字符串的时候是将2进制转为16进制格式的字符串不是直接转因为会出错
* @param res 加密的原文
* @param algorithm 加密使用的算法名称
* @param key 加密的秘钥
* @param keysize
* @param isEncode
* @return
*/
private String keyGeneratorES(String res,String algorithm,String key,int keysize,boolean isEncode){
try {
KeyGenerator kg = KeyGenerator.getInstance(algorithm);
if (keysize == 0) {
byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
kg.init(new SecureRandom(keyBytes));
}else if (key==null) {
kg.init(keysize);
}else {
byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
kg.init(keysize, new SecureRandom(keyBytes));
}
SecretKey sk = kg.generateKey();
SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
if (isEncode) {
cipher.init(Cipher.ENCRYPT_MODE, sks);
byte[] resBytes = charset==null?res.getBytes():res.getBytes(charset);
return parseByte2HexStr(cipher.doFinal(resBytes));
}else {
cipher.init(Cipher.DECRYPT_MODE, sks);
return new String(cipher.doFinal(parseHexStr2Byte(res)));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private String base64(byte[] res){
return Base64.encode(res);
}
/**将二进制转换成16进制 */
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**将16进制转换为二进制*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**
* md5加密算法进行加密不可逆
* @param res 需要加密的原文
* @return
*/
public String MD5(String res) {
return messageDigest(res, MD5);
}
/**
* md5加密算法进行加密不可逆
* @param res 需要加密的原文
* @param key 秘钥
* @return
*/
public String MD5(String res, String key) {
return keyGeneratorMac(res, HmacMD5, key);
}
/**
* 使用SHA1加密算法进行加密不可逆
* @param res 需要加密的原文
* @return
*/
public String SHA1(String res) {
return messageDigest(res, SHA1);
}
/**
* 使用SHA1加密算法进行加密不可逆
* @param res 需要加密的原文
* @param key 秘钥
* @return
*/
public String SHA1(String res, String key) {
return keyGeneratorMac(res, HmacSHA1, key);
}
/**
* 使用DES加密算法进行加密可逆
* @param res 需要加密的原文
* @param key 秘钥
* @return
*/
public String DESencode(String res, String key) {
return keyGeneratorES(res, DES, key, keysizeDES, true);
}
/**
* 对使用DES加密算法的密文进行解密可逆
* @param res 需要解密的密文
* @param key 秘钥
* @return
*/
public String DESdecode(String res, String key) {
return keyGeneratorES(res, DES, key, keysizeDES, false);
}
/**
* 使用AES加密算法经行加密可逆
* @param res 需要加密的密文
* @param key 秘钥
* @return
*/
public String AESencode(String res, String key) {
return keyGeneratorES(res, AES, key, keysizeAES, true);
}
/**
* 对使用AES加密算法的密文进行解密
* @param res 需要解密的密文
* @param key 秘钥
* @return
*/
public String AESdecode(String res, String key) {
return keyGeneratorES(res, AES, key, keysizeAES, false);
}
/**
* 使用异或进行加密
* @param res 需要加密的密文
* @param key 秘钥
* @return
*/
public String XORencode(String res, String key) {
byte[] bs = res.getBytes();
for (int i = 0; i < bs.length; i++) {
bs[i] = (byte) ((bs[i]) ^ key.hashCode());
}
return parseByte2HexStr(bs);
}
/**
* 使用异或进行解密
* @param res 需要解密的密文
* @param key 秘钥
* @return
*/
public String XORdecode(String res, String key) {
byte[] bs = parseHexStr2Byte(res);
for (int i = 0; i < bs.length; i++) {
bs[i] = (byte) ((bs[i]) ^ key.hashCode());
}
return new String(bs);
}
/**
* 直接使用异或第一调用加密第二次调用解密
* @param res 密文
* @param key 秘钥
* @return
*/
public int XOR(int res, String key) {
return res ^ key.hashCode();
}
/**
* 使用Base64进行加密
* @param res 密文
* @return
*/
public String Base64Encode(String res) {
return Base64.encode(res.getBytes());
}
/**
* 使用Base64进行解密
* @param res
* @return
*/
public String Base64Decode(String res) {
return new String(Base64.decode(res));
}
public static void main(String[] args){
EncryptUtil encryptUtil = EncryptUtil.getInstance() ;
String url = "https://iof.kocelcloud.cn/index-4.html?id=@&tenantId=C60F5F392CCDC471";
String id = encryptUtil.DESencode("415", "paras");
String id1 = encryptUtil.DESencode("418", "paras");
String id2 = encryptUtil.DESencode("416", "paras");
System.out.println(url.replaceAll("@",id));
System.out.println(url.replaceAll("@",id1));
System.out.println(url.replaceAll("@",id2));
}
}

@ -0,0 +1,108 @@
package com.rootcloud.common.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* @author w-chenhengqi
*/
@Component
public class GaoDeAPIUtils {
private final static Logger log = LoggerFactory.getLogger(GaoDeAPIUtils.class);
private static String addressUrl;
private static String key;
/**api接口参数常量 */
private static final String CODE = "code";
private static final String STATUS = "status";
private static final String INFO = "info";
private static final String INFO_CODE = "infocode";
private static final String KEY = "key";
@Value("${gode.api.key:1ad65e39043ea039f82ac56d62ea1559}")
public void setKey(String key) {
GaoDeAPIUtils.key = key;
}
@Value("${gode.api.addressUrl:https://restapi.amap.com/v3/geocode/regeo}")
public void setAddressUrl(String addressUrl){
GaoDeAPIUtils.addressUrl = addressUrl;
}
@Resource
private RedisTemplate redisTemplate;
private final String redisJwdPrefix = "gps_";
/**
* 发送请求到高德
*
* @param param 发送参数
* @return JSONArray
*/
private JSONObject getGaoDeAddress(Map<String, String> param) {
JSONObject bodyJson= null;
ResponseEntity<JSONObject> responseEntity = RestTemplateUtils.get(addressUrl, JSONObject.class, param);
//调接口成功
if (responseEntity.getStatusCode().is2xxSuccessful()) {
//获取返回内容
bodyJson = responseEntity.getBody();
//status 返回结果状态值值为0或10表示请求失败1表示请求成功
if (bodyJson != null && Objects.equals(0, bodyJson.getInteger(STATUS))) {
//info 成功时返回OK否则返回错误原因
log.warn("GaoDeAPIUtils.requestGaoDeApiGps[{}],infocode[{}]", bodyJson.getString(INFO), bodyJson.getString(INFO_CODE));
}
} else { //网络请求失败1超时2服务器错误
log.warn("GaoDeAPIUtils.requestGaoDeApiGps[{}]", "网络请求失败");
}
return bodyJson;
}
public String getAddressByJwd(String jwd){
Object addressRedis = redisTemplate.opsForValue().get(redisJwdPrefix+jwd);
String address = null;
if(addressRedis == null){
Map<String, String> param = new HashMap<>();
//key 请求服务权限标识
param.put(KEY, key);
param.put("location",jwd);
try {
log.info("高德地图查询数据==>");
JSONObject object = getGaoDeAddress(param);
log.info("高德地图返回结果==>{}",object);
if (object != null) {
JSONObject dataJson = object.getJSONObject("regeocode");
if (dataJson != null) {
address = String.valueOf(dataJson.get("formatted_address"));
}
}
}catch (Exception e){
log.info("调用高德地图查询地址失败==>{}",e.getMessage());
}
if(StringUtils.isNotBlank(address)){
redisTemplate.opsForValue().set(redisJwdPrefix+jwd, address, 1, TimeUnit.HOURS);
}
}else{
address = String.valueOf(addressRedis);
}
return address;
}
}

@ -0,0 +1,79 @@
package com.rootcloud.common.util;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BooleanSupplier;
public class MapBuilder<V> {
private Map<String, V> map;
private MapBuilder() {}
/**
* 创建一个Map构建器
* @param <V> Value类型
* @return 构建器
*/
public static <V> MapBuilder<V> of() {
MapBuilder<V> mapBuilder = new MapBuilder<>();
mapBuilder.map = new HashMap<>(16);
return mapBuilder;
}
/**
* 创建一个Map构建器
* @param <V> Value类型
* @return 构建器
*/
public static <V> MapBuilder<V> of(int size) {
MapBuilder<V> mapBuilder = new MapBuilder<>();
mapBuilder.map = new HashMap<>(size);
return mapBuilder;
}
/**
* 根据指定的Map创建一个Map构建器
* @param <V> Value类型
* @return 构建器
*/
public static <V> MapBuilder<V> of(Map<String, V> map) {
MapBuilder<V> mapBuilder = new MapBuilder<>();
mapBuilder.map = null == map ? new HashMap<>(16) : map;
return mapBuilder;
}
public MapBuilder<V> put(String k, V value) {
this.map.put(k, value);
return this;
}
public MapBuilder<V> putNotNull(String k, V value) {
if (null != value) {
this.map.put(k, value);
}
return this;
}
public MapBuilder<V> putIf(String k, V value, BooleanSupplier supplier) {
if (supplier.getAsBoolean()) {
this.map.put(k, value);
}
return this;
}
public MapBuilder<V> clear() {
this.map.clear();
return this;
}
public MapBuilder<V> remove(String k) {
this.map.remove(k);
return this;
}
public Map<String, V> build() {
return map;
}
}

@ -0,0 +1,24 @@
package com.rootcloud.common.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class OrderNumberUtils {
private static int callCount = 0;
private static String lastDate = "";
public static String generateOrderNumber() {
String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
if (!currentDate.equals(lastDate)) {
callCount = 0;
lastDate = currentDate;
}
callCount++;
return currentDate + String.format("%03d", callCount);
}
}

@ -0,0 +1,273 @@
package com.rootcloud.common.util;
import com.rootcloud.domain.vo.RepPrinterTargetDicVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
import java.util.*;
//平台设备转换帮助类
public class PlatformDeviceTransUtil {
private static final Logger logger = LoggerFactory.getLogger(PlatformDeviceTransUtil.class);
//将平台设备编码转换为用户设备编码
public static List<Map<String, Object>> repalceDevice(Map<String,String> printerDeviceRelationData, List<Map<String, Object>> list ){
List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
for( Map<String, Object> data : list ){
//平台设备编码
String platformDevice = data.get("deviceId")==null?data.get("device_id").toString():data.get("deviceId").toString();
//获取用户设备编码[含设备位置]
String userDeviceId = printerDeviceRelationData.get(platformDevice)==null?platformDevice:printerDeviceRelationData.get(platformDevice);
data.put("deviceId", userDeviceId);
data.put("device_id", userDeviceId);
datas.add(data);
}
return datas;
}
//根据value获取key
public static Set<String> repalceDevice2(Map<String,String> printerDeviceRelationData, String deviceCode ){
if(!printerDeviceRelationData.containsValue(deviceCode))
{
return null;
}
Set<String> keySet =new LinkedHashSet<String>();
for(String k:printerDeviceRelationData.keySet())
{
if(printerDeviceRelationData.get(k).equals(deviceCode))
{
keySet.add(k);
}
}
return keySet;
}
//按照设备机型分组
public static Map<String, Object> groupByDeviceType(String[] deviceTypes, List<Map<String, Object>> list,Map<String, Object> targetmap){
logger.info( "start开始按照设备机型对数据进行分组。deviceTypes"+deviceTypes+ " list:"+list );
Map<String, Object> dyxlData = new HashMap<String, Object>();
DecimalFormat df =new DecimalFormat("0.0");
int length = list==null?0:list.size();
Map<String, List<Map<String, Object>>> datas = new LinkedHashMap<String, List<Map<String, Object>>>();
for( int i=0; i<length; i++ ){
Map<String, Object> data = list.get(i);
String deviceId = data.get("deviceId").toString();
String deviceType = "" ;
for( String tmp: deviceTypes){
// if( deviceId.indexOf(tmp) >=0 ){
if( deviceId.startsWith(tmp)){
deviceType = tmp ;
}
}
RepPrinterTargetDicVO DYXL = (RepPrinterTargetDicVO) targetmap.get("DYXL"+deviceType);
if( DYXL!=null ){
String targetValue = df.format(DYXL.getTargetValue()) ;
if( datas.get(deviceType)!=null ){
List<Map<String, Object>> tmpList = datas.get(deviceType) ;
Map<String, Object> tmpdata= new HashMap<String, Object>();
tmpdata.put("deviceId", deviceId);
tmpdata.put("dyxl", data.get("dyxl"));
tmpdata.put("targetValue", targetValue);
tmpList.add(tmpdata);
datas.put(deviceType, tmpList);
}else{
List<Map<String, Object>> tmpList = new ArrayList<Map<String, Object>>() ;
Map<String, Object> tmpdata= new HashMap<String, Object>();
tmpdata.put("deviceId", deviceId);
tmpdata.put("dyxl", data.get("dyxl"));
tmpdata.put("targetValue", targetValue);
tmpList.add(tmpdata);
datas.put(deviceType, tmpList);
}
}
}
logger.info("分组后数据:"+datas);
List<String> xListDYXL = new ArrayList<String>();
List<String> dyxlList = new ArrayList<String>();
List<List<String>> listTarget = new ArrayList<List<String>>();
int index = 0;
String ratelist = "";//2218机型为___SDream机型为__2218-1最低___SDreamA最低____
String aveRatelist = "";//2218机型为___SDream机型为__
String lowRatelist = "";//2218-1最低___SDreamA最低____
for(Map.Entry<String, List<Map<String, Object>>> data: datas.entrySet() ){
String deviceType = data.getKey();
RepPrinterTargetDicVO DYXL = (RepPrinterTargetDicVO) targetmap.get("DYXL"+deviceType);
String targetValue = "null";
if( DYXL!=null ){
targetValue = df.format(DYXL.getTargetValue()) ;
}
List<Map<String, Object>> listData = data.getValue();
if( listData!=null && listData.size()>0 ){
String[] targets = new String[length+datas.size()];
float tota_dyxl=0;
String ave = "0.00";
int index2 = 0;
for( int i=0; listData!=null && i<listData.size(); i++ ){
Map<String, Object> mapdata = listData.get(i);
float dyxl = Float.parseFloat(mapdata.getOrDefault("dyxl", "0").toString());
String deviceId = mapdata.get("deviceId")==null?"":mapdata.get("deviceId").toString();
xListDYXL.add(deviceId);
dyxlList.add(df.format(dyxl));
targets[index] = targetValue ;
index++;
index2++;
tota_dyxl += dyxl ;
if( i==(listData.size()-1) ){
String dyxlStr = "<span class='xh'>"+df.format(dyxl)+"</span>";
lowRatelist += deviceId+"的打印效率最低,为"+dyxlStr+"L/h";
}
}
//平均值
xListDYXL.add("平均值");
ave = String.format("%.1f", index2==0?0:tota_dyxl/index2);
dyxlList.add(ave);
targets[index]=targetValue;
index++;
//打印效率加目标值 2020-12-1加
String rate = "<span class='xh'>"+ave+"</span>";
aveRatelist += deviceType+"机型为"+rate+"L/h(目标值:"+targetValue+"L/h)";
listTarget.add( Arrays.asList(targets) );
}
}
ratelist = aveRatelist + lowRatelist ;
logger.info("统计数据:"+ratelist);
dyxlData.put("xList", xListDYXL);
dyxlData.put("dyxlList", dyxlList);
dyxlData.put("targetValue", listTarget);
dyxlData.put("ratelist", ratelist.length()==0?"":ratelist.substring(0, ratelist.length()-1));//平均打印效率
return dyxlData ;
}
public static Map<String, Object> groupByDeviceType2(String[] deviceTypes, List<Map<String, Object>> list,Map<String, Object> targetmap){
logger.info( "start开始按照设备机型对数据进行分组。deviceTypes"+deviceTypes+ " list:"+list );
Map<String, Object> dyxlData = new HashMap<String, Object>();
DecimalFormat df =new DecimalFormat("0.0");
int length = list==null?0:list.size();
Map<String, List<Map<String, Object>>> datas = new LinkedHashMap<String, List<Map<String, Object>>>();
Map<String, Object> data1 = list.get(0);
String deviceId1 = data1.get("deviceId").toString();
String deviceType1 = "" ;
for( String tmp: deviceTypes){
// if( deviceId1.indexOf(tmp) >=0 ){
if( deviceId1.startsWith(tmp)){
deviceType1 = tmp ;
}
}
if(deviceType1.equals(""))
{
logger.info("系统配置中找不到设备"+deviceId1+"的机型...");
}
String targetValue ="";
RepPrinterTargetDicVO DYXL1 = (RepPrinterTargetDicVO) targetmap.get("DYXL"+deviceType1);
if( DYXL1!=null )
{
targetValue = df.format(DYXL1.getTargetValue()) ;
List<Map<String, Object>> tmpList = new ArrayList<Map<String, Object>>() ;
Map<String, Object> tmpdata= new HashMap<String, Object>();
tmpdata.put("deviceId", deviceId1);//1800-10
tmpdata.put("dyxl", data1.get("dyxl")); //打印效率
tmpdata.put("targetValue", targetValue); //目标值
tmpList.add(tmpdata);
datas.put(deviceType1, tmpList);
}
else
logger.info("系统配置中找不到设备"+deviceId1+"的目标值"+"DYXL"+deviceType1);
/*
for( int i=0; i<length; i++ )
{
Map<String, Object> data = list.get(i);
String deviceId = data.get("deviceId").toString();
String deviceType = "" ;
for( String tmp: deviceTypes){
if( deviceId.indexOf(tmp) >=0 ){
deviceType = tmp ;
}
}
RepPrinterTargetDicVO DYXL = (RepPrinterTargetDicVO) targetmap.get("DYXL"+deviceType);
if( DYXL!=null ){
String targetValue = df.format(DYXL.getTargetValue()) ;
if( datas.get(deviceType)!=null ){
List<Map<String, Object>> tmpList = datas.get(deviceType) ;
Map<String, Object> tmpdata= new HashMap<String, Object>();
tmpdata.put("deviceId", deviceId);
tmpdata.put("dyxl", data.get("dyxl"));
tmpdata.put("targetValue", targetValue);
tmpList.add(tmpdata);
datas.put(deviceType, tmpList);
}else{
List<Map<String, Object>> tmpList = new ArrayList<Map<String, Object>>() ;
Map<String, Object> tmpdata= new HashMap<String, Object>();
tmpdata.put("deviceId", deviceId);
tmpdata.put("dyxl", data.get("dyxl"));
tmpdata.put("targetValue", targetValue);
tmpList.add(tmpdata);
datas.put(deviceType, tmpList);
}
}
} */
logger.info("分组后数据:"+datas);
List<String> xListDYXL = new ArrayList<String>();
float tota_dyxl=0;
int index = 0;
List<String> dyxlList = new ArrayList<String>();
List<List<String>> listTarget = new ArrayList<List<String>>();
for( Map<String, Object> item : list )
{
float dyxl = Float.parseFloat(item.getOrDefault("dyxl", "0").toString());
tota_dyxl += dyxl ;
String device = item.get("deviceId").toString();
String days = item.get("day")==null?"":item.get("day").toString();
xListDYXL.add(days);
dyxlList.add(df.format(dyxl));
index++;
}
//平均值
xListDYXL.add("平均值");
String ave = String.format("%.1f", index==0?0:tota_dyxl/index);
dyxlList.add(ave);
// Map<String, Object> ave_map = new HashMap<String, Object>();
// ave_map.put("dyxl", ave);
// ave_map.put("day", "平均值");
// dataList.add(ave_map);
// logger.info("统计数据:"+ratelist);
dyxlData.put("xList", xListDYXL);
dyxlData.put("dyxlList", dyxlList);
dyxlData.put("targetValue", targetValue);
dyxlData.put("avgDyxlValue", ave);
// dyxlData.put("targetValue", listTarget);
// dyxlData.put("ratelist", ratelist.length()==0?"":ratelist.substring(0, ratelist.length()-1));//平均打印效率
return dyxlData ;
}
}

Some files were not shown because too many files have changed in this diff Show More