提交 59bcbb3f 编写于 作者: yesgohome123's avatar yesgohome123

2023年5月27日08:47:18

上级 9ad22547
# Java
*.class
*.db
*.ear
*.jar
*.war
# Intellij
.idea/
classes/
*.ids
*.iml
*.ipr
*.iws
*.orig
# Eclipse
.settings/
.classpath
.factorypath
.loadpath
.metadata
.project
*.bak
*.launch
*.pydevproject
*.swp
*.tmp
*~.nib
local.properties
# Visual Studio Code
.vscode/
# JRebel
rebel.xml
# Maven
!eweb-architect/.mvn/wrapper/maven-wrapper.jar
!maven/wrapper/maven-wrapper.jar
maven/
target/
.flattened-pom.xml
release.properties
# Gradle
!gradle/wrapper/maven-wrapper.jar
.gradle/
build/
# SVN
.svn/
# Mac OSX
.DS_Store
# Windows
._*
*.*~
*~
.merge_file*
Desktop.ini
Thumbs.db
# Others
logs/
log/
.log
.buildpath
.cproject
.externalToolBuilders/**
.Spotlight-V100
.Trashes
ARG VARIANT="11"
FROM mcr.microsoft.com/vscode/devcontainers/java:0-${VARIANT}
# [Option] Install Maven
ARG INSTALL_MAVEN="false"
ARG MAVEN_VERSION=""
# [Option] Install Gradle
ARG INSTALL_GRADLE="false"
ARG GRADLE_VERSION=""
RUN if [ "${INSTALL_MAVEN}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install maven \"${MAVEN_VERSION}\""; fi \
&& if [ "${INSTALL_GRADLE}" = "true" ]; then su vscode -c "umask 0002 && . /usr/local/sdkman/bin/sdkman-init.sh && sdk install gradle \"${GRADLE_VERSION}\""; fi
{
"name": "app",
"build": {
"dockerfile": "Dockerfile",
"args": {
"VARIANT": "11",
"INSTALL_MAVEN": "true",
"INSTALL_GRADLE": "false",
"NODE_VERSION": "lts/*"
}
},
"settings": {
"java.home": "/docker-java-home"
},
"extensions": [
"vscjava.vscode-java-pack",
"pivotal.vscode-boot-dev-pack"
],
"forwardPorts": [8081],
"remoteUser": "vscode",
"features": {
"docker-in-docker": "latest",
"docker-from-docker": "latest"
}
}
root = true
[*]
indent_style = tab
indent_size = 4
max_line_length = 120
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.{yml, bat}]
indent_size = 2
[*.md]
trim_trailing_whitespace = false
[Jenkinsfile]
indent_size = 2
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo1.maven.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION
+ "/maven-wrapper-"
+ WRAPPER_VERSION
+ ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use
* instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '"
+ outputFile.getParentFile().getAbsolutePath()
+ "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(
new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
#
# Copyright 2012-2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo1.maven.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
#
# Copyright 2012-2019 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
sonar.sourceEncoding=UTF-8
# Exclusions for copy-paste detection
#sonar.cpd.exclusions=
此差异已折叠。
<!--
- Copyright 2012-2019 the original author or authors.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- https://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-->
<svg xmlns="http://www.w3.org/2000/svg" width="94" height="20">
<linearGradient id="b" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="a">
<rect width="94" height="20" rx="3" fill="#fff"/>
</clipPath>
<g clip-path="url(#a)">
<path fill="#555" d="M0 0h61v20H0z"/>
<path fill="#007ec6" d="M61 0h33v20H61z"/>
<path fill="url(#b)" d="M0 0h94v20H0z"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif"
font-size="110">
<text x="315" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)"
textLength="510">
language
</text>
<text x="315" y="140" transform="scale(.1)" textLength="510">language</text>
<text x="765" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)"
textLength="230">
java
</text>
<text x="765" y="140" transform="scale(.1)" textLength="230">java</text>
</g>
</svg>
<!--
- Copyright 2012-2019 the original author or authors.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- https://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-->
<svg xmlns="http://www.w3.org/2000/svg" width="118" height="20">
<linearGradient id="b" x2="0" y2="100%">
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
<stop offset="1" stop-opacity=".1"/>
</linearGradient>
<clipPath id="a">
<rect width="118" height="20" rx="3" fill="#fff"/>
</clipPath>
<g clip-path="url(#a)">
<path fill="#555" d="M0 0h47v20H0z"/>
<path fill="#e05d44" d="M47 0h71v20H47z"/>
<path fill="url(#b)" d="M0 0h118v20H0z"/>
</g>
<g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif"
font-size="110">
<text x="245" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)"
textLength="370">
license
</text>
<text x="245" y="140" transform="scale(.1)" textLength="370">license</text>
<text x="815" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)"
textLength="610">
apache 2.0
</text>
<text x="815" y="140" transform="scale(.1)" textLength="610">apache 2.0</text>
</g>
</svg>
@startuml
!if %variable_exists("$THEME")
title 架构图 - $THEME theme
!else
title 架构图
!endif
'skinparam BackgroundColor transparent
[eden-architect] <<架构>>
[eden-component] <<组件>>
[eden-dependencies] <<依赖管理>>
[eden-parent] <<父工程>>
[eden-commons] <<工具集>>
[eden-extensions] <<扩展点组件>>
[eden-spring-framework] <<基础框架>>
[eden-spring-data] <<数据存储组件>>
[eden-spring-security] <<授权认证组件>>
[eden-spring-integration] <<第三方集成组件>>
[eden-spring-boot] <<Spring Boot组件>>
[eden-spring-boot-test] <<Spring Boot组件测试>>
[eden-spring-boot-starters] <<Spring Boot组件自动装配>>
[eden-spring-cloud] <<Spring Cloud组件>>
[eden-spring-cloud-starters] <<Spring Cloud组件自动装配>>
[eden-spring-test] <<Spring测试组件>>
[eden-solutions] <<解决方案>>
[eden-cola] <<COLA架构>>
[eden-cola-extensions] <<COLA扩展点>>
[eden-cola-statemachine] <<COLA状态机>>
[eden-plugins] <<插件集合>>
[eden-tests] <<测试集合>>
[eden-deployment-tests] <<部署测试集>>
[eden-integration-tests] <<集成测试集>>
[eden-performance-tests] <<性能测试集>>
[eden-smoke-tests] <<冒烟测试集>>
skinparam component {
backgroundColor<<组件>> SkyBlue
backgroundColor<<依赖管理>> SkyBlue
backgroundColor<<父工程>> SkyBlue
backgroundColor<<工具集>> SkyBlue
backgroundColor<<扩展点组件>> SkyBlue
backgroundColor<<基础框架>> SkyBlue
backgroundColor<<数据存储组件>> Pink
backgroundColor<<授权认证组件>> Pink
backgroundColor<<第三方集成组件>> Pink
backgroundColor<<Spring Boot组件>> Pink
backgroundColor<<Spring Cloud组件>> Pink
backgroundColor<<Spring Boot组件测试>> PaleGreen
backgroundColor<<Spring Boot组件自动装配>> PaleGreen
backgroundColor<<Spring Cloud组件自动装配>> PaleGreen
backgroundColor<<Spring测试组件>> PaleGreen
backgroundColor<<COLA架构>> Plum
backgroundColor<<COLA扩展点>> Plum
backgroundColor<<COLA状态机>> Plum
backgroundColor<<解决方案>> PaleGreen
backgroundColor<<插件集合>> Khaki
backgroundColor<<测试集合>> Khaki
backgroundColor<<部署测试集>> Khaki
backgroundColor<<集成测试集>> Khaki
backgroundColor<<性能测试集>> Khaki
backgroundColor<<冒烟测试集>> Khaki
}
[eden-component] --> [eden-architect]
[eden-dependencies] --> [eden-component]
[eden-parent] --> [eden-dependencies]
[eden-commons] --> [eden-parent]
[eden-extensions] --> [eden-commons]
[eden-spring-framework] --> [eden-commons]
[eden-spring-framework] --> [eden-extensions]
[eden-spring-boot] --> [eden-spring-framework]
[eden-spring-data] --> [eden-spring-framework]
[eden-spring-security] --> [eden-spring-framework]
[eden-spring-integration] --> [eden-spring-framework]
[eden-spring-cloud] -l-> [eden-spring-boot]
[eden-spring-cloud] -r-> [eden-spring-security]
[eden-spring-test] <-- [eden-spring-framework]
[eden-spring-test] <-- [eden-spring-data]
[eden-spring-test] <-- [eden-spring-integration]
[eden-spring-boot-starters] --> [eden-spring-boot]
[eden-spring-boot-starters] --> [eden-spring-data]
[eden-spring-boot-starters] --> [eden-spring-security]
[eden-spring-boot-starters] --> [eden-spring-integration]
[eden-spring-boot-test] <-- [eden-spring-boot]
[eden-spring-boot-test] <-- [eden-spring-cloud]
[eden-spring-cloud-starters] --> [eden-spring-cloud]
[eden-solutions] --> [eden-extensions]
[eden-solutions] --> [eden-spring-framework]
[eden-solutions] ..> [eden-spring-integration]
[eden-cola] --> [eden-commons]
[eden-cola] -u-> [eden-spring-framework]
[eden-cola-extensions] -u-> [eden-cola]
[eden-cola-statemachine] -r-> [eden-cola]
[eden-architect] <.u. [eden-plugins]
[eden-architect] <.u. [eden-tests]
[eden-tests] <-u- [eden-deployment-tests]
[eden-tests] <-u- [eden-integration-tests]
[eden-tests] <-u- [eden-performance-tests]
[eden-tests] <-u- [eden-smoke-tests]
@enduml
# Ignore everything in this directory
*
# Except this file !.gitkeep
# Ignore everything in this directory
*
# Except this file !.gitkeep
......@@ -12,6 +12,7 @@
<description>流行工具集整合</description>
<dependencies>
<!-- 开发组件 -->
<dependency>
<groupId>org.mapstruct</groupId>
......@@ -38,13 +39,11 @@
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
<!-- 工具集-->
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>cglib</groupId>
......@@ -66,7 +65,10 @@
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<!-- Apache Commons -->
<dependency>
<groupId>org.apache.commons</groupId>
......@@ -113,6 +115,17 @@
<artifactId>commons-pool</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<optional>true</optional>
</dependency>
<!-- 公式处理 -->
<dependency>
<groupId>org.mvel</groupId>
......@@ -231,5 +244,14 @@
<artifactId>thumbnailator</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
</dependencies>
</project>
package cn.easycode.akina.commons.bean;
import cn.easycode.akina.commons.lang.StringUtils;
import java.util.Collection;
import java.util.Map;
@Deprecated
public class Bean2Json {
/**
* @param map
* @return
*/
public static String toJson(Map<?, ?> map) {
StringBuilder json = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : map.entrySet()) {
if (first) {
first = false;
} else {
json.append(",");
}
String k = e.getKey().toString();
Object v = e.getValue();
Class<?> vClazz = v == null ? String.class : v.getClass();
if (Object[].class.isAssignableFrom(vClazz)) {
json.append(wrapJson(k)).append(':').append(toJson((Object[]) v));
} else if (Collection.class.isAssignableFrom(vClazz)) {
Collection<?> innerArray = (Collection<?>) v;
json.append(wrapJson(k)).append(':').append(toJson(innerArray));
} else if (Map.class.isAssignableFrom(vClazz)) {
@SuppressWarnings("unchecked")
Map<Object, ?> innerMap = (Map<Object, ?>) v;
json.append(wrapJson(k)).append(':').append(toJson(innerMap));
} else {
json.append(wrapJson(k)).append(':').append(wrapJson(v));
}
}
json.append("}");
return json.toString();
}
/**
* @param array
* @return
*/
public static String toJson(Collection<?> array) {
return toJson(array.toArray(new Object[0]));
}
/**
* @param array
* @return
*/
public static String toJson(Object[] array) {
StringBuilder json = new StringBuilder("[");
boolean first = true;
for (Object v : array) {
if (first) {
first = false;
} else {
json.append(",");
}
Class<?> vClazz = v == null ? null : v.getClass();
if (vClazz != null && Object[].class.isAssignableFrom(vClazz)) {
json.append(toJson((Object[]) v));
} else if (vClazz != null && Collection.class.isAssignableFrom(vClazz)) {
@SuppressWarnings("unchecked")
Collection<Object> innerArray = (Collection<Object>) v;
json.append(toJson(innerArray));
} else if (vClazz != null && Map.class.isAssignableFrom(vClazz)) {
@SuppressWarnings("unchecked")
Map<Object, Object> innerMap = (Map<Object, Object>) v;
json.append(toJson(innerMap));
} else {
json.append(wrapJson(v));
}
}
json.append("]");
return json.toString();
}
// ------
private static final char DOT = '.';
/**
* @param value
* @return
*/
public static String wrapJson(Object value) {
if (value == null || value.toString().length() < 1) {
return "\"\"";
}
if (value instanceof String) {
return '"' + escape(value) + '"';
}
String v = value.toString();
if (isNumber(v) || "true".equals(v) || "false".equals(v)) {
return v;
}
return '"' + escape(v) + '"';
}
/**
* @param json
* @return
*/
public static String escape(Object json) {
if (json == null) {
return StringUtils.EMPTY;
}
String jn = json.toString();
if (jn.contains("\"")) {
jn = jn.replaceAll("\"", "&quot;");
}
jn = jn.replaceAll("[\\n\\r\\t]", "");
if (jn.contains("\\")) {
jn = jn.replaceAll("\\\\", "\\\\\\\\");
}
jn = jn.replace("
", ""); // 一个奇怪的乱码
return jn;
}
/**
* @param json
* @return
*/
public static String unescape(Object json) {
if (json == null) {
return StringUtils.EMPTY;
}
String str = json.toString();
str = str.replaceAll("&quot;", "\"");
return str;
}
/**
* @param v
* @return
*
* @see NumberUtils#isDigits(String)
* @see NumberUtils#isNumber(String)
*/
public static boolean isNumber(String v) {
if (StringUtils.isEmpty(v)) {
return false;
}
if (v.charAt(0) == DOT || v.charAt(v.length() - 1) == DOT) {
return false;
}
int dot = 0;
for (int i = 0; i < v.length(); i++) {
char ch = v.charAt(i);
if (!Character.isDigit(ch)) {
if (ch != DOT) {
return false;
}
dot++;
if (dot > 1) {
return false;
}
}
}
return true;
}
}
package cn.easycode.akina.commons.bean;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* 反射工具
*
*/
public final class ReflectUtils {
private static final Class<?>[] OBJECT = new Class[] { Object.class };
private static final Class<?>[] NO_PARAM = new Class[] { };
private static final Method OBJECT_EQUALS;
private static final Method OBJECT_HASHCODE;
static {
try {
OBJECT_EQUALS = Object.class.getMethod("equals", OBJECT);
OBJECT_HASHCODE = Object.class.getMethod("hashCode", NO_PARAM);
} catch (Exception e) {
throw new RuntimeException("无法找到 Object#equals 或 Object#hashCode 方法", e);
}
}
/**
* 复写 {@link Object#equals(Object)}
*
* @param clazz
* @return
*/
public static boolean overridesEquals(Class<?> clazz) {
Method equals;
try {
equals = clazz.getMethod("equals", OBJECT);
} catch (NoSuchMethodException nsme) {
return false; // its an interface so we can't really tell anything...
}
return !OBJECT_EQUALS.equals(equals);
}
/**
* 复写 {@link Object#hashCode()}
*
* @param clazz
* @return
*/
public static boolean overridesHashCode(Class<?> clazz) {
Method hashCode;
try {
hashCode = clazz.getMethod("hashCode", NO_PARAM);
} catch (NoSuchMethodException nsme) {
return false; // its an interface so we can't really tell anything...
}
return !OBJECT_HASHCODE.equals(hashCode);
}
/**
* 使用当前线程加载 Class
*
* @param clazzName
* @return
* @throws ClassNotFoundException
*/
public static Class<?> classForName(String clazzName)
throws ClassNotFoundException {
try {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null) {
return contextClassLoader.loadClass(clazzName);
}
} catch (Throwable ignore) {
}
return Class.forName(clazzName);
}
/**
* 使用调用者线程加载 Class
*
* @param clazzName
* @param caller
* @return
* @throws ClassNotFoundException
*/
public static Class<?> classForName(String clazzName, Class<?> caller)
throws ClassNotFoundException {
try {
return Class.forName(clazzName, true, caller.getClassLoader());
} catch (Throwable ignore) {
}
return classForName(clazzName);
}
/**
* 类是否 <code>public</code>
*
* @param clazz
* @param member
* @return
*/
public static boolean isPublicClass(Class<?> clazz, Member member) {
return Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(clazz.getModifiers());
}
/**
* 类是否 <code>abstract</code>
*
* @param clazz
* @return
*/
public static boolean isAbstractClass(Class<?> clazz) {
int modifier = clazz.getModifiers();
return Modifier.isAbstract(modifier) || Modifier.isInterface(modifier);
}
/**
* 类是否 <code>final</code>
*
* @param clazz
* @return
*/
public static boolean isFinalClass(Class<?> clazz) {
return Modifier.isFinal(clazz.getModifiers());
}
/**
* 字段是否 "public static final"
*
* @param field
* @return
*/
public static boolean isPublicStaticFinal(Field field) {
int modifiers = field.getModifiers();
return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
}
/**
* 获取修饰符的字符串表示
*
* @param mod
* @return
*/
public static String getModifierString(int mod) {
StringBuilder sb = new StringBuilder(32);
if (Modifier.isPublic(mod)) {
sb.append("public ");
}
if (Modifier.isProtected(mod)) {
sb.append("protected ");
}
if (Modifier.isPrivate(mod)) {
sb.append("private ");
}
if (Modifier.isAbstract(mod)) {
sb.append("abstract ");
}
if (Modifier.isStatic(mod)) {
sb.append("static ");
}
if (Modifier.isFinal(mod)) {
sb.append("final ");
}
if (Modifier.isSynchronized(mod)) {
sb.append("synchronized ");
}
if (Modifier.isTransient(mod)) {
sb.append("transient ");
}
if (Modifier.isVolatile(mod)) {
sb.append("volatile ");
}
if (Modifier.isStrict(mod)) {
sb.append("strictfp ");
}
if (Modifier.isNative(mod)) {
sb.append("native ");
}
if (Modifier.isInterface(mod)) {
sb.append("interface ");
}
return sb.toString().trim();
}
/**
* 获取父级类
*
* @param clazz
* @return
*/
public static Class<?> getSuperclassGenricType(Class<?> clazz) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] genTypes = ((ParameterizedType) genType).getActualTypeArguments();
if (!(genTypes[0] instanceof Class<?>)) {
return Object.class;
}
return (Class<?>) genTypes[0];
}
/**
* 获取所有子类
*
* @param scanPackage
* @param superClass
* @return
* @throws IOException
* @throws ClassNotFoundException
*/
public static Set<Class<?>> getAllSubclasses(String scanPackage, Class<?> superClass)
throws IOException, ClassNotFoundException {
Set<Class<?>> classes = new LinkedHashSet<>();
boolean recursive = true;
String packageName = scanPackage;
String packageDirName = packageName.replace('.', '/');
Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
while (dirs.hasMoreElements()) {
URL url = dirs.nextElement();
String protocol = url.getProtocol();
if ("file".equals(protocol)) {
String filePath = URLDecoder.decode(url.getFile(), "utf-8");
scanClassesInPackage(packageName, filePath, recursive, superClass, classes);
} else if ("jar".equals(protocol)) {
JarFile jar;
jar = ((JarURLConnection) url.openConnection()).getJarFile();
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.charAt(0) == '/') {
name = name.substring(1);
}
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
if (idx != -1) {
packageName = name.substring(0, idx).replace('/', '.');
}
if ((idx != -1) || recursive) {
if (name.endsWith(".class") && !entry.isDirectory()) {
String className = name.substring(packageName.length() + 1, name.length() - 6);
addScanClass(packageName + '.' + className, superClass, classes);
}
}
}
}
}
}
return classes;
}
/**
* @param packageName
* @param packagePath
* @param recursive
* @param superClass
* @param classes
* @throws ClassNotFoundException
*/
private static void scanClassesInPackage(String packageName, String packagePath, boolean recursive, Class<?> superClass,
Set<Class<?>> classes) throws ClassNotFoundException {
File dir = new File(packagePath);
if (!dir.exists() || !dir.isDirectory()) {
return;
}
File[] dirfiles = dir.listFiles(file -> (recursive && file.isDirectory()) || (file.getName().endsWith(".class")));
if (dirfiles != null) {
for (File file : dirfiles) {
if (file.isDirectory()) {
scanClassesInPackage(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, superClass, classes);
} else {
String className = file.getName().substring(0, file.getName().length() - 6);
addScanClass(packageName + '.' + className, superClass, classes);
}
}
}
}
/**
* @param className
* @param superClass
* @param into
* @throws ClassNotFoundException
*/
private static void addScanClass(String className, Class<?> superClass, Set<Class<?>> into) throws ClassNotFoundException {
Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
if (superClass == null || (superClass.isAssignableFrom(clazz) && !superClass.equals(clazz))) {
into.add(clazz);
}
}
private ReflectUtils() {}
}
package cn.easycode.akina.commons.collections;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class ExpiresMap <K, V> implements Map<K, V> {
public static final int HOUR_IN_SECOND = 60 * 60;
private final Map<K, Object[]> nestable = new HashMap<>();
/**
* @param key
* @param expires 秒
* @return
*/
@SuppressWarnings("unchecked")
public V get(Object key, int expires) {
Object[] v = nestable.get(key);
if (v == null) {
return null;
}
long time = System.currentTimeMillis() - (Long) v[1];
if (time / 1000 > expires) {
remove(key);
return null;
}
return (V) v[0];
}
@Deprecated
@SuppressWarnings("unchecked")
@Override
public V get(Object key) {
Object[] v = nestable.get(key);
return v == null ? null : (V) v[0];
}
@Override
public V put(K key, V value) {
nestable.put(key, new Object[] { value, System.currentTimeMillis() });
return value;
}
@SuppressWarnings("unchecked")
@Override
public V remove(Object key) {
Object[] v = nestable.remove(key);
return v == null ? null : (V) v[0];
}
@Override
public int size() {
return nestable.size();
}
@Override
public boolean isEmpty() {
return nestable.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return nestable.containsKey(key);
}
@Override
public void clear() {
nestable.clear();
}
@Override
public void putAll(Map<? extends K, ? extends V> m) {
throw new UnsupportedOperationException();
}
@Override
public Set<K> keySet() {
throw new UnsupportedOperationException();
}
@Override
public Collection<V> values() {
throw new UnsupportedOperationException();
}
@Override
public Set<Entry<K, V>> entrySet() {
throw new UnsupportedOperationException();
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
}
package cn.easycode.akina.commons.crypto;
import cn.easycode.akina.commons.encoder.Base64Encoder;
import cn.easycode.akina.commons.encoder.UrlBase64Encoder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Random;
/**
* 编码工具
*
* @author Zhao Fangfang
* @version $Id: Bean2Json.java 48 2015-08-18 02:57:54Z zhaofang123@gmail.com $
*/
public class CodecUtils {
/** 0-9a-zA-Z */
public static final String CODES64 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final Base64Encoder BASE64_ENCODER = new Base64Encoder();
private static final UrlBase64Encoder URL_BASE64_ENCODER = new UrlBase64Encoder();
/**
* BASE64 编码
*
* @param data
* @return
*/
public static byte[] base64Encode(byte[] data) {
int length = (data.length + 2) / 3 * 4;
ByteArrayOutputStream bOut = new ByteArrayOutputStream(length);
try {
BASE64_ENCODER.encode(data, 0, data.length, bOut);
} catch (IOException e) {
throw new RuntimeException("Exception encoding base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* BASE64 解码
*
* @param data
* @return
*/
public static byte[] base64Decode(byte[] data) {
int len = data.length / 4 * 3;
ByteArrayOutputStream bOut = new ByteArrayOutputStream(len);
try {
BASE64_ENCODER.decode(data, 0, data.length, bOut);
} catch (IOException e) {
throw new RuntimeException("Exception decoding base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* BASE64 URL 编码
*
* @param data
* @return
*/
public static byte[] base64UrlEncode(byte[] data) {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try {
URL_BASE64_ENCODER.encode(data, 0, data.length, bOut);
} catch (IOException e) {
throw new RuntimeException("Exception encoding URL safe base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* BASE64 UR L解码
*
* @param data
* @return
*/
public static byte[] base64UrlDecode(byte[] data) {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
try {
URL_BASE64_ENCODER.decode(data, 0, data.length, bOut);
} catch (IOException e) {
throw new RuntimeException("Exception decoding URL safe base64 string: " + e);
}
return bOut.toByteArray();
}
/**
* URL 编码
*
* @param text
* @return
*/
public static String urlEncode(String text) {
try {
return URLEncoder.encode(text, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Exception encoding URL string: " + e);
}
}
/**
* URL 解码
*
* @param text
* @return
*/
public static String urlDecode(String text) {
try {
return URLDecoder.decode(text, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Exception decoding URL string: " + e);
}
}
/**
* 10进制转换到任意进制
*
* @param dec
* @param radix 2~62
* @return
*/
public static String dec2any(long dec, int radix) {
if (radix < 2 || radix > 62) {
radix = 2;
}
if (radix == 10) {
return String.valueOf(dec);
}
char[] buf = new char[65];
int pos = 64;
boolean isNegative = (dec < 0);
if (!isNegative) {
dec = -dec;
}
while (dec <= -radix) {
buf[pos--] = CODES64.charAt((int) (-(dec % radix)));
dec = dec / radix;
}
buf[pos] = CODES64.charAt((int) (-dec));
return new String(buf, pos, (65 - pos));
}
/**
* 任意进制转换到10进制
*
* @param number
* @param radix
* @return
*/
public static long any2dec(String number, int radix) {
long dec = 0;
long digitValue;
int len = number.length() - 1;
for (int t = 0; t <= len; t++) {
digitValue = CODES64.indexOf(number.charAt(t));
dec = dec * radix + digitValue;
}
return dec;
}
/**
* 产生指定长度的随机码(码表: 0-9a-zA-Z)
*
* @param length
* @return
*/
public static String randomCode(int length) {
StringBuilder code = new StringBuilder();
Random random = new SecureRandom();
int codeLength = CODES64.length();
for (int i = 0; i < length; i++) {
code.append(CODES64.charAt(random.nextInt(codeLength)));
}
return code.toString();
}
/**
* BASE64 URL 编码(UTF8)
*
* @param data
* @return
*/
public static String base64UrlEncode(String data) {
return new String(base64UrlEncode(data.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
}
/**
* BASE64 URL 解码(UTF8)
*
* @param data
* @return
*/
public static String base64UrlDecode(String data) {
return new String(base64UrlDecode(data.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
}
/**
* BASE64 编码(UTF8)
*
* @param data
* @return
*/
public static String base64Encode(String data) {
return new String(base64Encode(data.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
}
/**
* BASE64 解码(UTF8)
*
* @param data
* @return
*/
public static String base64Decode(String data) {
return new String(base64Decode(data.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8);
}
/**
* 字符转 UNICODE
*
* @param data
*/
public static String encodeUnicode(String data) {
char[] utfBytes = data.toCharArray();
final StringBuilder buffer = new StringBuilder();
for (char utfByte : utfBytes) {
String hexb = Integer.toHexString(utfByte);
if (hexb.length() <= 2) {
hexb = "00" + hexb;
}
buffer.append("\\u").append(hexb);
}
return buffer.toString();
}
/**
* UNICODE 转字符
*
* @param data
*/
public static String decodeUnicode(String data) {
int start = 0;
int end;
final StringBuilder buffer = new StringBuilder();
while (start > -1) {
end = data.indexOf("\\u", start + 2);
String charStr;
if (end == -1) {
charStr = data.substring(start + 2);
} else {
charStr = data.substring(start + 2, end);
}
char letter = (char) Integer.parseInt(charStr, 16);
buffer.append(letter);
start = end;
}
return buffer.toString();
}
private CodecUtils() {}
}
package cn.easycode.akina.commons.crypto;
import cn.easycode.akina.commons.lang.StringUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.zip.CRC32;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* 加密工具类
*
* @author Zhao Fangfang
* @version $Id: Bean2Json.java 48 2015-08-18 02:57:54Z zhaofang123@gmail.com $
* @see CodecUtils
*/
public final class EncryptUtils {
/**
* MD5加密
*
* @param input
* @return
*/
private static byte[] toMD5(byte[] input) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
digest.update(input);
return digest.digest();
}
/**
* MD5加密
*
* @param input
* @return
*/
public static String toMD5Hex(byte[] input) {
return toHexString(toMD5(input));
}
/**
* MD5加密
*
* @param input
* @return
*/
public static String toMD5Hex(String input) {
return toMD5Hex(input.getBytes(StandardCharsets.UTF_8));
}
/**
* SHA1加密
*
* @param input
* @return
*/
private static byte[] toSHA(byte[] input, String algorithm) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
digest.update(input);
return digest.digest();
}
/**
* SHA1加密
*
* @param input
* @return
*/
public static String toSHA1Hex(byte[] input) {
return toHexString(toSHA(input, "SHA1"));
}
/**
* SHA1加密
*
* @param input
* @return
*/
public static String toSHA1Hex(String input) {
return toSHA1Hex(input.getBytes(StandardCharsets.UTF_8));
}
/**
* SHA-256加密
*
* @param input
* @return
*/
public static String toSHA256Hex(byte[] input) {
return toHexString(toSHA(input, "SHA-256"));
}
/**
* SHA-256加密
*
* @param input
* @return
*/
public static String toSHA256Hex(String input) {
return toSHA256Hex(input.getBytes(StandardCharsets.UTF_8));
}
/**
* CRC32编码(6-8位)
*
* @param input
* @return
*/
public static String toCRC32Hex(byte[] input) {
CRC32 crc32 = new CRC32();
crc32.update(input);
return Long.toHexString( crc32.getValue() );
}
/**
* 返回8位CRC32编码,不够位数在尾部补0
*
* @param input
* @return
*/
@Deprecated
public static String toCRC32HexPad(byte[] input) {
return toCRC32HexPadding(input);
}
/**
* 返回8位CRC32编码,不够位数在尾部补0
*
* @param input
* @return
*/
public static String toCRC32HexPadding(byte[] input) {
String crc32 = toCRC32Hex(input);
if (crc32.length() == 8) return crc32;
return StringUtils.rightPad(crc32, 8, '0');
}
/**
* @param data
* @return
*/
public static String toHexString(byte[] data) {
StringBuilder sb = new StringBuilder();
for (byte b : data) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
/**
* AES加密
*
* @param input
* @param passwd
* @return
*/
public static String aesEncrypt(String input, byte[] passwd) {
try {
SecretKeySpec key = buildAesSecretKey(passwd);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] result = cipher.doFinal(input.getBytes(StandardCharsets.UTF_8));
return new String(CodecUtils.base64Encode(result));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* AES解密
*
* @param input
* @param passwd
* @return
*/
public static String aesDecrypt(String input, byte[] passwd) {
try {
SecretKeySpec key = buildAesSecretKey(passwd);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] result = cipher.doFinal(CodecUtils.base64Decode(input.getBytes(StandardCharsets.UTF_8)));
return new String(result);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* @param passwd
* @return
*/
private static SecretKeySpec buildAesSecretKey(byte[] passwd) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(passwd));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
return new SecretKeySpec(enCodeFormat, "AES");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private EncryptUtils() {}
}
package cn.easycode.akina.commons.date;
import cn.easycode.akina.commons.lang.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* 日期时间工具
*
*
* @see DateUtils
*/
public class CalendarUtils extends DateFormatUtils {
public static final TimeZone DEFAULT_TIME_ZONE = TimeZone.getDefault();
/**
* 2099.12.31
*/
public static final Date DATE_20991231 = new GregorianCalendar(2099, Calendar.DECEMBER, 31).getTime();
/**
* 获取<tt>Calendar</tt>实例
*
* @return
*/
public static Calendar getInstance() {
return Calendar.getInstance(DEFAULT_TIME_ZONE, DEFAULT_LOCALE);
}
/**
* 获取<tt>Calendar</tt>实例
*
* @param date
* @return
*/
public static Calendar getInstance(Date date) {
Calendar cal = getInstance();
cal.setTime(date);
return cal;
}
/**
* 返回当前日期
*
* @return
*/
public static Date now() {
return getInstance().getTime();
}
/**
* 在当前日期上添加日
*
* @param amount
* @return
*/
public static Date addDay(int amount) {
return add(amount, Calendar.DAY_OF_MONTH);
}
/**
* 在当前日期上添加月
*
* @param amount
* @return
*/
public static Date addMonth(int amount) {
return add(amount, Calendar.MONTH);
}
/**
* 在当前日期上添加指定字段和值
*
* @param amount
* @param field {@link Calendar}
* @return
*/
public static Date add(int amount, int field) {
Calendar cal = getInstance();
cal.add(field, amount);
return cal.getTime();
}
/**
* 在指定日期上添加日
*
* @param date
* @param amount
* @return
*/
public static Date addDay(Date date, int amount) {
return add(date, amount, Calendar.DAY_OF_MONTH);
}
/**
* 在指定日期上添加月
*
* @param date
* @param amount
* @return
*/
public static Date addMonth(Date date, int amount) {
return add(date, amount, Calendar.MONTH);
}
/**
* 在指定日期上添加指定字段和值
*
* @param date
* @param amount
* @param field
* @return
*/
public static Date add(Date date, int amount, int field) {
Calendar cal = getInstance(date);
cal.add(field, amount);
return cal.getTime();
}
/**
* 时间归零 00:00:00
*
* @param calendar
*/
public static void clearTime(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}
/**
* 时间最大值 23:59:59
*
* @param calendar
*/
public static void fullTime(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
}
/**
* 时间归零 00:00:00
*
* @param date
*/
public static Date clearTime(Date date) {
Calendar cal = getInstance(date);
clearTime(cal);
return cal.getTime();
}
/**
* 时间最大值 23:59:59
*
* @param date
*/
public static Date fullTime(Date date) {
Calendar cal = getInstance(date);
fullTime(cal);
return cal.getTime();
}
/**
* 是否同月(注意:不检查年)
*
* @param date
* @param another
* @return
* @see #isSameMonth(Date, Date, boolean)
*/
public static boolean isSameMonth(Date date, Date another) {
return isSameMonth(date, another, false);
}
/**
* 是否同月
*
* @param date
* @param another
* @param absolute 是否比较年,如为 false 则只比较同月
* @return
*/
public static boolean isSameMonth(Date date, Date another, boolean absolute) {
Calendar cal1 = getInstance(date);
Calendar cal2 = getInstance(another);
if (!absolute) {
return cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
}
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
&& cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH);
}
/**
* 是否同日(注意:不检查年、月)
*
* @param date
* @param another
* @return
* @see #isSameDay(Date, Date, boolean)
*/
public static boolean isSameDay(Date date, Date another) {
return isSameDay(date, another, false);
}
/**
* 是否同日
*
* @param date
* @param another
* @param absolute 是否比较年月,如为 false 则只比较同日
* @return
*/
public static boolean isSameDay(Date date, Date another, boolean absolute) {
Calendar cal1 = getInstance(date);
Calendar cal2 = getInstance(another);
if (!absolute) {
return cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
}
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
&& cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)
&& cal1.get(Calendar.DAY_OF_MONTH) == cal2.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取当前日期到指定日期的相差天数,如果结束日期小于当前日期将返回负数
*
* @param end
* @return
*/
public static int getDayLeft(Date end) {
return getDayLeft(now(), end);
}
/**
* 获取开始日期到结束日期的相差天数,如果结束日期小于开始日期将返回负数
*
* @param begin
* @param end
* @return
*/
public static int getDayLeft(Date begin, Date end) {
begin = clearTime(begin);
end = clearTime(end);
int ct = begin.compareTo(end);
if (ct == 0) {
return 0;
}
if (ct < 0) {
Calendar cal = getInstance(begin);
int days = -1;
while (cal.getTime().compareTo(end) <= 0) {
days++;
cal.add(Calendar.DAY_OF_YEAR, 1);
}
return days;
} else {
Calendar cal = getInstance(end);
int days = -1;
while (cal.getTime().compareTo(begin) <= 0) {
days++;
cal.add(Calendar.DAY_OF_YEAR, 1);
}
return -days;
}
}
/**
* 尝试解析日期,支持以下日期格式
* <ul>
* <li>yyyyMMdd</li>
* <li>yyyyMMddHHmmss</li>
* <li>yyyy-MM-dd</li>
* <li>yyyy-MM-dd HH:mm:ss</li>
* <li>yyyy年MM月dd日</li>
* <li>yyyy年MM月dd日 HH时mm分ss秒</li>
* </ul>
*
* @param source 无法解析则返回 <code>null</code>
* @return
*/
public static Date parse(String source) {
if (StringUtils.isBlank(source)) {
return null;
}
int len = source.trim().length();
if (len == 8) {
return parse(source, getPlainDateFormat());
} else if (len == 14) {
return parse(source, getPlainDateTimeFormat());
} else if (len == 10) {
return parse(source, getUTCDateFormat());
} else if (len == 19) {
return parse(source, getUTCDateTimeFormat());
} else if (len == 11) {
return parse(source, getCNDateFormat());
} else if (len == 21) {
return parse(source, getCNDateTimeFormat());
}
return null;
}
/**
* 解析日期,可指定格式
*
* @param source
* @param format
* @return
*/
public static Date parse(String source, DateFormat format) {
try {
return format.parse(source);
} catch (ParseException ex) {
return null;
}
}
/**
* 解析日期,可指定格式
*
* @param source
* @param format
* @return
*/
public static Date parse(String source, String format) {
return parse(source, getDateFormat(format));
}
}
package cn.easycode.akina.commons.date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* @author Zhao Fangfang
* @version $Id: DateFormatUtils.java 101 2012-09-11 15:24:46Z zhaofang123@gmail.com $
* @since 2.6, 2012-9-11
*/
public class DateFormatUtils {
public static final Locale DEFAULT_LOCALE = Locale.CHINESE;
/**
* 获取日志格式<tt>yyyy年MM月dd日</tt>
*
* @return
*/
public static DateFormat getCNDateFormat() {
return CN_DATE_FORMAT_TL.get();
}
/**
* 获取日志格式<tt>HH时mm分ss秒</tt>
*
* @return
*/
public static DateFormat getCNTimeFormat() {
return CN_TIME_FORMAT_TL.get();
}
/**
* 获取日志格式<tt>yyyy年MM月dd日 HH时mm分ss秒</tt>
*
* @return
*/
public static DateFormat getCNDateTimeFormat() {
return CN_DATETIME_FORMAT_TL.get();
}
/**
* 获取日志格式<tt>yyyy-MM-dd</tt>
*
* @return
*/
public static DateFormat getUTCDateFormat() {
return UTC_DATE_FORMAT_TL.get();
}
/**
* 获取日志格式<tt>yyyy-MM-dd HH:mm:ss</tt>
*
* @return
*/
public static DateFormat getUTCDateTimeFormat() {
return UTC_DATETIME_FORMAT_TL.get();
}
/**
* 获取日志格式<tt>yyyyMMdd</tt>
*
* @return
*/
public static DateFormat getPlainDateFormat() {
return PLAIN_DATE_FORMAT_TL.get();
}
/**
* 获取日志格式<tt>yyyyMMddHHmmss</tt>
*
* @return
*/
public static DateFormat getPlainDateTimeFormat() {
return PLAIN_DATETIME_FORMAT_TL.get();
}
/**
* 获取日志格式<tt>yyyy-MM-dd HH:mm:ss 'UTC'Z</tt>
*
* @return
*/
public static DateFormat getUTCWithZoneDateTimeFormat() {
return UTC_WITH_ZONE_DATETIME_FORMAT_TL.get();
}
/**
* 获取指定格式的日志格式化对象
*
* @return
*/
public static DateFormat getDateFormat(String formatted) {
return new SimpleDateFormat(formatted, DEFAULT_LOCALE);
}
/**
* @param formatted
* @param date
* @return
*/
public static String format(String formatted, Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(formatted, DEFAULT_LOCALE);
return sdf.format(date);
}
public static final String CN_DATE_FORMAT = "yyyy年MM月dd日";
private static final ThreadLocal<DateFormat> CN_DATE_FORMAT_TL = ThreadLocal.withInitial(() -> new SimpleDateFormat(CN_DATE_FORMAT));
public static final String CN_TIME_FORMAT = "HH时mm分ss秒";
private static final ThreadLocal<DateFormat> CN_TIME_FORMAT_TL = ThreadLocal.withInitial(() -> new SimpleDateFormat(CN_TIME_FORMAT));
public static final String CN_DATETIME_FORMAT = "yyyy年MM月dd日 HH时mm分ss秒";
private static final ThreadLocal<DateFormat> CN_DATETIME_FORMAT_TL = ThreadLocal.withInitial(() -> new SimpleDateFormat(CN_DATETIME_FORMAT));
public static final String UTC_DATE_FORMAT = "yyyy-MM-dd";
private static final ThreadLocal<DateFormat> UTC_DATE_FORMAT_TL = ThreadLocal.withInitial(() -> new SimpleDateFormat(UTC_DATE_FORMAT));
public static final String UTC_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
private static final ThreadLocal<DateFormat> UTC_DATETIME_FORMAT_TL = ThreadLocal.withInitial(() -> new SimpleDateFormat(UTC_DATETIME_FORMAT));
public static final String PLAIN_DATE_FORMAT = "yyyyMMdd";
private static final ThreadLocal<DateFormat> PLAIN_DATE_FORMAT_TL = ThreadLocal.withInitial(() -> new SimpleDateFormat(PLAIN_DATE_FORMAT));
public static final String PLAIN_DATETIME_FORMAT = "yyyyMMddHHmmss";
private static final ThreadLocal<DateFormat> PLAIN_DATETIME_FORMAT_TL = ThreadLocal.withInitial(() -> new SimpleDateFormat(PLAIN_DATETIME_FORMAT));
public static final String UTC_WITH_ZONE_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss 'UTC'Z";
private static final ThreadLocal<DateFormat> UTC_WITH_ZONE_DATETIME_FORMAT_TL = ThreadLocal.withInitial(() -> new SimpleDateFormat(UTC_WITH_ZONE_DATETIME_FORMAT));
}
package cn.easycode.akina.commons.encoder;
import java.io.IOException;
import java.io.OutputStream;
public class Base64Encoder {
protected final byte[] encodingTable = { (byte) 'A', (byte) 'B',
(byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',
(byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L',
(byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q',
(byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V',
(byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a',
(byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k',
(byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p',
(byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',
(byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',
(byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
(byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
(byte) '+', (byte) '/' };
protected byte padding = (byte) '=';
/**
* set up the decoding table.
*/
protected final byte[] decodingTable = new byte[128];
protected void initialiseDecodingTable() {
for (int i = 0; i < encodingTable.length; i++) {
decodingTable[encodingTable[i]] = (byte) i;
}
}
public Base64Encoder() {
initialiseDecodingTable();
}
/**
* encode the input data producing a base 64 output stream.
*
* @return the number of bytes produced.
*/
public int encode(byte[] data, int off, int length, OutputStream out)
throws IOException {
int modulus = length % 3;
int dataLength = (length - modulus);
int a1, a2, a3;
for (int i = off; i < off + dataLength; i += 3) {
a1 = data[i] & 0xff;
a2 = data[i + 1] & 0xff;
a3 = data[i + 2] & 0xff;
out.write(encodingTable[(a1 >>> 2) & 0x3f]);
out.write(encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]);
out.write(encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]);
out.write(encodingTable[a3 & 0x3f]);
}
/*
* process the tail end.
*/
int b1, b2, b3;
int d1, d2;
switch (modulus) {
case 0: /* nothing left to do */
break;
case 1:
d1 = data[off + dataLength] & 0xff;
b1 = (d1 >>> 2) & 0x3f;
b2 = (d1 << 4) & 0x3f;
out.write(encodingTable[b1]);
out.write(encodingTable[b2]);
out.write(padding);
out.write(padding);
break;
case 2:
d1 = data[off + dataLength] & 0xff;
d2 = data[off + dataLength + 1] & 0xff;
b1 = (d1 >>> 2) & 0x3f;
b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f;
b3 = (d2 << 2) & 0x3f;
out.write(encodingTable[b1]);
out.write(encodingTable[b2]);
out.write(encodingTable[b3]);
out.write(padding);
break;
}
return (dataLength / 3) * 4 + ((modulus == 0) ? 0 : 4);
}
private boolean ignore(char c) {
return (c == '\n' || c == '\r' || c == '\t' || c == ' ');
}
/**
* decode the base 64 encoded byte data writing it to the given output
* stream, whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public int decode(byte[] data, int off, int length, OutputStream out)
throws IOException {
byte b1, b2, b3, b4;
int outLen = 0;
int end = off + length;
while (end > off) {
if (!ignore((char) data[end - 1])) {
break;
}
end--;
}
int i = off;
int finish = end - 4;
i = nextI(data, i, finish);
while (i < finish) {
b1 = decodingTable[data[i++]];
i = nextI(data, i, finish);
b2 = decodingTable[data[i++]];
i = nextI(data, i, finish);
b3 = decodingTable[data[i++]];
i = nextI(data, i, finish);
b4 = decodingTable[data[i++]];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
outLen += 3;
i = nextI(data, i, finish);
}
outLen += decodeLastBlock(out, (char) data[end - 4],
(char) data[end - 3], (char) data[end - 2],
(char) data[end - 1]);
return outLen;
}
private int nextI(byte[] data, int i, int finish) {
while ((i < finish) && ignore((char) data[i])) {
i++;
}
return i;
}
/**
* decode the base 64 encoded String data writing it to the given output
* stream, whitespace characters will be ignored.
*
* @return the number of bytes produced.
*/
public int decode(String data, OutputStream out) throws IOException {
byte b1, b2, b3, b4;
int length = 0;
int end = data.length();
while (end > 0) {
if (!ignore(data.charAt(end - 1))) {
break;
}
end--;
}
int i = 0;
int finish = end - 4;
i = nextI(data, i, finish);
while (i < finish) {
b1 = decodingTable[data.charAt(i++)];
i = nextI(data, i, finish);
b2 = decodingTable[data.charAt(i++)];
i = nextI(data, i, finish);
b3 = decodingTable[data.charAt(i++)];
i = nextI(data, i, finish);
b4 = decodingTable[data.charAt(i++)];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
length += 3;
i = nextI(data, i, finish);
}
length += decodeLastBlock(out, data.charAt(end - 4), data
.charAt(end - 3), data.charAt(end - 2), data.charAt(end - 1));
return length;
}
private int decodeLastBlock(OutputStream out, char c1, char c2, char c3,
char c4) throws IOException {
byte b1, b2, b3, b4;
if (c3 == padding) {
b1 = decodingTable[c1];
b2 = decodingTable[c2];
out.write((b1 << 2) | (b2 >> 4));
return 1;
} else if (c4 == padding) {
b1 = decodingTable[c1];
b2 = decodingTable[c2];
b3 = decodingTable[c3];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
return 2;
} else {
b1 = decodingTable[c1];
b2 = decodingTable[c2];
b3 = decodingTable[c3];
b4 = decodingTable[c4];
out.write((b1 << 2) | (b2 >> 4));
out.write((b2 << 4) | (b3 >> 2));
out.write((b3 << 6) | b4);
return 3;
}
}
private int nextI(String data, int i, int finish) {
while ((i < finish) && ignore(data.charAt(i))) {
i++;
}
return i;
}
}
package cn.easycode.akina.commons.encoder;
public class UrlBase64Encoder extends Base64Encoder {
public UrlBase64Encoder() {
encodingTable[encodingTable.length - 2] = (byte) '-';
encodingTable[encodingTable.length - 1] = (byte) '_';
padding = (byte) '.';
// we must re-create the decoding table with the new encoded values.
initialiseDecodingTable();
}
}
package cn.easycode.akina.commons.identifier;
import cn.easycode.akina.commons.crypto.EncryptUtils;
import java.nio.charset.StandardCharsets;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.ComputerSystem;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OperatingSystem;
public class ComputerIdentifier {
/**
* @return
*/
public static String generateIdentifier() {
SystemInfo systemInfo = new SystemInfo();
OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
ComputerSystem computerSystem = hardwareAbstractionLayer.getComputerSystem();
String vendor = operatingSystem.getManufacturer();
String processorSerialNumber = computerSystem.getSerialNumber();
String processorIdentifier = centralProcessor.getProcessorIdentifier().getIdentifier();
int processors = centralProcessor.getLogicalProcessorCount();
String delimiter = "#";
return vendor +
delimiter +
processorSerialNumber +
delimiter +
processorIdentifier +
delimiter +
processors;
}
/**
* @return
*/
public static String generateIdentifierKey() {
String id = generateIdentifier();
return EncryptUtils.toCRC32HexPadding(id.getBytes(StandardCharsets.UTF_8));
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
String id = generateIdentifier();
System.out.println(id + " = " + generateIdentifierKey());
}
}
}
package cn.easycode.akina.commons.identifier;
import java.io.Serializable;
/**
* Identifier generator
*
* @author <a href="mailto:zhaofang123@gmail.com">FANGFANG ZHAO</a>
* @since 0.1, 06/13/08
* @version $Id: IdentifierGenerator.java 8 2015-06-08 09:09:03Z zhaofang123@gmail.com $
*/
public interface IdentifierGenerator {
/**
* Generate a new identifier
*
* @return
*/
Serializable generate();
/**
* Gets length of id
*
* @return
*/
int getLength();
}
package cn.easycode.akina.commons.identifier;
import cn.hutool.core.util.ByteUtil;
import java.io.Serializable;
import java.net.InetAddress;
/**
* UUID Hex Generator
*
* @author <a href="mailto:zhaofang123@gmail.com">FANGFANG ZHAO</a>
* @since 0.1, 06/13/08
* @version $Id: UUIDHexGenerator.java 8 2015-06-08 09:09:03Z zhaofang123@gmail.com $
*/
public class UUIDHexGenerator implements IdentifierGenerator {
private static final int IP;
static {
int ipadd;
try {
ipadd = ByteUtil.bytesToInt(InetAddress.getLocalHost().getAddress());
} catch (Exception ex) {
ipadd = 0;
}
IP = ipadd;
}
private static short counter = (short) 0;
final private static int JVM = (int) (System.currentTimeMillis() >>> 8);
final protected char sep;
/**
* Create a new UUIDHexGenerator
*/
public UUIDHexGenerator() {
this('-');
}
/**
* Create a new UUIDHexGenerator
*
* @param sep
*/
public UUIDHexGenerator(char sep) {
this.sep = sep;
}
/**
* Generate uuid hex
*
* @return
*/
@Override
public Serializable generate() {
return format(getIP()) + sep +
format(getJVM()) + sep +
format(getMoTime()) + sep +
format(getLoTime()) + sep +
format(getCount());
}
@Override
public int getLength() {
return 36;
}
/**
* Format a int value
*/
protected String format(int intval) {
String formatted = Integer.toHexString(intval);
StringBuilder buf = new StringBuilder("00000000");
buf.replace(8 - formatted.length(), 8, formatted);
return buf.toString();
}
/**
* Format a short value
*/
protected String format(short shortval) {
String formatted = Integer.toHexString(shortval);
StringBuilder buf = new StringBuilder("0000");
buf.replace(4 - formatted.length(), 4, formatted);
return buf.toString();
}
/**
* Unique across JVMs on this machine (unless they load this class in the
* same quater second - very unlikely)
*/
protected int getJVM() {
return JVM;
}
/**
* Unique in a millisecond for this JVM instance (unless there are &gt;
* Short.MAX_VALUE instances created in a millisecond)
*/
protected short getCount() {
synchronized (UUIDHexGenerator.class) {
if (counter < 0) {
counter = 0;
}
return counter++;
}
}
/**
* Unique in a local network
*/
protected int getIP() {
return IP;
}
/**
* Unique down to month
*/
protected short getMoTime() {
return (short) (System.currentTimeMillis() >>> 32);
}
/**
* Unique down to millisecond
*/
protected int getLoTime() {
return (int) System.currentTimeMillis();
}
}
......@@ -2,13 +2,8 @@
package cn.easycode.akina.commons.lang;
import lombok.NonNull;
import lombok.experimental.UtilityClass;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import cn.easycode.akina.commons.json.JacksonUtils;
import cn.easycode.akina.commons.lang.math.NumberUtils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
......@@ -16,13 +11,19 @@ import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Map;
import lombok.NonNull;
import lombok.experimental.UtilityClass;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
/**
* 对象工具集
*
* @author
* @since
* @since
* @see org.apache.commons.lang3.ObjectUtils
*/
@UtilityClass
......@@ -119,4 +120,148 @@ public class ObjectUtils extends org.apache.commons.lang3.ObjectUtils {
}
return cast(object, clazz);
}
/**
* @param o
* @return
*/
public static boolean toBool(Object o) {
return toBool(o, Boolean.FALSE);
}
/**
* @param o
* @param defaultVal
* @return
* @see BooleanUtils#toBoolean(String)
*/
public static boolean toBool(Object o, boolean defaultVal) {
if (o == null) {
return defaultVal;
} else if (o instanceof Boolean) {
return (Boolean) o;
}
return BooleanUtils.toBoolean(o.toString());
}
/**
* @param o
* @return
*/
public static int toInt(Object o) {
return toInt(o, 0);
}
/**
* @param o
* @param defaultVal
* @return
* @see NumberUtils#toInt(String)
*/
public static int toInt(Object o, int defaultVal) {
if (o == null) {
return defaultVal;
}
if (o instanceof Number) {
return ((Number) o).intValue();
}
return NumberUtils.toInt(o.toString());
}
/**
* @param o
* @return
*/
public static long toLong(Object o) {
return toLong(o, 0L);
}
/**
* @param o
* @param defaultVal
* @return
* @see NumberUtils#toLong(String)
*/
public static long toLong(Object o, long defaultVal) {
if (o == null) {
return defaultVal;
}
if (o instanceof Number) {
return ((Number) o).longValue();
}
return NumberUtils.toLong(o.toString());
}
/**
* @param o
* @return
*/
public static double toDouble(Object o) {
return toDouble(o, 0d);
}
/**
* @param o
* @param defaultVal
* @return
* @see NumberUtils#toDouble(String)
*/
public static double toDouble(Object o, double defaultVal) {
if (o == null) {
return defaultVal;
}
if (o instanceof Number) {
return ((Number) o).doubleValue();
}
return NumberUtils.toDouble(o.toString());
}
/**
* 比较两个对象
*
* @param object
* @param another
* @return
* @see Object#equals(Object)
*/
public static boolean equals(Object object, Object another) {
if (object == null && another == null) return true;
if (object == null || another == null) return false;
return object.equals(another);
}
/**
* 保留指定精度(四舍五入)
*
* @param value
* @param scale 小数位
* @return
*/
public static double round(double value, int scale) {
return BigDecimal.valueOf(value)
.setScale(scale, RoundingMode.HALF_UP).doubleValue();
}
/**
* 除法,两个数字中任意一个为0则返回0
*
* @param divisor
* @param dividend
* @return
*/
public static double divide(int divisor, int dividend) {
return divide(divisor + 0d, dividend + 0d);
}
/**
* 除法,两个数字中任意一个为0则返回0
*
* @param divisor
* @param dividend
* @return
*/
public static double divide(double divisor, double dividend) {
if (divisor == 0 || dividend == 0) return 0d;
return divisor / dividend;
}
}
package cn.easycode.akina.commons.lang;
import cn.easycode.akina.commons.runtime.RuntimeInformation;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.JavaVersion;
import oshi.driver.windows.perfmon.MemoryInformation;
/**
* JVM 系统工具
*
* @author Zhao Fangfang
* @version $Id: Bean2Json.java 48 2015-08-18 02:57:54Z zhaofang123@gmail.com $
*/
public final class SystemUtils {
/**
* 执行命令行
*
* @param command
*/
public static void command(String command) {
command(command, System.out);
}
/**
* 执行命令行
*
* @param command
* @param stream
*/
public static void command(String command, PrintStream stream) {
if (StringUtils.isBlank(command)) {
return;
}
BufferedReader reader = null;
try {
Runtime rtx = Runtime.getRuntime();
Process process = rtx.exec(command);
reader = new BufferedReader(new InputStreamReader( process.getInputStream() ));
if (stream != null) {
String str;
while ((str = reader.readLine()) != null) {
stream.println(str);
}
}
try {
System.out.println("Exit: " + process.waitFor());
} catch (Exception ex) {
System.err.println("Processes was interrupted");
throw ex;
}
} catch (Exception ex) {
if (!command.startsWith("cmd /c")) {
command("cmd /c " + command);
} else {
throw new RuntimeException("Error executing commond: " + command, ex);
}
} finally {
try {
if (reader != null) reader.close();
} catch (Exception ignore) { }
}
}
private static long lastGcTime = 0;
/**
* 执行 GC
*/
synchronized public static void gc() {
if (System.currentTimeMillis() - lastGcTime < 60 * 1000) {
return;
}
lastGcTime = System.currentTimeMillis();
try {
System.gc();
TimeUnit.SECONDS.sleep(30);
System.runFinalization();
TimeUnit.SECONDS.sleep(30);
System.gc();
TimeUnit.SECONDS.sleep(30);
System.runFinalization();
TimeUnit.SECONDS.sleep(30);
} catch (Exception ex) {
//...
} finally {
lastGcTime = System.currentTimeMillis();
}
}
/**
* 获取当前线程总数
*
* @return
*/
public static long getThreadCount() {
ThreadGroup group = Thread.currentThread().getThreadGroup();
ThreadGroup top = group;
while (group != null) {
top = group;
group = group.getParent();
}
if (top == null) return 0L;
int estimatedSize = top.activeCount() * 2;
Thread[] slackList = new Thread[estimatedSize];
return top.enumerate(slackList);
}
private static RuntimeInformation runtimeInformation;
/**
* 获取运行时信息
*
* @return
*/
synchronized public static RuntimeInformation getRuntimeInformation() {
if (runtimeInformation == null) {
if (!org.apache.commons.lang3.SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5)) {
throw new RuntimeException("Java version least 1.5");
}
runtimeInformation = new RuntimeInformation();
}
return runtimeInformation;
}
/**
* 内存统计(单位:MB)
*
* @return
*/
public static List<MemoryInformation> getMemoryStatistics() {
return getMemoryStatistics(false);
}
/**
* 获取内存统计
*
* @return
*/
public static List<MemoryInformation> getMemoryStatistics(boolean containsPool) {
List<MemoryInformation> stats = new ArrayList<>();
return Collections.unmodifiableList(stats);
}
/**
* DUMP 线程信息
*
* @param stream
*/
public static void dumpThreads(PrintStream stream) {
Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces();
for (Thread thread : traces.keySet()) {
stream.print(String.format("\nThread[%s@%d,%d,%s]: (state = %s)",
thread.getName(), thread.getId(), thread.getPriority(),
thread.getThreadGroup().getName(), thread.getState()));
for (StackTraceElement stackTraceElement : traces.get(thread)) {
stream.print("\n\t" + stackTraceElement);
}
}
}
private SystemUtils() {}
}
//package cn.easycode.akina.commons.net;
//
//import cn.easycode.akina.commons.crypto.CodecUtils;
//import java.io.UnsupportedEncodingException;
//import java.util.ArrayList;
//import java.util.HashSet;
//import java.util.Set;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//import org.apache.commons.lang3.RandomUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
///**
// * 短链处理
// *
// * @author Zhao Fangfang
// * @version $Id: ShortUrl.java 87 2015-09-28 14:51:01Z zhaofang123@gmail.com $
// */
//@Deprecated
//public class ShortUrl {
//
// private static final Logger LOG = LoggerFactory.getLogger(ShortUrl.class);
//
// final static Pattern URL_PATTERN = Pattern.compile("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=#,]*)?");
//
// /**
// * 将内容中的 URL 全部换为短链
// *
// * @param content
// * @return
// */
// public static String shortUrlWithContent(String content) {
// if (content == null) {
// return null;
// }
//
// Matcher matcher = URL_PATTERN.matcher(content);
// Set<String> urls = new HashSet<>();
// while (matcher.find()) {
// urls.add(matcher.group());
// }
// if (urls.isEmpty()) {
// return content;
// }
//
// for (String url : urls) {
// if (url.startsWith("http://t.cn") || url.startsWith("http://url.cn")
// || url.startsWith("http://tb.cn") || url.startsWith("http://dwz.cn")) {
// continue;
// }
//
// String sUrl = shortUrl(url);
// content = content.replace(url, sUrl);
// }
// return content;
// }
//
// private static final HttpClientEx HTTP_CLIENT_EX = new HttpClientEx(3 * 1000, "utf-8");
// // http://blog.sina.com.cn/s/blog_9e1ea13a01017y3n.html
// private static final String[] APPKEYS = new String[] { "5786724301", "82966982", "405597125", "3822648575", "2849184197", "2702428363", "211160679", "31641035" };
// private static String LAST_APPKEY = null;
// /**
// * t.cn
// *
// * @param url
// * @return
// */
// public static String shortUrl(String url) {
// String appkey = LAST_APPKEY;
// for (int i = 0; i < 5; i++) {
// if (i > 0 || appkey == null) {
// appkey = APPKEYS[RandomUtils.nextInt(APPKEYS.length)];
// }
//
// try {
// String api = String.format(
// "http://api.weibo.com/2/short_url/shorten.json?source=%s&url_long=%s",
// appkey,
// CodecUtils.urlEncode(url));
// String result = HTTP_CLIENT_EX.get(api);
// String[] split = result.split("http://t.cn");
// if (split.length != 2) {
// return url;
// }
// String sUrl = split[1].split("url_long")[0].split(",")[0];
// sUrl = "t.cn" + sUrl.replaceAll("\"", EMPTY).replaceAll(",", EMPTY);
// LAST_APPKEY = appkey;
// return sUrl;
// } catch (Exception ex) {
// LOG.error("短网址失败: " + url + " << " + appkey + " >> " + ex.getLocalizedMessage());
// }
// }
// return url;
// }
//
// /**
// * 使用百度 dwz.la 缩短网址
// *
// * @param url
// * @return
// */
// @Deprecated
// public static String dwzUrl(String url) {
// HttpPost post = new HttpPost("http://dwz.cn/create.php");
// List<NameValuePair> nvp = new ArrayList<>();
// nvp.add(new BasicNameValuePair("url", url));
// try {
// post.setEntity(new UrlEncodedFormEntity(nvp));
// } catch (UnsupportedEncodingException e) {
// return null;
// }
//
// String r = HttpClientEx.instance().execMethod(post);
// r = r.replace("\\", EMPTY);
// String[] rSplit = r.split("dwz.cn");
// String sUrl = rSplit[1].split("\"")[0];
// sUrl = "dwz.cn" + sUrl;
// return sUrl;
// }
//
// /**
// * dwz.la
// *
// * @param url
// * @return
// */
// public static String ft12Url(String url) {
// try {
// String url2 = String.format("http://api.ft12.com/api.php?url=%s", CodecUtils.urlEncode(url));
// return HttpClientEx.instance().get(url2);
//
// } catch (Exception ex) {
// LOG.error("短网址失败: " + url + " >> " + ex.getLocalizedMessage());
// }
// return url;
// }
//}
package cn.easycode.akina.commons.regex;
import lombok.NonNull;
import lombok.experimental.UtilityClass;
import cn.easycode.akina.commons.lang.StringUtils;
import cn.easycode.akina.commons.regex.pattern.RegexCache;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.NonNull;
import lombok.experimental.UtilityClass;
/**
* 正则表达式工具类
*
* @author
* @since
*/
@UtilityClass
public class RegexUtils {
public static final Pattern EMAIL_PATTERN = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
public static final Pattern URL_PATTERN = Pattern.compile("^(https?|ftp)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
public static final Pattern CNMOBILE_PATTERN = Pattern.compile("^(1[3-9][0-9])\\d{8}$");
public static final Pattern TEL_PATTERN = Pattern.compile("[0-9\\-]{7,18}");
/**
* @param email
* @return
*/
public static boolean isEMail(String email) {
return StringUtils.isNotBlank(email) && EMAIL_PATTERN.matcher(email).find()
&& !(email.endsWith("yahoo.cn") || email.endsWith("yahoo.com.cn") || email.endsWith(".")
|| email.startsWith(".") || StringUtils.countMatches(email, "@") > 1 || email.contains(".."));
}
/**
* @param url
* @return
*/
public static boolean isUrl(String url) {
return StringUtils.isNotBlank(url) && URL_PATTERN.matcher(url).find();
}
/**
* @param mobile
* @return
*/
public static boolean isCNMobile(String mobile) {
if (StringUtils.isBlank(mobile) || mobile.length() < 11) {
return false;
}
if (mobile.startsWith("+86")) {
mobile = mobile.substring(3);
} else if (mobile.startsWith("86")) {
mobile = mobile.substring(2);
}
return CNMOBILE_PATTERN.matcher(mobile).find();
}
/**
* @param tel
* @return
*/
public static boolean isTel(String tel) {
if (StringUtils.isBlank(tel) || tel.length() < 7) {
return false;
}
if (tel.startsWith("-") || tel.endsWith("-") || tel.contains("--")) {
return false;
}
return TEL_PATTERN.matcher(tel).find();
}
public static boolean isMatch(@NonNull String regex, @NonNull CharSequence input) {
return Pattern.matches(regex, input);
}
......
package cn.easycode.akina.commons.runtime;
/**
* 内存信息
*
*/
public interface MemoryInformation {
/**
* @return
*/
String getName();
/**
* @return
*/
long getTotal();
/**
* @return
*/
long getUsed();
/**
* @return
*/
long getFree();
}
package cn.easycode.akina.commons.runtime;
import java.lang.management.MemoryPoolMXBean;
public class MemoryInformationBean implements MemoryInformation {
/**
* byte &gt; MiB
*/
public static final long MEGABYTES = 1048576L;
private final MemoryPoolMXBean memoryPool;
/**
* @param memoryPoolMXBean
*/
public MemoryInformationBean(MemoryPoolMXBean memoryPoolMXBean) {
this.memoryPool = memoryPoolMXBean;
}
@Override
public String getName() {
return memoryPool.getName();
}
@Override
public long getTotal() {
return (memoryPool.getUsage().getMax());
}
@Override
public long getUsed() {
return (memoryPool.getUsage().getUsed());
}
@Override
public long getFree() {
return getTotal() - getUsed();
}
@Override
public String toString() {
return getName() + ": " + memoryPool.getUsage();
}
}
package cn.easycode.akina.commons.runtime;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
/**
* 运行时信息
*
*/
public class RuntimeInformation {
private final MemoryMXBean memory;
private final RuntimeMXBean runtime;
private final OperatingSystemMXBean osMXBean;
private final ThreadMXBean threadMXBean;
private long preTime = System.nanoTime();
private long preUsedTime = 0;
/**
*/
public RuntimeInformation() {
this.memory = ManagementFactory.getMemoryMXBean();
this.runtime = ManagementFactory.getRuntimeMXBean();
this.osMXBean = ManagementFactory.getOperatingSystemMXBean();
this.threadMXBean = ManagementFactory.getThreadMXBean();
}
/**
* @return
*/
public long getTotalHeapMemory() {
return (memory.getHeapMemoryUsage().getMax());
}
/**
* @return
*/
public long getTotalHeapMemoryUsed() {
return (memory.getHeapMemoryUsage().getUsed());
}
/**
* @return
*/
public long getTotalNonHeapMemory() {
return (memory.getNonHeapMemoryUsage().getMax());
}
/**
* @return
*/
public long getTotalNonHeapMemoryUsed() {
return (memory.getNonHeapMemoryUsage().getUsed());
}
/**
* @return
*/
public long getTotalPermGenMemory() {
return (getPermGen().getTotal());
}
/**
* @return
*/
public long getTotalPermGenMemoryUsed() {
return (getPermGen().getUsed());
}
/**
* @return
*/
public List<MemoryInformation> getMemoryPoolInformation() {
List<MemoryPoolMXBean> mxBeans = ManagementFactory.getMemoryPoolMXBeans();
List<MemoryInformation> result = new ArrayList<>(mxBeans.size());
for (MemoryPoolMXBean mxBean : mxBeans) {
result.add(new MemoryInformationBean(mxBean));
}
return Collections.unmodifiableList(result);
}
/**
* 获取 JVM 输入参数
*
* @return
*/
public String getJvmInputArguments() {
final StringBuilder sb = new StringBuilder();
for (final String argument : runtime.getInputArguments()) {
sb.append(argument).append(" ");
}
return sb.toString();
}
/**
* 获取永久代内存
*
* @return
*/
private MemoryInformation getPermGen() {
for (final MemoryInformation info : getMemoryPoolInformation()) {
final String name = info.getName().toLowerCase();
if (name.contains("perm gen")) {
return info;
}
}
return new MemoryInformation() {
@Override
public String getName() { return ""; }
@Override
public long getTotal() { return -1; }
@Override
public long getUsed() { return -1; }
@Override
public long getFree() { return -1; }
};
}
/**
* 获取系统负载
*
* @return
*/
public double getSystemLoad() {
return osMXBean.getSystemLoadAverage();
}
/**
* 获取 JVM 进程负载
*
* @return
*/
public double getProcessLoad() {
long totalTime = 0;
for (long id : threadMXBean.getAllThreadIds()) {
totalTime += threadMXBean.getThreadCpuTime(id);
}
long currentTime = System.nanoTime();
long usedTime = totalTime - preUsedTime;
long totalPassedTime = currentTime - preTime;
preTime = currentTime;
preUsedTime = totalTime;
return (((double) usedTime) / totalPassedTime / osMXBean.getAvailableProcessors()) * 100;
}
/**
* 获取容器端口
*
* @return
*/
public int getServletPort() {
MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
try {
Set<ObjectName> objectNames = beanServer.queryNames(
new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
String port = objectNames.iterator().next().getKeyProperty("port");
return Integer.parseInt(port);
} catch (Exception e) {
return -1;
}
}
}
package cn.easycode.akina.commons.web;
import cn.easycode.akina.commons.crypto.CodecUtils;
import cn.easycode.akina.commons.date.CalendarUtils;
import cn.easycode.akina.commons.lang.StringUtils;
import cn.easycode.akina.commons.xml.XMLHelper;
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.dom4j.Document;
/**
* SERVLET 工具集
*
* @author Zhao Fangfang
* @version $Id: Bean2Json.java 48 2015-08-18 02:57:54Z zhaofang123@gmail.com $
*/
public class ServletUtils {
/**
* @param request
* @param paramName
* @return
*/
public static String getParameter(ServletRequest request, String paramName) {
return getParameter(request, paramName, null);
}
/**
* @param request
* @param paramName
* @param defaultValue
* @return
*/
public static String getParameter(ServletRequest request, String paramName, String defaultValue) {
String value = request.getParameter(paramName);
return value == null ? defaultValue : value;
}
/**
* @param request
* @return
*/
public static HttpSession getSession(ServletRequest request) {
return getSession(request, true);
}
/**
* @param request
* @param autoCreate
* @return
*/
public static HttpSession getSession(ServletRequest request, boolean autoCreate) {
return ((HttpServletRequest) request).getSession(autoCreate);
}
/**
* @param request
* @param attrName
* @return
*/
public static Object getSessionAttribute(ServletRequest request, String attrName) {
return getSessionAttribute(request, attrName, null);
}
/**
* @param request
* @param attrName
* @param defaultValue
* @return
*/
public static Object getSessionAttribute(ServletRequest request, String attrName, Object defaultValue) {
Object value = getSession(request).getAttribute(attrName);
return value == null ? defaultValue : value;
}
/**
* @param request
* @param attrName
* @param value
*/
public static void setSessionAttribute(ServletRequest request, String attrName, Object value) {
if (value == null) {
getSession(request, false).removeAttribute(attrName);
} else {
getSession(request, true).setAttribute(attrName, value);
}
}
/**
* @param request
* @param cookieName
* @return
*/
public static Cookie getCookie(HttpServletRequest request, String cookieName) {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies[0] != null) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return cookie;
}
}
}
return null;
}
/**
* @param request
* @param cookieName
* @return
*/
public static String readCookie(HttpServletRequest request, String cookieName) {
Cookie cookie = getCookie(request, cookieName);
if (cookie == null) {
return null;
}
String cookieValue = cookie.getValue();
if (StringUtils.isBlank(cookieValue)) {
return cookieValue;
}
return CodecUtils.urlDecode(cookieValue);
}
/**
* @param response
* @param cookieName
* @param cookieValue
*/
public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue) {
addCookie(response, cookieName, cookieValue, 60 * 60 * 24 * 14, null, null);
}
/**
* @param response
* @param cookieName
* @param cookieValue
* @param maxAge
* @param domain
* @param path
*/
public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue, int maxAge, String domain, String path) {
Cookie cookie = new Cookie(cookieName, CodecUtils.urlEncode(cookieValue));
cookie.setMaxAge(maxAge);
if (domain != null) {
cookie.setDomain(domain);
}
if (path != null) {
cookie.setPath(path);
}
response.addCookie(cookie);
}
/**
* @param request
* @param response
* @param cookieName
*/
public static void removeCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
Cookie cookie = getCookie(request, cookieName);
if (cookie == null) {
return;
}
cookie.setMaxAge(0);
response.addCookie(cookie);
}
/**
* @param response
* @return
*/
public static PrintWriter getWriter(HttpServletResponse response) {
try {
return response.getWriter();
} catch (IOException ex) {
throw new RuntimeException("Could't gets writer of response!", ex);
}
}
/**
* @param response
* @param output
*/
public static void write(HttpServletResponse response, String output) {
getWriter(response).write(output);
}
/**
* @param response
* @param output
*/
public static void writeJson(HttpServletResponse response, String output) {
setContentType(response, CT_JSON_RFC4627);
write(response, output);
}
/**
* @param request
* @return
* @throws IOException
*/
public static Document getRequestDocument(ServletRequest request) throws IOException {
BufferedReader reader = request.getReader();
if (reader == null) {
return null;
}
return XMLHelper.createDocument(reader, WebUtils.ENCODING_DEFAULT, true);
}
/**
* @param request
* @return
*/
public static JSON getRequestJson(ServletRequest request) {
String req = getRequestString(request);
return (JSON) JSON.parse(req);
}
/**
* @param request
* @return
*/
public static String getRequestString(ServletRequest request) {
BufferedReader br;
try {
br = request.getReader();
if (br == null) {
return null;
}
} catch (IOException ex) {
throw new RuntimeException("Could't gets reader of response!", ex);
}
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException ex) {
throw new RuntimeException("Could't read line of reader!", ex);
}
return sb.toString();
}
/**
* @param response
* @param contentType
*/
public static void setContentType(ServletResponse response, String contentType) {
String encod = response.getCharacterEncoding();
encod = (StringUtils.isBlank(encod)) ? "UTF-8" : encod;
response.setContentType(contentType + "; charset=" + encod);
}
/**
* @param request
* @param response
* @param path
*/
public static void forward(ServletRequest request, HttpServletResponse response, String path) {
try {
request.getRequestDispatcher(path).forward(request, response);
} catch (Exception ex) {
throw new RuntimeException("Could't forward to url: " + path, ex);
}
}
/**
* @param response
*/
public static void setNoCacheHeaders(HttpServletResponse response) {
// Set to expire far in the past.
response.setHeader("expires", "Sat, 6 May 1995 12:00:00 GMT");
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("cache-control", "no-cache,no-store,max-age=0");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("cache-control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("pragma", "no-cache");
}
/**
* @param request
* @return
*/
public static String getRemoteAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// Fix ip prefix
if (ip != null && ip.length() > 7) {
if (ip.startsWith("::ffff:")) ip = ip.substring(7);
else if ("0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) ip = "127.0.0.1";
}
return ip;
}
/**
* @param request
* @return
*/
public static String getReferer(HttpServletRequest request) {
return request.getHeader("referer");
}
/**
* @param request
* @return
*/
public static boolean isAjaxRequest(HttpServletRequest request) {
String hv = request.getHeader("x-requested-with");
return "XMLHttpRequest".equalsIgnoreCase(hv);
}
/**
* 添加缓存头(到期时间、max-age)
*
* @param response
* @param minute
*/
public static void addCacheHead(HttpServletResponse response, int minute) {
response.setHeader("Cache-Control", "public, max-age=" + (minute * 60));
response.setDateHeader("Expires", CalendarUtils.add(minute, Calendar.MINUTE).getTime());
}
/**
* 获取请求 URL(包括参数)
*
* @param request
* @return
*/
public static String getFullRequestUrl(HttpServletRequest request) {
StringBuffer fullUrl = request.getRequestURL();
String qstr = request.getQueryString();
if (StringUtils.isNotBlank(qstr)) {
fullUrl.append("?").append(qstr);
}
return fullUrl.toString();
}
/**
* 获取请求协议
*
* @param request
* @return
*/
public static String getScheme(HttpServletRequest request) {
String scheme = request.getHeader("x-forwarded-proto");
if (StringUtils.isBlank(scheme)) {
scheme = request.getScheme();
}
return scheme;
}
// -----------------------------------------------------------------------------------
public static final String INCLUDE_REQUEST_URI = "javax.servlet.include.request_uri";
public static final String INCLUDE_CONTEXT_PATH = "javax.servlet.include.context_path";
public static final String INCLUDE_SERVLET_PATH = "javax.servlet.include.servlet_path";
public static final String INCLUDE_PATH_INFO = "javax.servlet.include.path_info";
public static final String INCLUDE_QUERY_STRING = "javax.servlet.include.query_string";
public static final String FORWARD_REQUEST_URI = "javax.servlet.forward.request_uri";
public static final String FORWARD_CONTEXT_PATH = "javax.servlet.forward.context_path";
public static final String FORWARD_SERVLET_PATH = "javax.servlet.forward.servlet_path";
public static final String FORWARD_PATH_INFO = "javax.servlet.forward.path_info";
public static final String FORWARD_QUERY_STRING = "javax.servlet.forward.query_string";
public static final String ERROR_STATUS_CODE = "javax.servlet.error.status_code";
public static final String ERROR_EXCEPTION_TYPE = "javax.servlet.error.exception_type";
public static final String ERROR_MESSAGE = "javax.servlet.error.message";
public static final String ERROR_EXCEPTION = "javax.servlet.error.exception";
public static final String ERROR_REQUEST_URI = "javax.servlet.error.request_uri";
public static final String ERROR_SERVLET_NAME = "javax.servlet.error.servlet_name";
public static final String JSP_JSP_EXCEPTION = "javax.servlet.jsp.jspException";
public static final String CT_PLAIN = "text/plain";
public static final String CT_HTML = "text/html";
public static final String CT_XML = "text/xml";
public static final String CT_JS = "text/javascript";
public static final String CT_JS_RFC4392 = "application/javascript";
public static final String CT_JSON = CT_JS;
public static final String CT_JSON_RFC4627 = "application/json";
}
package cn.easycode.akina.commons.web;
import cn.easycode.akina.commons.lang.StringUtils;
import java.util.Enumeration;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
/**
*
* @author Zhao Fangfang
* @version $Id: Bean2Json.java 48 2015-08-18 02:57:54Z zhaofang123@gmail.com $
*/
public class WebUtils {
public static final String ENCODING_UTF8 = "UTF-8";
public static final String ENCODING_GBK = "GBK";
public static final String ENCODING_DEFAULT = ENCODING_UTF8;
// ---------------------------------------------- TOKENs
/**
* KEY 前缀 */
public static final String KEY_PREFIX = WebUtils.class.getPackage().getName() + "__";
/**
* 当前会话中的用户 */
public static final String CURRENT_USER = KEY_PREFIX + "CURRENT_USER";
/**
* Request#attribute 中的消息 */
public static final String REQUEST_MESSAGE = KEY_PREFIX + "REQUEST_MESSAGE";
// ---------------------------------------------- STATUS CODEs
public static final int STATUS_OK = 0;
public static final int STATUS_FAIL = 1;
public static final int STATUS_ERROR = 2;
/**
* @param request
* @param message
*/
public static void setMessage(ServletRequest request, String message) {
request.setAttribute(REQUEST_MESSAGE, message);
}
/**
* @param request
* @return
*/
public static String getMessage(ServletRequest request) {
return (String) request.getAttribute(WebUtils.REQUEST_MESSAGE);
}
/**
* @param request
* @return
*/
public static String dumpHeaders(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
Enumeration<?> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = request.getHeader(name);
sb.append(name).append('=').append(StringUtils.isBlank(value) ? "<blank>" : value).append("; ");
}
return sb.toString();
}
/**
* @param request
* @return
*/
public static String dumpAttributes(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
Enumeration<?> names = request.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Object value = request.getAttribute(name);
sb.append(name).append('=').append(value == null ? "<null>" : value).append("; ");
}
return sb.toString();
}
/**
* @param request
* @return
*/
public static String dumpParameters(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
Enumeration<?> names = request.getParameterNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Object value = request.getParameter(name);
sb.append(name).append('=').append(value == null ? "<null>" : value).append("; ");
}
return sb.toString();
}
}
package cn.easycode.akina.commons.xml;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.io.SAXReader;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* SAXReader 缓存
*
* @author Zhao Fangfang
* @version $Id: Bean2Json.java 48 2015-08-18 02:57:54Z zhaofang123@gmail.com $
*/
public class FastSAXReader {
private static final Log LOG = LogFactory.getLog(FastSAXReader.class);
private final int initial;
private final Queue<XMLReader> xmlReadres = new ConcurrentLinkedQueue<>();
/**
* @param initial
*/
public FastSAXReader(int initial) {
this.initial = initial;
doInitAllCache();
}
/**
* @param xxe
* @return
*/
public SAXReader getSAXParser(boolean xxe) {
XMLReader xmlReader = xmlReadres.poll();
if (xmlReader == null) {
LOG.warn("No more cache, create new XMLReader ....");
xmlReader = doCachingOneReader(null);
}
SAXReader saxReader = new SAXReader(xmlReader);
saxReader.setMergeAdjacentText(true);
if (xxe) {
try {
saxReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
} catch (SAXException ignored) {
// NOOP
}
}
return saxReader;
}
/**
* @param reader
*/
public void release(SAXReader reader) {
try {
xmlReadres.add(reader.getXMLReader());
} catch (SAXException e) {
LOG.warn("Release SAXReader to cache fail!", e);
}
}
/**
* Initialize cache
*/
private void doInitAllCache() {
LOG.debug("Initializing " + initial + " SAXReader in cache");
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
for (int i = 0; i < initial; i++) {
doCachingOneReader(factory);
}
} catch (Exception ex) {
throw new ExceptionInInitializerError(ex);
}
}
private XMLReader doCachingOneReader(SAXParserFactory factory) {
if (factory == null) {
factory = SAXParserFactory.newInstance();
}
try {
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setFeature("http://xml.org/sax/features/validation", false);
xmlReadres.add(reader);
return reader;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
package cn.easycode.akina.commons.xml;
import cn.easycode.akina.commons.lang.StringUtils;
import cn.easycode.akina.commons.web.WebUtils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
/**
* XML helper
*
* @author Zhao Fangfang
* @version $Id: Bean2Json.java 48 2015-08-18 02:57:54Z zhaofang123@gmail.com $
*/
public class XMLHelper {
private static final FastSAXReader FAST_SAX_READER = new FastSAXReader(100);
/**
* @param text
* @return
*/
public static Document parseText(String text) {
try {
return DocumentHelper.parseText(text);
} catch (DocumentException ex) {
throw new IllegalArgumentException("Bad XML content: " + text, ex);
}
}
/**
* @param fileName
* @return
*/
public static Document createDocument(String fileName) {
try {
return createDocument(new FileInputStream(fileName));
} catch (FileNotFoundException ex) {
throw new RuntimeException("Could't found specify file: " + fileName, ex);
}
}
/**
* @param stream
* @return
*/
public static Document createDocument(InputStream stream) {
SAXReader saxReader = FAST_SAX_READER.getSAXParser(false);
try {
saxReader.setEncoding(WebUtils.ENCODING_DEFAULT);
return saxReader.read(stream);
} catch (DocumentException ex) {
throw new RuntimeException("Could't read XML from InputStream!", ex);
} finally {
FAST_SAX_READER.release(saxReader);
try {
stream.close();
} catch (IOException ignore) { }
}
}
/**
* @param reader
* @return
*/
public static Document createDocument(Reader reader) {
return createDocument(reader, WebUtils.ENCODING_DEFAULT);
}
/**
* @param reader
* @param encoding
* @return
*/
public static Document createDocument(Reader reader, String encoding) {
return createDocument(reader, encoding, false);
}
/**
* @param reader
* @param encoding
* @param xxe
* @return
*/
public static Document createDocument(Reader reader, String encoding, boolean xxe) {
SAXReader saxReader = FAST_SAX_READER.getSAXParser(xxe);
try {
saxReader.setEncoding(encoding);
return saxReader.read(reader);
} catch (DocumentException ex) {
throw new RuntimeException("Could't read XML from InputStream!", ex);
} finally {
FAST_SAX_READER.release(saxReader);
try {
reader.close();
} catch (IOException ignore) { }
}
}
/**
* 获取元素内容
*
* @param node
* @param xpath
* @return
*/
public static String getText(Node node, String xpath) {
if (node == null) {
return StringUtils.EMPTY;
}
if (!StringUtils.isEmpty(xpath)) {
node = node.selectSingleNode(xpath);
}
return node == null ? StringUtils.EMPTY : node.getText();
}
/**
* 获取属性值
*
* @param node
* @param xpath
* @param attrName
* @return
*/
public static String getAttribute(Node node, String xpath, String attrName) {
if (node == null) {
return StringUtils.EMPTY;
}
if (!StringUtils.isEmpty(xpath)) {
node = node.selectSingleNode(xpath);
}
return node == null ? StringUtils.EMPTY
: StringUtils.defaultIfEmpty(node.valueOf("@" + attrName), StringUtils.EMPTY);
}
}
package cn.easycode.akina.commons.xml;
import java.io.StringWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamResult;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.DocumentSource;
/**
* XSLT 解析者
*
* @author Zhao Fangfang
* @version $Id: Bean2Json.java 48 2015-08-18 02:57:54Z zhaofang123@gmail.com $
*/
public class XSLTParser {
private final Transformer transformer;
/**
* @param transformer
*/
protected XSLTParser(Transformer transformer) {
this.transformer = transformer;
}
/**
* @return
*/
public Transformer getTransformer() {
return this.transformer;
}
/**
* @param element
* @return
*/
public String parse(Element element) {
return parse( DocumentHelper.createDocument(element) );
}
/**
* @param document
* @return
*/
public String parse(Document document) {
StringWriter sw = new StringWriter();
StreamResult outputTarget = new StreamResult(sw);
DocumentSource xmlSource = new DocumentSource(document);
try {
synchronized (transformer) {
transformer.transform(xmlSource, outputTarget);
}
} catch (TransformerException e) {
throw new RuntimeException("Transform document error!", e);
}
return sw.toString();
}
}
package cn.easycode.akina.commons.xml;
import java.io.InputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
/**
* XSLT 解析者工厂
*
* @author Zhao Fangfang
* @version $Id: Bean2Json.java 48 2015-08-18 02:57:54Z zhaofang123@gmail.com $
*/
public class XSLTParserFactory {
private static TransformerFactory transformerFactory;
static {
new XSLTParserFactory();
}
private XSLTParserFactory() {
transformerFactory = TransformerFactory.newInstance();
}
/**
* @param stream
* @return
*/
public static XSLTParser newParser(InputStream stream) {
StreamSource source = new StreamSource(stream);
Transformer t = newTransformer(source);
return new XSLTParser(t);
}
/**
* @param source
* @return
*/
public static Transformer newTransformer(StreamSource source) {
try {
return transformerFactory.newTransformer(source);
} catch (TransformerConfigurationException e) {
throw new RuntimeException("Could't create xslt transformer!", e);
}
}
}
......@@ -22,8 +22,10 @@
<!-- ${project.xxx} 当前pom文件的任意节点的内容 如project.artifactId -->
<properties>
<!-- 基础属性 -->
<java.version>1.8</java.version>
<reversion>1.0.1-SNAPSHOT</reversion>
<!-- 基础属性 -->
<java.version>17</java.version>
<resource.delimiter>@</resource.delimiter>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
......@@ -43,6 +45,14 @@
<versions-maven-plugin.version>2.7</versions-maven-plugin.version>
<git-commit-id-plugin.version>4.9.10</git-commit-id-plugin.version>
<nexus-staging-maven-plugin.version>1.6.13</nexus-staging-maven-plugin.version>
<!-- 推荐使用Harbor -->
<docker-maven-plugin.version>1.2.2</docker-maven-plugin.version>
<sonar.exclusions>mate-admin/**/*, mate-core/**/*</sonar.exclusions>
<docker.baseImage>openjdk:8-jre-alpine</docker.baseImage>
<docker.volumes>/tmp</docker.volumes>
<docker.image.prefix>192.168.3.6:8080/eweb</docker.image.prefix>
<docker.java.security.egd>-Djava.security.egd=file:/dev/./urandom</docker.java.security.egd>
<docker.java.opts>-Xms128m -Xmx128m</docker.java.opts>
<spring.boot.version>2.7.10</spring.boot.version>
<spring-boot-admin.version>2.7.10</spring-boot-admin.version>
......@@ -53,8 +63,11 @@
<cola.version>4.1.0</cola.version>
<mysql.connector.version>8.0.31</mysql.connector.version>
<oracle.connector.version>12.2.0.1</oracle.connector.version>
<postgresql.connector.version>42.4.3</postgresql.connector.version>
<!-- ORM 组件 -->
<druid.version>1.2.8</druid.version>
<mybatis.version>3.5.13</mybatis.version>
<mybatis-spring.version>2.0.7</mybatis-spring.version>
<mybatis.typehandlers.version>1.0.2</mybatis.typehandlers.version>
......@@ -62,13 +75,20 @@
<mybatis-plus-generator.version>3.5.2</mybatis-plus-generator.version>
<mybaits.generator.version>3.4.1</mybaits.generator.version>
<p6spy.version>3.9.1</p6spy.version>
<!-- 分页插件 -->
<pagehelper.version>5.3.1</pagehelper.version>
<dynamic-datasource.version>3.5.2</dynamic-datasource.version>
<!-- 数据源 -->
<druid.version>1.2.16</druid.version>
<p6spy.version>3.9.1</p6spy.version>
<dynamic-datasource.version>3.5.2</dynamic-datasource.version>
<sharding-jdbc.version>4.1.1</sharding-jdbc.version>
<!-- 缓存 -->
<redisson.version>3.18.1</redisson.version>
<lettuce.version>6.2.2.RELEASE</lettuce.version>
<caffeine.version>3.1.2</caffeine.version>
<!-- Web 组件 -->
<javax-ws-rs.version>2.1.1</javax-ws-rs.version>
<resteasy.version>5.0.2.Final</resteasy.version>
......@@ -120,6 +140,7 @@
<batik.version>1.12</batik.version>
<ftpserver.version>1.1.1</ftpserver.version>
<truelicense.version>1.33</truelicense.version>
<snakeyaml.version>1.30</snakeyaml.version>
<fastjson.version>1.2.83_noneautotype</fastjson.version>
<fastjson2.version>2.0.11</fastjson2.version>
......@@ -250,6 +271,7 @@
<artifactId>cola-component-catchlog-starter</artifactId>
<version>${cola.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
......@@ -296,6 +318,18 @@
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${dynamic-datasource.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
......@@ -320,7 +354,11 @@
<version>${mvel.version}</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.oshi</groupId>
<artifactId>oshi-core</artifactId>
<version>6.4.0</version>
</dependency>
<!-- 工具集-->
<dependency>
<groupId>org.ow2.asm</groupId>
......@@ -358,6 +396,29 @@
<artifactId>disruptor</artifactId>
<version>${disruptor.version}</version>
</dependency>
<!-- JSON Lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<!-- Google JSON工具包,未来替换fastjson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2</artifactId>
<version>${fastjson2.version}</version>
</dependency>
<!-- Thumbnailator -->
<dependency>
<groupId>net.coobird</groupId>
......@@ -456,13 +517,7 @@
<artifactId>ftpserver-core</artifactId>
<version>${ftpserver.version}</version>
</dependency>
<!-- JSON Lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>${json-lib.version}</version>
<classifier>jdk15</classifier>
</dependency>
<!-- 对象转换 -->
<dependency>
<groupId>com.github.dozermapper</groupId>
......@@ -553,7 +608,11 @@
<artifactId>dom4j</artifactId>
<version>${dom4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
......
......@@ -9,8 +9,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>eweb-parent</artifactId>
<packaging>pom</packaging>
<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>
<url>http://maven.apache.org</url>
......
package cn.easycode.akina;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
package cn.easycode.akina;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
......@@ -8,7 +8,7 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>eweb-tests</artifactId>
<packaging>jar</packaging>
<packaging>pom</packaging>
<name>eweb-tests</name>
<url>http://maven.apache.org</url>
......@@ -18,11 +18,6 @@
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
#Organize Import Order
0=java
1=javax
2=org
3=com
4=
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册