提交 4aa6efbc authored 作者: 陈世营's avatar 陈世营

【新增】leaf 接口

上级 3a13cb57
...@@ -60,6 +60,27 @@ ...@@ -60,6 +60,27 @@
<!-- 集成swagger ui --> <!-- 集成swagger ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-swagger-ui.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-swagger-ui.version}</version>
</dependency>
<!-- 解决Integer类型example为空时,访问swagger报错问题 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${io-swagger.version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${io-swagger.version}</version>
</dependency>
<!-- 解决Integer类型example为空时,访问swagger报错问题 --> <!-- 解决Integer类型example为空时,访问swagger报错问题 -->
......
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>LoitKeyGenerate</artifactId>
<groupId>com.loit.key.generate</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>loit-keygen-server</artifactId>
<packaging>jar</packaging>
<dependencies>
<!-- 集成swagger ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!-- 解决Integer类型example为空时,访问swagger报错问题 -->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</dependency>
<dependency>
<groupId>com.timeloit.project</groupId>
<artifactId>loit-keygen-leaf-config</artifactId>
</dependency>
<!-- 微服务:Feign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- nacos 注册中心 -->
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-starter-timeloit-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-timeloit-nacos-config</artifactId>
</dependency>
</dependencies>
<build>
<finalName>loit-keygen-server</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
\ No newline at end of file
package com.loit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
@ServletComponentScan
@EnableFeignClients
@RestController
@EnableSwagger2
public class LoitKeygenServerApplication extends SpringBootServletInitializer {
private static Logger log = LoggerFactory.getLogger(LoitKeygenServerApplication.class);
@Override
protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(LoitKeygenServerApplication.class);
}
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
SpringApplication.run(LoitKeygenServerApplication.class, args);
long endTime = System.currentTimeMillis();
float excTime = (float) (endTime - startTime) / 1000;
log.info("############--- loit-maintenance项目启动成功,执行用时:" + excTime + "秒 ---############");
}
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
final CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); // 允许cookies跨域
config.addAllowedOrigin("*");// #允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
config.addAllowedHeader("*");// #允许访问的头信息,*表示全部
config.setMaxAge(18000L);// 预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
config.addAllowedMethod("OPTIONS");// 允许提交请求的方法,*表示全部允许
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");// 允许Get的请求方法
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
package com.loit.common.config;
import com.google.common.collect.Maps;
import com.loit.common.utils.PropertiesLoader;
import com.loit.common.utils.StringUtils;
import org.apache.ibatis.io.Resources;
import org.springframework.core.io.DefaultResourceLoader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.Map;
import java.util.Properties;
/**
* 全局配置类
* @author loit
* @version 2014-06-25
*/
public class Global {
/**
* 当前对象实例
*/
private static Global global = new Global();
/**
* 保存全局属性值
*/
private static Map<String, String> map = Maps.newHashMap();
/**
* 属性文件加载对象
*/
private static PropertiesLoader loader = new PropertiesLoader("/config/custom.properties");
/**
* 显示/隐藏
*/
public static final String SHOW = "1";
public static final String HIDE = "0";
/**
* 是/否
*/
public static final String YES = "1";
public static final String NO = "0";
/**
* 对/错
*/
public static final String TRUE = "true";
public static final String FALSE = "false";
/**
* 上传文件基础虚拟路径
*/
public static final String USERFILES_BASE_URL = "/userfiles/";
/**
* 获取当前对象实例
*/
public static Global getInstance() {
return global;
}
/**
* 获取配置
* @see ${fns:getConfig('adminPath')}
*/
public static String getConfig(String key) {
String value = map.get(key);
if (value == null){
value = loader.getProperty(key);
map.put(key, value != null ? value : StringUtils.EMPTY);
}
return value;
}
/**
* 获取管理端根路径
*/
public static String getAdminPath() {
return getConfig("adminPath");
}
/**
* 获取前端根路径
*/
public static String getFrontPath() {
return getConfig("frontPath");
}
/**
* 获取URL后缀
*/
public static String getUrlSuffix() {
return getConfig("urlSuffix");
}
/**
* 是否是演示模式,演示模式下不能修改用户、角色、密码、菜单、授权
*/
public static Boolean isDemoMode() {
String dm = getConfig("demoMode");
return "true".equals(dm) || "1".equals(dm);
}
/**
* 在修改系统用户和角色时是否同步到Activiti
*/
public static Boolean isSynActivitiIndetity() {
String dm = getConfig("activiti.isSynActivitiIndetity");
return "true".equals(dm) || "1".equals(dm);
}
/**
* 页面获取常量
* @see ${fns:getConst('YES')}
*/
public static Object getConst(String field) {
try {
return Global.class.getField(field).get(null);
} catch (Exception e) {
// 异常代表无配置,这里什么也不做
}
return null;
}
/**
* 获取上传文件的根目录
* @return
*/
public static String getUserfilesBaseDir() {
String dir = getConfig("userfiles.basedir");
if (StringUtils.isBlank(dir)){
try {
// dir = ServletContextFactory.getServletContext().getRealPath("/");
} catch (Exception e) {
return "";
}
}
if(!dir.endsWith("/")) {
dir += "/";
}
return dir;
}
/**
* 获取工程路径
* @return
*/
public static String getProjectPath(){
// 如果配置了工程路径,则直接返回,否则自动获取。
String projectPath = Global.getConfig("projectPath");
if (StringUtils.isNotBlank(projectPath)){
return projectPath;
}
try {
File file = new DefaultResourceLoader().getResource("").getFile();
if (file != null){
while(true){
File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
if (f == null || f.exists()){
break;
}
if (file.getParentFile() != null){
file = file.getParentFile();
}else{
break;
}
}
projectPath = file.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return projectPath;
}
/**
* 写入properties信息
*
* @param key
* 名称
* @param value
* 值
*/
public static void modifyConfig(String key, String value) {
try {
// 从输入流中读取属性列表(键和元素对)
Properties prop = getProperties();
prop.setProperty(key, value);
String path = Global.class.getResource("/config/custom.properties").getPath();
FileOutputStream outputFile = new FileOutputStream(path);
prop.store(outputFile, "modify");
outputFile.close();
outputFile.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 返回 Properties
* @param fileName 文件名 (注意:加载的是src下的文件,如果在某个包下.请把包名加上)
* @param
* @return
*/
public static Properties getProperties(){
Properties prop = new Properties();
try {
Reader reader = Resources.getResourceAsReader("/config/custom.properties");
prop.load(reader);
} catch (Exception e) {
return null;
}
return prop;
}
}
package com.loit.common.config;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Swagger配置
*
* @author wbh
* @date 2018年12月15日
*/
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
@Primary
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(Swagger2
.basePackage("com.loit.key.generate")).paths(PathSelectors.any()).build();
}
/**
* Predicate that matches RequestHandler with given base package name for the class of the handler method.
* This predicate includes all request handlers matching the provided basePackage
*
* @param basePackage - base package of the classes
* @return this
*/
public static Predicate<RequestHandler> basePackage(final String basePackage) {
return new Predicate<RequestHandler>() {
@Override
public boolean apply(RequestHandler input) {
return declaringClass(input).transform(handlerPackage(basePackage)).or(true);
}
};
}
/**
* 处理包路径配置规则,支持多路径扫描匹配以逗号隔开
*
* @param basePackage 扫描包路径
* @return Function
*/
private static Function<Class<?>, Boolean> handlerPackage(final String basePackage) {
return new Function<Class<?>, Boolean>() {
@Override
public Boolean apply(Class<?> input) {
for (String strPackage : basePackage.split(",")) {
boolean isMatch = input.getPackage().getName().startsWith(strPackage);
if (isMatch) {
return true;
}
}
return false;
}
};
}
/**
* @param input RequestHandler
* @return Optional
*/
@SuppressWarnings("deprecation")
private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
return Optional.fromNullable(input.declaringClass());
}
private ApiInfo apiInfo() {
InetAddress address;
String hostAddress = null;
try {
address = InetAddress.getLocalHost();
hostAddress = address.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}//获取的是本地的IP地址
String projectName = Global.getConfig("productName");
return new ApiInfoBuilder()
.title(projectName + "api文档")
.description("v1.0 add by gaoyanyun (2514917157@qq.com) \n"
+ "v1.1 update by wangbh (wbh1213@qq.com)")
.termsOfServiceUrl("http://" + hostAddress + ":9008/api-demo/swagger-ui.html")
.version("1.0")
.build();
}
}
package com.loit.common.config;
import com.loit.common.interceptor.LogInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 拦截器配置
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
protected Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 添加拦截器
registry.addInterceptor(securityInterceptor()).addPathPatterns("/**");
}
private HandlerInterceptor securityInterceptor() {
return new LogInterceptor();
}
}
package com.loit.common.config;
\ No newline at end of file
package com.loit.common.exception;
/**
* 基础异常
*/
public class BusinessException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
//所属模块
private String module;
/**
* 错误码
*/
private String code;
/**
* Ba
* 错误码对应的参数
*/
private Object[] args;
/**
* 错误消息
*/
private String defaultMessage;
public BusinessException(String module, String code, Object[] args, String defaultMessage) {
super(defaultMessage);
this.module = module;
this.code = code;
this.args = args;
this.defaultMessage = defaultMessage;
}
public BusinessException(String module, String code, Object[] args) {
this(module, code, args, null);
}
public BusinessException(String module, String defaultMessage) {
this(module, null, null, defaultMessage);
}
public BusinessException(String code, Object[] args) {
this(null, code, args, null);
}
public BusinessException(String defaultMessage) {
this(null, null, null, defaultMessage);
}
public String getModule() {
return module;
}
public String getCode() {
return code;
}
public Object[] getArgs() {
return args;
}
public String getDefaultMessage() {
return defaultMessage;
}
@Override
public String toString() {
return this.getClass() + "{" +
"module='" + module + '\'' +
", message='" + getMessage() + '\'' +
'}';
}
}
/**
* Copyright &copy; 2015-2020 isaac All rights reserved.
*/
package com.loit.common.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
/**
* 日志拦截器
*
* @author zpc
* @version 2014-8-19
*/
public class LogInterceptor implements HandlerInterceptor {
protected Logger logger = LoggerFactory.getLogger(getClass());
private static final ThreadLocal<Long> startTimeThreadLocal =
new NamedThreadLocal<Long>("ThreadLocal StartTime");
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
long beginTime = System.currentTimeMillis();//1、开始时间
if (logger.isDebugEnabled()) {
startTimeThreadLocal.set(beginTime); //线程绑定变量(该数据只有当前请求的线程可见)
logger.debug("[{}] 开始计时: {} URI: {} ", beginTime, new SimpleDateFormat("hh:mm:ss.SSS")
.format(beginTime), request.getRequestURI());
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
logger.info("ViewName: " + modelAndView.getViewName());
}
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
// 保存日志
//LogUtils.saveLog(request, handler, ex, null);
// 打印JVM信息。
if (logger.isDebugEnabled()) {
long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量(开始时间)
long endTime = System.currentTimeMillis(); //2、结束时间
long timeSlot = endTime - beginTime;
String timeDesc = "time consuming";
if (timeSlot > 1000 && timeSlot <= 5000) {
timeDesc = "long time consuming";
} else if (timeSlot > 5000) {
timeDesc = "super long time consuming";
}
logger.debug("[{}] 计时结束:{} {}: {} URI: {} 最大内存: {}m 已分配内存: {}m 已分配内存中的剩余空间: {}m 最大可用内存: {}m",
beginTime, new SimpleDateFormat("hh:mm:ss.SSS").format(endTime), timeDesc, timeSlot + "ms",
request.getRequestURI(), Runtime.getRuntime().maxMemory() / 1024 / 1024, Runtime.getRuntime().totalMemory() / 1024 / 1024, Runtime.getRuntime().freeMemory() / 1024 / 1024,
(Runtime.getRuntime().maxMemory() - Runtime.getRuntime().totalMemory() + Runtime.getRuntime().freeMemory()) / 1024 / 1024);
}
}
}
/**
* Copyright (c) 2005-2011 springside.org.cn
*
* $Id: PropertiesLoader.java 1690 2012-02-22 13:42:00Z calvinxiu $
*/
package com.loit.common.utils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import java.io.IOException;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Properties;
/**
* Properties文件载入工具类. 可载入多个properties文件, 相同的属性在最后载入的文件中的值将会覆盖之前的值,但以System的Property优先.
* @author calvin
* @version 2013-05-15
*/
public class PropertiesLoader {
private static Logger logger = LoggerFactory.getLogger(PropertiesLoader.class);
private static ResourceLoader resourceLoader = new DefaultResourceLoader();
private final Properties properties;
public PropertiesLoader(String... resourcesPaths) {
properties = loadProperties(resourcesPaths);
}
public Properties getProperties() {
return properties;
}
/**
* 取出Property,但以System的Property优先,取不到返回空字符串.
*/
private String getValue(String key) {
String systemProperty = System.getProperty(key);
if (systemProperty != null) {
return systemProperty;
}
if (properties.containsKey(key)) {
return properties.getProperty(key);
}
return "";
}
/**
* 取出String类型的Property,但以System的Property优先,如果都为Null则抛出异常.
*/
public String getProperty(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return value;
}
/**
* 取出String类型的Property,但以System的Property优先.如果都为Null则返回Default值.
*/
public String getProperty(String key, String defaultValue) {
String value = getValue(key);
return value != null ? value : defaultValue;
}
/**
* 取出Integer类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
*/
public Integer getInteger(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return Integer.valueOf(value);
}
/**
* 取出Integer类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
*/
public Integer getInteger(String key, Integer defaultValue) {
String value = getValue(key);
return value != null ? Integer.valueOf(value) : defaultValue;
}
/**
* 取出Double类型的Property,但以System的Property优先.如果都为Null或内容错误则抛出异常.
*/
public Double getDouble(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return Double.valueOf(value);
}
/**
* 取出Double类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容错误则抛出异常
*/
public Double getDouble(String key, Integer defaultValue) {
String value = getValue(key);
return value != null ? Double.valueOf(value) : defaultValue;
}
/**
* 取出Boolean类型的Property,但以System的Property优先.如果都为Null抛出异常,如果内容不是true/false则返回false.
*/
public Boolean getBoolean(String key) {
String value = getValue(key);
if (value == null) {
throw new NoSuchElementException();
}
return Boolean.valueOf(value);
}
/**
* 取出Boolean类型的Property,但以System的Property优先.如果都为Null则返回Default值,如果内容不为true/false则返回false.
*/
public Boolean getBoolean(String key, boolean defaultValue) {
String value = getValue(key);
return value != null ? Boolean.valueOf(value) : defaultValue;
}
/**
* 载入多个文件, 文件路径使用Spring Resource格式.
*/
private Properties loadProperties(String... resourcesPaths) {
Properties props = new Properties();
for (String location : resourcesPaths) {
// logger.debug("Loading properties file from:" + location);
InputStream is = null;
try {
Resource resource = resourceLoader.getResource(location);
is = resource.getInputStream();
props.load(is);
} catch (IOException ex) {
logger.info("Could not load properties from path:" + location + ", " + ex.getMessage());
} finally {
IOUtils.closeQuietly(is);
}
}
return props;
}
}
/**
* Copyright &copy; 2015-2020 isaac All rights reserved.
*/
package com.loit.common.utils;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
* @author loit
* @version 2013-05-22
*/
public class StringUtils extends org.apache.commons.lang3.StringUtils {
private static final char SEPARATOR = '_';
private static final String CHARSET_NAME = "UTF-8";
/**
* 转换为字节数组
* @param str
* @return
*/
public static byte[] getBytes(String str){
if (str != null){
try {
return str.getBytes(CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return null;
}
}else{
return null;
}
}
/**
* 转换为字节数组
* @param bytes
* @return
*/
public static String toString(byte[] bytes){
try {
return new String(bytes, CHARSET_NAME);
} catch (UnsupportedEncodingException e) {
return EMPTY;
}
}
/**
* 是否包含字符串
* @param str 验证字符串
* @param strs 字符串组
* @return 包含返回true
*/
public static boolean inString(String str, String... strs){
if (str != null){
for (String s : strs){
if (str.equals(trim(s))){
return true;
}
}
}
return false;
}
/**
* 替换掉HTML标签方法
*/
public static String replaceHtml(String html) {
if (isBlank(html)){
return "";
}
String regEx = "<.+?>";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(html);
String s = m.replaceAll("");
return s;
}
/**
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
* @param html
* @return
*/
public static String replaceMobileHtml(String html){
if (html == null){
return "";
}
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
}
/**
* 缩略字符串(不区分中英文字符)
* @param str 目标字符串
* @param length 截取长度
* @return
*/
public static String abbr(String str, int length) {
if (str == null) {
return "";
}
try {
StringBuilder sb = new StringBuilder();
int currentLength = 0;
for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
currentLength += String.valueOf(c).getBytes("GBK").length;
if (currentLength <= length - 3) {
sb.append(c);
} else {
sb.append("...");
break;
}
}
return sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "";
}
public static String abbr2(String param, int length) {
if (param == null) {
return "";
}
StringBuffer result = new StringBuffer();
int n = 0;
char temp;
boolean isCode = false; // 是不是HTML代码
boolean isHTML = false; // 是不是HTML特殊字符,如&nbsp;
for (int i = 0; i < param.length(); i++) {
temp = param.charAt(i);
if (temp == '<') {
isCode = true;
} else if (temp == '&') {
isHTML = true;
} else if (temp == '>' && isCode) {
n = n - 1;
isCode = false;
} else if (temp == ';' && isHTML) {
isHTML = false;
}
try {
if (!isCode && !isHTML) {
n += String.valueOf(temp).getBytes("GBK").length;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (n <= length - 3) {
result.append(temp);
} else {
result.append("...");
break;
}
}
// 取出截取字符串中的HTML标记
String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)",
"$1$2");
// 去掉不需要结素标记的HTML标记
temp_result = temp_result
.replaceAll(
"</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
"");
// 去掉成对的HTML标记
temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>",
"$2");
// 用正则表达式取出标记
Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
Matcher m = p.matcher(temp_result);
List<String> endHTML = Lists.newArrayList();
while (m.find()) {
endHTML.add(m.group(1));
}
// 补全不成对的HTML标记
for (int i = endHTML.size() - 1; i >= 0; i--) {
result.append("</");
result.append(endHTML.get(i));
result.append(">");
}
return result.toString();
}
/**
* 转换为Double类型
*/
public static Double toDouble(Object val){
if (val == null){
return 0D;
}
try {
return Double.valueOf(trim(val.toString()));
} catch (Exception e) {
return 0D;
}
}
/**
* 转换为Float类型
*/
public static Float toFloat(Object val){
return toDouble(val).floatValue();
}
/**
* 转换为Long类型
*/
public static Long toLong(Object val){
return toDouble(val).longValue();
}
/**
* 转换为Integer类型
*/
public static Integer toInteger(Object val){
return toLong(val).intValue();
}
/**
* 获得用户远程地址
*/
public static String getRemoteAddr(HttpServletRequest request){
String remoteAddr = request.getHeader("X-Real-IP");
if (isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("X-Forwarded-For");
}else if (isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("Proxy-Client-IP");
}else if (isNotBlank(remoteAddr)) {
remoteAddr = request.getHeader("WL-Proxy-Client-IP");
}
return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
}
/**
* 驼峰命名法工具
* @return
* toCamelCase("hello_world") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCamelCase(String s) {
if (s == null) {
return null;
}
s = s.toLowerCase();
StringBuilder sb = new StringBuilder(s.length());
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == SEPARATOR) {
upperCase = true;
} else if (upperCase) {
sb.append(Character.toUpperCase(c));
upperCase = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
/**
* 驼峰命名法工具
* @return
* toCamelCase("hello_world") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toCapitalizeCamelCase(String s) {
if (s == null) {
return null;
}
s = toCamelCase(s);
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
/**
* 驼峰命名法工具
* @return
* toCamelCase("hello_world") == "helloWorld"
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
* toUnderScoreCase("helloWorld") = "hello_world"
*/
public static String toUnderScoreCase(String s) {
if (s == null) {
return null;
}
StringBuilder sb = new StringBuilder();
boolean upperCase = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
boolean nextUpperCase = true;
if (i < (s.length() - 1)) {
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
}
if ((i > 0) && Character.isUpperCase(c)) {
if (!upperCase || !nextUpperCase) {
sb.append(SEPARATOR);
}
upperCase = true;
} else {
upperCase = false;
}
sb.append(Character.toLowerCase(c));
}
return sb.toString();
}
/**
* 如果不为空,则设置值
* @param target
* @param source
*/
public static void setValueIfNotBlank(String target, String source) {
if (isNotBlank(source)){
target = source;
}
}
/**
* 转换为JS获取对象值,生成三目运算返回结果
* @param objectString 对象串
* 例如:row.user.id
* 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
*/
public static String jsGetVal(String objectString){
StringBuilder result = new StringBuilder();
StringBuilder val = new StringBuilder();
String[] vals = split(objectString, ".");
for (int i=0; i<vals.length; i++){
val.append("." + vals[i]);
result.append("!"+(val.substring(1))+"?'':");
}
result.append(val.substring(1));
return result.toString();
}
/**
* 首字母大写
* @param className
* @return
*/
public static String toUpString(String className) {
char[] cs = className.toCharArray();
cs[0] -= 32;
String ClassName = String.valueOf(cs);
return ClassName;
}
/**
* @Description: 首字母小写
* @author: Administrator
* @date: 2019年10月28日 下午3:47:19
* @param @param oldStr
* @param @return 参数
* @return String 返回类型
* @throws
*/
public static String toLowerString(String oldStr){
char[]chars = oldStr.toCharArray();
chars[0] += 32;
return String.valueOf(chars);
}
}
package com.loit.key.generate.server.controller;
import com.loit.component.keygen.leaf.LeafSegmentKeyGeneratorFactory;
import com.loit.key.generate.server.exception.LeafServerException;
import com.loit.key.generate.server.exception.NoKeyException;
import com.sankuai.inf.leaf.IDGen;
import com.sankuai.inf.leaf.common.Result;
import com.sankuai.inf.leaf.common.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LeafController {
private Logger logger = LoggerFactory.getLogger(LeafController.class);
@Autowired
private LeafSegmentKeyGeneratorFactory leafSegmentKeyGeneratorFactory;
@Autowired
private IDGen idGen;
@RequestMapping(value = "/api/segment/get/{key}")
public String getSegmentId(@PathVariable("key") String key) {
Comparable<?> t_order_id = leafSegmentKeyGeneratorFactory.getKeyGenerator(key).generateKey();
Result result = new Result();
result.setId((Long) t_order_id);
return get(key, result);
}
@RequestMapping(value = "/api/snowflake/get/{key}")
public String getSnowflakeId(@PathVariable("key") String key) {
Result result = idGen.get(key);
return get(key, result);
}
private String get(@PathVariable("key") String key, Result id) {
Result result;
if (key == null || key.isEmpty()) {
throw new NoKeyException("Key is none");
}
result = id;
if (Status.EXCEPTION.equals(result.getStatus())) {
throw new LeafServerException(result.toString());
}
return String.valueOf(result.getId());
}
}
package com.loit.key.generate.server.exception;
import com.loit.common.exception.BusinessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
public class LeafServerException extends BusinessException {
public LeafServerException(String msg) {
super(msg);
}
}
package com.loit.key.generate.server.exception;
import com.loit.common.exception.BusinessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Key is none")
public class NoKeyException extends BusinessException {
public NoKeyException(String defaultMessage) {
super(defaultMessage);
}
}
package com.loit.key.generate.server;
\ No newline at end of file
package com.loit;
\ No newline at end of file
server:
port: 9008
spring:
application:
name: loit-keygen-server
cloud:
nacos:
discovery:
# Nacos 注册中心地址
server-addr: 39.100.254.140:8103
namespace: 6c8fa2e5-a3b8-48a0-9ab6-c1097ecc0dc3
leaf:
namespace: leaf_${spring.application.name}
zkserver:
# zookeeper 地址
list: 127.0.0.1:2181
segment:
# 初始化Id
id.initial.value: 1
# 步长
step: 50
spring:
profiles:
active: dev
\ No newline at end of file
spring.profiles.active=dev
spring.application.name=loit-keygen-server
# Nacos
spring.cloud.nacos.config.server-addr=39.100.254.140:8103
spring.cloud.nacos.config.namespace=6c8fa2e5-a3b8-48a0-9ab6-c1097ecc0dc3
spring.cloud.nacos.config.file-extension=yaml
\ No newline at end of file
#\u4ea7\u54c1\u4fe1\u606f\u8bbe\u7f6e
productName=\u65f6\u4ee3\u51cc\u5b87\u8f6f\u4ef6\u5f00\u53d1
simpleName=demo
copyrightYear=2017
version=V1.0
#\u7248\u6743
copyrightFlag=true
copyrightMsg=Copyright &copy; \u5317\u4eac\u65f6\u4ee3\u51cc\u5b87\u79d1\u6280\u80a1\u4efd\u6709\u9650\u516c\u53f8
copyrightData=&copy; 2017-2025
#\u6f14\u793a\u6a21\u5f0f: \u4e0d\u80fd\u64cd\u4f5c\u548c\u4fdd\u5b58\u7684\u6a21\u5757\uff1a sys: area/office/user/role/menu/dict, cms: site/category
demoMode=false
#\u7ba1\u7406\u57fa\u7840\u8def\u5f84, \u9700\u540c\u6b65\u4fee\u6539\uff1aweb.xml
#adminPath=/a
#\u524d\u7aef\u57fa\u7840\u8def\u5f84
frontPath=/f
#\u7f51\u7ad9URL\u540e\u7f00
urlSuffix=.html
#\u662f\u5426\u4e0d\u5141\u8bb8\u5237\u65b0\u4e3b\u9875\uff0c\u4e0d\u5141\u8bb8\u60c5\u51b5\u4e0b\uff0c\u5237\u65b0\u4e3b\u9875\u4f1a\u5bfc\u81f4\u91cd\u65b0\u767b\u5f55
notAllowRefreshIndex=false
#\u662f\u5426\u5141\u8bb8\u591a\u8d26\u53f7\u540c\u65f6\u767b\u5f55
user.multiAccountLogin=true
#\u5206\u9875\u914d\u7f6e
page.pageSize=10
#\u7855\u6b63\u7ec4\u4ef6\u662f\u5426\u4f7f\u7528\u7f13\u5b58
supcan.useCache=false
#\u901a\u77e5\u95f4\u9694\u65f6\u95f4\u8bbe\u7f6e, \u5355\u4f4d\uff1a\u6beb\u79d2, 30s=30000ms, 60s=60000ms
oa.notify.remind.interval=60000
#============================#
#==== Framework settings ====#
#============================#
#\u4f1a\u8bdd\u8d85\u65f6\uff0c \u5355\u4f4d\uff1a\u6beb\u79d2\uff0c 20m=1200000ms, 30m=1800000ms, 60m=3600000ms
session.sessionTimeout=1800000
#\u4f1a\u8bdd\u6e05\u7406\u95f4\u9694\u65f6\u95f4\uff0c \u5355\u4f4d\uff1a\u6beb\u79d2\uff0c2m=120000ms\u3002
session.sessionTimeoutClean=120000
#\u7f13\u5b58\u8bbe\u7f6e
ehcache.configFile=cache/ehcache-local.xml
#ehcache.configFile=cache/ehcache-rmi.xml
#\u7d22\u5f15\u9875\u8def\u5f84
web.view.index=/a
#\u89c6\u56fe\u6587\u4ef6\u5b58\u653e\u8def\u5f84
web.view.prefix=/webpage/
web.view.suffix=.jsp
#\u6700\u5927\u6587\u4ef6\u4e0a\u4f20\u9650\u5236\uff0c\u5355\u4f4d\u5b57\u8282. 10M=10*1024*1024(B)=10485760 bytes\uff0c\u9700\u540c\u6b65\u4fee\u6539\uff1ackfinder.xml
web.maxUploadSize=10485760
#\u65e5\u5fd7\u62e6\u622a\u8bbe\u7f6e\uff0c\u6392\u9664\u7684URI\uff1b\u5305\u542b @RequestMapping\u6ce8\u89e3\u7684value\u3002\uff08\u5df2\u4f5c\u5e9f\uff09
#web.logInterceptExcludeUri=/, /login, /sys/menu/tree, /sys/menu/treeData, /oa/oaNotify/self/count
#web.logInterceptIncludeRequestMapping=save, delete, import, updateSort
#\u9759\u6001\u6587\u4ef6\u540e\u7f00
web.staticFile=.css,.js,.png,.jpg,.gif,.jpeg,.bmp,.ico,.swf,.psd,.htc,.htm,.html,.crx,.xpi,.exe,.ipa,.apk
#\u5355\u70b9\u767b\u5f55CAS\u8bbe\u7f6e
cas.server.url=http://127.0.0.1:8180/cas
cas.project.url=http://127.0.0.1:8080/loitSystem
#\u5de5\u4f5c\u6d41\u8bbe\u7f6e
activiti.isSynActivitiIndetity=false
activiti.export.diagram.path=c:/activiti_diagram
#activiti font (windows font: \u5b8b\u4f53 linux font: simsun)
activiti.diagram.activityFontName=\u5b8b\u4f53
activiti.diagram.labelFontName=\u5b8b\u4f53
#activiti\u5916\u90e8\u8868\u5355\u6839\u5730\u5740\u914d\u7f6e
activiti.form.server.url=
#\u4e0a\u4f20\u6587\u4ef6\u7edd\u5bf9\u8def\u5f84, \u8def\u5f84\u4e2d\u4e0d\u5141\u8bb8\u5305\u542b\u201cuserfiles\u201d
userfiles.basedir=D:/loitSystemImages
#\u5de5\u7a0b\u8def\u5f84\uff0c\u5728\u4ee3\u7801\u751f\u6210\u65f6\u83b7\u53d6\u4e0d\u5230\u5de5\u7a0b\u8def\u5f84\u65f6\uff0c\u53ef\u518d\u6b64\u6307\u5b9a\u7edd\u5bf9\u8def\u5f84\u3002
projectPath=D\:\\test
#
fromEmail=
toEmail=
emailName=
emailPassword=
cpu=100
jvm=100
ram=100
#\u9644\u4ef6\u4e0a\u4f20
userName=
password=
shareDir=localhost/MediaRoot/
#\u524d\u7aef\u8bfb\u53d6\u8def\u5f84
readShareDir=http://localhost:8080/MediaRoot/
#\u6c34\u5370\u8bfb\u53d6\u5730\u5740
srcImgPath=D:/apache-Tomcat-7.0/webapps/MediaRoot/
#\u6c34\u5370\u8f93\u51fa\u5730\u5740
tarImgPath=D:/apache-Tomcat-7.0/webapps/MediaRoot/
appKey=9c959b4e84b99c40568990cf
masterSecret=8a8079c5c481ca2e87d71f74
single=\\ftl\\single
many=\\ftl\\many
jdbc.type=mysql
file.uploadDir=/usr/portal
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<modules> <modules>
<module>loit-dependencies</module> <module>loit-dependencies</module>
<module>loit-keygen-server</module>
</modules> </modules>
<parent> <parent>
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论