0.0.1-SNAPSHOT
王兵 5 years ago
parent b12ba8d795
commit db8615d81e

@ -7,12 +7,14 @@
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="nginx-admin" />
<module name="nginx-admin (1)" />
</profile>
</annotationProcessing>
<bytecodeTargetLevel>
<module name="admin" target="1.8" />
<module name="nginx-admin" target="1.8" />
<module name="wsqlite" target="1.8" />
<module name="nginx-admin (1)" target="1.5" />
<module name="wsqlite" target="1.5" />
</bytecodeTargetLevel>
</component>
</project>

@ -1,141 +0,0 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>xyz.wbsite</groupId>
<artifactId>nginx-admin-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>xyz.wbsite</groupId>
<artifactId>nginx-admin</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven.test.skip>true</maven.test.skip>
</properties>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>xyz.wbsite</groupId>
<artifactId>wsqlite</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<!-- freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>net.sf.dozer</groupId>
<artifactId>dozer</artifactId>
</dependency>
</dependencies>
<build>
<!-- 项目名称 -->
<finalName>nginx-admin</finalName>
<!-- 默认的主代码目录 -->
<sourceDirectory>src/main/java</sourceDirectory>
<!-- 默认的测试代码目录 -->
<testSourceDirectory>src/test/java</testSourceDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<!-- 包含java下的xml文件 -->
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/mpr/*.xml</include>
</includes>
</resource>
<!-- 包含lib中所有jar包 -->
<resource>
<directory>${basedir}/src/main/resources/lib</directory>
<targetPath>BOOT-INF/lib/</targetPath>
<includes>
<include>*.jar</include>
</includes>
</resource>
<!-- 启动bat -->
<resource>
<directory>${basedir}/src/main/resources</directory>
<includes>
<include>*.bat</include>
</includes>
<targetPath>${basedir}/target</targetPath>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webResources>
<resource>
<directory>${project.basedir}/src/main/resources/lib</directory>
<targetPath>WEB-INF/lib</targetPath>
<includes>
<include>*.jar</include>
</includes>
</resource>
</webResources>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -1,21 +0,0 @@
package xyz.wbsite;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

@ -1,275 +0,0 @@
package xyz.wbsite.action;
import xyz.wbsite.frame.base.BaseResponse;
import xyz.wbsite.frame.base.Error;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.frame.utils.LocalData;
import xyz.wbsite.frame.utils.LogUtil;
import xyz.wbsite.frame.utils.MD5Util;
import xyz.wbsite.frame.utils.MapperUtil;
import xyz.wbsite.frame.utils.Message;
import xyz.wbsite.frame.utils.ProcessUtil;
import xyz.wbsite.frame.utils.ValidationUtil;
import xyz.wbsite.module.admin.ent.Mapping;
import xyz.wbsite.module.admin.ent.NginxCtrl;
import xyz.wbsite.module.admin.mgr.MappingManager;
import xyz.wbsite.module.admin.req.LoginRequest;
import xyz.wbsite.module.admin.req.MappingCreateRequest;
import xyz.wbsite.module.admin.req.MappingDeleteRequest;
import xyz.wbsite.module.admin.req.MappingFindRequest;
import xyz.wbsite.module.admin.req.MappingUpdateRequest;
import xyz.wbsite.module.admin.rsp.LoginResponse;
import xyz.wbsite.module.admin.rsp.MappingFindResponse;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import xyz.wbsite.wsqlite.ObjectClient;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Controller
public class AjaxController {
@Autowired
private MappingManager mappingManager;
@Autowired
private NginxCtrl nginxCtrl;
@Autowired
private ObjectClient objectClient;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
@Value("${admin.username}")
private String username;
@Value("${admin.password}")
private String password;
@RequestMapping("/ajax")
@ResponseBody
public BaseResponse ajax(@RequestParam("method") String method, HttpServletRequest request, HttpServletResponse response) {
BaseResponse baseResponse = new BaseResponse();
String jsonString = null;
try {
if (method == null) {
baseResponse.addError(new Error(ErrorType.BUSINESS_ERROR, "请求方法不能为空!"));
return baseResponse;
}
Token token = LocalData.getToken();
if (token == null) {
token = LocalData.getTempToken();
}
if (!token.hasResource(method)) {
baseResponse.addError(new Error(ErrorType.BUSINESS_ERROR, "无权调用该接口!"));
return baseResponse;
}
InputStreamReader isr = new InputStreamReader(request.getInputStream(), "UTF-8");
BufferedReader in = new BufferedReader(isr);
jsonString = in.readLine();
switch (method) {
case "ajax.login":
baseResponse = login(jsonString, token);
break;
case "nginx.start":
baseResponse = nginxStart(jsonString, token);
break;
case "nginx.stop":
baseResponse = nginxStop(jsonString, token);
break;
case "nginx.reload":
baseResponse = nginxReload(jsonString, token);
break;
case "ajax.admin.mapping.find":
baseResponse = findMapping(jsonString, token);
break;
// 创建映射
case "ajax.admin.mapping.create":
baseResponse = createMapping(jsonString, token);
flushConfig();
break;
// 删除映射
case "ajax.admin.mapping.delete":
baseResponse = deleteMapping(jsonString, token);
flushConfig();
break;
// 修改映射
case "ajax.admin.mapping.update":
baseResponse = updateMapping(jsonString, token);
flushConfig();
break;
case "ajax.admin.config.flush":
flushConfig();
baseResponse = new BaseResponse();
break;
default:
baseResponse.addError(ErrorType.INVALID_PARAMETER, Message.NOT_EXIST_METHOD);
break;
}
} catch (Exception ex) {
baseResponse.addError(ErrorType.SYSTEM_ERROR, Message.ERROR_500);
LogUtil.dumpException(ex);
} finally {
if (baseResponse.hasError()) {
LogUtil.e("请求方法" + method + ", 请求参数:" + jsonString);
LogUtil.e("返回结果包含异常" + MapperUtil.toJson(baseResponse));
}
}
return baseResponse;
}
private BaseResponse login(String jsonString, Token token) {
LoginRequest loginRequest = MapperUtil.toJava(jsonString, LoginRequest.class);
LoginResponse loginResponse = new LoginResponse();
ValidationUtil.validate(loginRequest, loginResponse);
if (loginResponse.hasError()) {
return loginResponse;
}
if (!loginRequest.getUsername().equals(username)) {
loginResponse.addError(ErrorType.BUSINESS_ERROR, "用户不存在!");
return loginResponse;
}
if (!loginRequest.getPassword().equals(password)) {
loginResponse.addError(ErrorType.BUSINESS_ERROR, "密码错误!");
return loginResponse;
}
String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());
String encode = MD5Util.encode(yyyyMMdd + username + password);
LocalData.getResponse().addCookie(new Cookie("token", encode));
return loginResponse;
}
private BaseResponse nginxStart(String jsonString, Token token) {
BaseResponse baseResponse = new BaseResponse();
if (nginxCtrl.isRunning()) {
baseResponse.addError(ErrorType.BUSINESS_ERROR, "程序已经运行");
return baseResponse;
}
ProcessUtil.execBat(nginxCtrl.getStartCmd());
return baseResponse;
}
private BaseResponse nginxStop(String jsonString, Token token) {
BaseResponse baseResponse = new BaseResponse();
if (!nginxCtrl.isRunning()) {
baseResponse.addError(ErrorType.BUSINESS_ERROR, "程序尚未运行");
return baseResponse;
}
ProcessUtil.execBat(nginxCtrl.getStopCmd());
return baseResponse;
}
private synchronized BaseResponse nginxReload(String jsonString, Token token) {
BaseResponse baseResponse = new BaseResponse();
if (!nginxCtrl.isRunning()) {
baseResponse.addError(ErrorType.BUSINESS_ERROR, "程序尚未运行");
return baseResponse;
}
// 刷新配置文件
flushConfig();
// 重新加载配置文件
ProcessUtil.execBat(nginxCtrl.getReloadCmd());
return baseResponse;
}
/**
*
*/
private BaseResponse createMapping(String jsonString, Token token) {
MappingCreateRequest request = MapperUtil.toJava(jsonString, MappingCreateRequest.class);
return mappingManager.create(request, token);
}
/**
*
*/
private BaseResponse deleteMapping(String jsonString, Token token) {
MappingDeleteRequest request = MapperUtil.toJava(jsonString, MappingDeleteRequest.class);
return mappingManager.delete(request, token);
}
/**
*
*/
private BaseResponse updateMapping(String jsonString, Token token) {
MappingUpdateRequest request = MapperUtil.toJava(jsonString, MappingUpdateRequest.class);
return mappingManager.update(request, token);
}
/**
*
*/
private BaseResponse findMapping(String jsonString, Token token) {
MappingFindRequest request = MapperUtil.toJava(jsonString, MappingFindRequest.class);
return mappingManager.find(request, token);
}
private synchronized void flushConfig() {
Writer wr = null;
try {
File config = nginxCtrl.getConfig();
HashMap<String, Object> context = new HashMap<>();
MappingFindRequest mappingFindRequest = new MappingFindRequest();
mappingFindRequest.setPageSize(0);
mappingFindRequest.setSortKey("SERVICE_PORT");
MappingFindResponse mappingFindResponse = mappingManager.find(mappingFindRequest, LocalData.getSysToken());
Map<String, List<Mapping>> services = new HashMap<>();
for (Mapping mapping : mappingFindResponse.getResult()) {
List<Mapping> mappings = services.get(mapping.getServicePort());
if (mappings == null) {
mappings = new ArrayList<>();
services.put(mapping.getServicePort(), mappings);
}
mappings.add(mapping);
}
context.put("services", services);
Template template = freeMarkerConfigurer.getConfiguration().getTemplate("nginx.conf.ftl");
wr = new OutputStreamWriter(new FileOutputStream(config), "UTF-8");
//写入
template.process(context, wr);
//关闭流
wr.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} finally {
try {
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

@ -1,454 +0,0 @@
package xyz.wbsite.action;
import com.fasterxml.jackson.core.TreeNode;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import xyz.wbsite.config.ActionConfig;
import xyz.wbsite.frame.base.BaseRequest;
import xyz.wbsite.frame.base.BaseResponse;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.base.Screen;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.frame.utils.AESUtil;
import xyz.wbsite.frame.utils.LocalData;
import xyz.wbsite.frame.utils.LogUtil;
import xyz.wbsite.frame.utils.MD5Util;
import xyz.wbsite.frame.utils.MapperUtil;
import xyz.wbsite.frame.utils.RequestUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Locale;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ControllerController
* htm{@link GlobalController#action(Model, HttpServletRequest, HttpServletResponse)}
* ajax{@link GlobalController#ajax(String, String, String, HttpServletRequest, HttpServletResponse, String, MultipartFile)}
* {@link GlobalController#exceptionHandler(HttpServletRequest, HttpServletResponse, Model, Exception)}
* {@link GlobalController#sse(String)}
* <p>
* Request
* Api#Example#Request ==> ##Request
*
* @author author
* @version 0.0.1
* @since 2017-01-01
*/
@Controller
@ControllerAdvice
public class GlobalController implements ErrorController {
@Value("${r'${server.servlet.context-path}'}")
private String context;
@Value("${r'${web.home.page}'}")
private String homePage;
@Value("${r'${web.login.page}'}")
private String loginPage;
@Autowired
private FreeMarkerViewResolver viewResolver;
/**
*
*
* @param request
* @param response
* @param exception
* @return
*/
@ExceptionHandler(Exception.class)
public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Model model, Exception exception) {
StringBuffer msg = new StringBuffer("");
if (exception != null) {
msg = new StringBuffer("");
String message = exception.toString();
int length = exception.getStackTrace().length;
if (length > 0) {
msg.append("<a>").append(message).append("</a><br>");
for (int i = 0; i < length; i++) {
msg.append("<a>").append(exception.getStackTrace()[i]).append("</a><br>");
}
} else {
msg.append(message);
}
}
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
model.addAttribute("msg", msg.toString());
return "500";
}
private final static String ERROR_PATH = "/error";
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@RequestMapping(value = ERROR_PATH)
public String error(HttpServletRequest request, HttpServletResponse response) {
switch (response.getStatus()) {
case 404:
return "404";
case 403:
String errorUrl = RequestUtil.getErrorUrl(request);
errorUrl = errorUrl.replaceFirst(context, "");
if ((errorUrl.equals(homePage) || errorUrl.equals("/")) && LocalData.getToken() == null) {
try {
response.sendRedirect(context + loginPage);
} catch (IOException e) {
e.printStackTrace();
}
}
return "403";
case 500:
return "500";
default:
return "403";
}
}
@RequestMapping("/")
public String home() {
Token token = LocalData.getToken();
if (token == null) {
return "redirect:" + loginPage;
} else {
return "redirect:" + homePage;
}
}
/**
* layoutscreen
* 使layoutViewNameTranslator
*
* @param model
* @param request
*/
@RequestMapping({"/**/*.htm"})
public String action(Model model, HttpServletRequest request, HttpServletResponse response) {
String servletPath = request.getServletPath();// /**/*.htm
String layout = "/layout/default";
String action = LocalData.getAction();// **/*
Pattern compile = Pattern.compile("^/(.+)\\.htm");
Matcher matcher = compile.matcher(servletPath);
if (matcher.find()) {
action = matcher.group(1);
LocalData.setAction(action);
}
try {
LocaleResolver localeResolver = (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
Locale locale = localeResolver.resolveLocale(request);
{//查询screen
String[] split = action.split("/");
StringBuilder sb = new StringBuilder("");
sb.append("screen");
for (int i = 0; i < split.length; i++) {
sb.append(File.separator);
sb.append(split[i]);
}
layout = sb.toString();
View view = viewResolver.resolveViewName(layout, locale);
if (view == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "");
return null;
}
// 尝试执行Screen执行器(服务器渲染),并返回视图模板
try {
String beanClassName = (ActionConfig.SCREEN_PREFIX + action).toLowerCase();
Screen screenExec = LocalData.getApplicationContext().getBean(beanClassName, Screen.class);
screenExec.exec(model, request, response);
if (response.getStatus() != HttpServletResponse.SC_OK) {
response.sendError(response.getStatus(), "");
return null;
}
} catch (BeansException e) {
}
}
{//查找layout
String[] split = action.split("/");
int lt = split.length;
while (lt > 0) {
StringBuilder sb = new StringBuilder("");
sb.append("layout");
for (int i = 0; i < lt - 1; i++) {
sb.append(File.separator);
sb.append(split[i]);
}
layout = sb.toString() + File.separator + split[split.length - 1];
View view = viewResolver.resolveViewName(layout, locale);
//无法找到对应layout使用默认layout
if (view == null) {
layout = sb.toString() + File.separator + "default";
View defaultView = viewResolver.resolveViewName(layout, locale);
if (null == defaultView && lt == 1) {
System.err.println("can not find layout/default.ftl");
} else if (null == defaultView) {
lt--;
} else {
break;
}
} else {
break;
}
}
}
} catch (Exception e) {
return exceptionHandler(request, response, model, e);
}
// todo 可在此获取共性数据(也可以在全局拦截器GlobalHandlerInterceptor、拦截器作用域比此更高)
// todo 例如用户信息等。其他业务数据在页面渲染后通过Ajax请求
return layout;
}
@RequestMapping("/ajax/{module}/{target}/{method}")
@ResponseBody
public Object ajax(
@PathVariable String module,
@PathVariable String target,
@PathVariable String method,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
@RequestBody(required = false) String data,
@RequestParam(name = "file", required = false) MultipartFile file) {
try {
String beanClassName = (ActionConfig.AJAX_PREFIX + module + "/" + target).toLowerCase();
Object ajax = LocalData.getApplicationContext().getBean(beanClassName);
Class ajaxClass = ajax.getClass();
Method[] methods = ajaxClass.getDeclaredMethods();
Method methodC = null;
for (Method meth : methods) {
if (meth.getName().equals(method)) {
methodC = meth;
}
}
if (methodC == null) {
BaseResponse baseResponse = new BaseResponse();
baseResponse.addError(ErrorType.BUSINESS_ERROR, "未找到对应的方法!");
return baseResponse;
}
Parameter[] parameters = methodC.getParameters();
Object[] arg = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
if (parameter.getType() == HttpServletRequest.class) {
arg[i] = httpServletRequest;
} else if (parameter.getType() == HttpServletResponse.class) {
arg[i] = httpServletResponse;
} else if (parameter.getType() == TreeNode.class) {
arg[i] = MapperUtil.toTree(data);
} else if (parameter.getType() == String.class) {
arg[i] = data;
} else if (parameter.getType() == MultipartFile.class) {
arg[i] = file;
} else if (BaseRequest.class.isAssignableFrom(parameter.getType())) {
arg[i] = MapperUtil.toJava(data, parameter.getType());
} else if (parameter.getType() == Token.class) {
arg[i] = LocalData.getToken();
} else {
arg[i] = null;
}
}
return methodC.invoke(ajax, arg);
} catch (BeansException e) {
e.printStackTrace();
BaseResponse baseResponse = new BaseResponse();
baseResponse.addError(ErrorType.BUSINESS_ERROR, "未找到对应的目标!");
return baseResponse;
} catch (IllegalAccessException e) {
e.printStackTrace();
BaseResponse baseResponse = new BaseResponse();
baseResponse.addError(ErrorType.BUSINESS_ERROR, "方法执必须公开!");
return baseResponse;
} catch (InvocationTargetException e) {
e.getTargetException().printStackTrace();
BaseResponse baseResponse = new BaseResponse();
baseResponse.addError(ErrorType.BUSINESS_ERROR, "方法执行错误[" + e.getTargetException().getMessage() + "]");
return baseResponse;
}
}
@RequestMapping(path = "/api/{module}/{target}/{method}", method = RequestMethod.POST)
@ResponseBody
public String api(
@PathVariable String module,
@PathVariable String target,
@PathVariable String method,
@RequestParam(required = false) String appKey,
@RequestParam(required = false) String sign,
@RequestParam(required = false) Long timestamp,
@RequestParam(required = false) String token,
@RequestParam(required = false) String encryptData,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
BaseResponse response = new BaseResponse();
if (appKey == null) {
response.addError(ErrorType.BUSINESS_ERROR, "应用码参数[appKey]不存在!");
return MapperUtil.toJson(response);
} else if (sign == null) {
response.addError(ErrorType.BUSINESS_ERROR, "签名参数[sign]不存在!");
return MapperUtil.toJson(response);
} else if (timestamp == null) {
response.addError(ErrorType.BUSINESS_ERROR, "时间戳参数[timestamp]不存在!");
return MapperUtil.toJson(response);
}
String data = null;
String appSecret = "1234567890123456";
// 解码
try {
data = AESUtil.decrypt2String(encryptData, appSecret);
} catch (Exception e) {
response.addError(ErrorType.BUSINESS_ERROR, "解码失败,请确认编码是否正确!");
return MapperUtil.toJson(response);
}
// 验证签名
String sign_ = MD5Util.encode(appSecret + data + timestamp);
if (!sign_.equals(sign)) {
response.addError(ErrorType.BUSINESS_ERROR, "签名验证失败!");
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
// 时效性验证
long currentTime = System.currentTimeMillis();
if (currentTime - timestamp > 2 * 60 * 1000) {
response.addError(ErrorType.BUSINESS_ERROR, "请求过期, 或本地时间错误!");
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
// 权限验证
if (!LocalData.getToken().hasRes(httpServletRequest.getServletPath())) {
response.addError(ErrorType.BUSINESS_ERROR, "[" + httpServletRequest.getServletPath() + "]未授权的资源!");
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
// 开始处理业务
try {
String beanClassName = (ActionConfig.API_PREFIX + module + "/" + target).toLowerCase();
Object ajax = LocalData.getApplicationContext().getBean(beanClassName);
Class ajaxClass = ajax.getClass();
Method[] methods = ajaxClass.getDeclaredMethods();
Method methodC = null;
for (Method meth : methods) {
if (meth.getName().equals(method)) {
methodC = meth;
}
}
if (methodC == null) {
response.addError(ErrorType.BUSINESS_ERROR, "未找到对应的方法!");
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
Parameter[] parameters = methodC.getParameters();
Object[] arg = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
if (parameter.getType() == HttpServletRequest.class) {
arg[i] = httpServletRequest;
} else if (parameter.getType() == HttpServletResponse.class) {
arg[i] = httpServletResponse;
} else if (BaseRequest.class.isAssignableFrom(parameter.getType())) {
arg[i] = MapperUtil.toJava(data, parameter.getType());
} else if (parameter.getType() == TreeNode.class) {
arg[i] = MapperUtil.toTree(data);
} else if (parameter.getType() == Token.class) {
arg[i] = LocalData.getToken();
} else {
arg[i] = null;
}
}
response = (BaseResponse) methodC.invoke(ajax, arg);
} catch (BeansException e) {
e.printStackTrace();
response.addError(ErrorType.BUSINESS_ERROR, "未找到对应的目标!");
} catch (IllegalAccessException e) {
e.printStackTrace();
response.addError(ErrorType.BUSINESS_ERROR, "方法执必须公开!");
} catch (InvocationTargetException e) {
LogUtil.dumpException(e.getTargetException());
e.getTargetException().printStackTrace();
response.addError(ErrorType.BUSINESS_ERROR, "方法执行错误[" + e.getTargetException().getMessage() + "]");
}
return AESUtil.encrypt2Base64(MapperUtil.toJson(response).getBytes(), appSecret);
}
private static ConcurrentHashMap<String, SseEmitter> sseMap = new ConcurrentHashMap();
/**
* Ssejs
* Sse{@link GlobalController#sseMap}
* Sse{@link GlobalController#pushAll}
*/
@RequestMapping(value = "/sse/{userId}", produces = "text/event-stream;charset=UTF-8")
public SseEmitter sse(@PathVariable String userId) {
SseEmitter sseEmitter = new SseEmitter(10000000L);
if (sseMap.get(userId) != null) {
sseMap.remove(userId);
}
sseMap.put(userId, sseEmitter);
return sseEmitter;
}
/**
* Sse
*
* @param data
*/
public static void pushAll(Object data) {
for (String s : sseMap.keySet()) {
try {
sseMap.get(s).send(MapperUtil.toJson(data), MediaType.APPLICATION_JSON);
} catch (IOException e) {
sseMap.remove(s);
}
}
}
}

@ -1,21 +0,0 @@
package xyz.wbsite.action.ajax;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import xyz.wbsite.frame.base.BaseResponse;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.utils.LogUtil;
import xyz.wbsite.frame.utils.MapperUtil;
import xyz.wbsite.frame.utils.ValidationUtil;
import xyz.wbsite.module.admin.mgr.MappingManager;
import java.io.IOException;
import java.util.List;
public class MappingAjax {
@Autowired
private MappingManager mappingManager;
}

@ -1,15 +0,0 @@
package xyz.wbsite.action.control;
import xyz.wbsite.frame.base.Control;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Footer extends Control {
@Override
public void exec(Model model, HttpServletRequest request, HttpServletResponse response) {
}
}

@ -1,15 +0,0 @@
package xyz.wbsite.action.control;
import xyz.wbsite.frame.base.Control;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Header extends Control {
@Override
public void exec(Model model, HttpServletRequest request, HttpServletResponse response) {
}
}

@ -1,23 +0,0 @@
package xyz.wbsite.action.screen;
import xyz.wbsite.frame.base.Screen;
import org.springframework.ui.Model;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Index extends Screen {
@Override
public void exec(Model model, HttpServletRequest request, HttpServletResponse response) {
model.addAttribute("hello", "Hello world!!!");
model.addAttribute("status", 0);
ArrayList<String> citys = new ArrayList();
citys.add("北京");
citys.add("上海");
citys.add("深圳");
model.addAttribute("citys", citys);
}
}

@ -1,139 +0,0 @@
package xyz.wbsite.config;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.core.type.filter.TypeFilter;
import xyz.wbsite.frame.base.Control;
import xyz.wbsite.frame.base.Screen;
import xyz.wbsite.frame.utils.LogUtil;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ScreenControl
* <p>
* Screen {@link ActionConfig#registryScreen}
* Control {@link ActionConfig#registryControl}
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Configuration
public class ActionConfig implements BeanDefinitionRegistryPostProcessor {
public static String SCREEN_PREFIX = "/screen/";
public static String CONTROL_PREFIX = "/control/";
public static String AJAX_PREFIX = "/ajax/";
public static String API_PREFIX = "/api/";
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
String aPackage = this.getClass().getPackage().getName();
Pattern compile = Pattern.compile("(.*)\\.config");
Matcher matcher = compile.matcher(aPackage);
if (matcher.find()) {
String basePackage = matcher.group(1);
registryScreen(basePackage + ".action.screen", beanDefinitionRegistry);
registryControl(basePackage + ".action.control", beanDefinitionRegistry);
registryAjax(basePackage + ".action.ajax", beanDefinitionRegistry);
registryApi(basePackage + ".action.api", beanDefinitionRegistry);
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
}
private int registryScreen(String basePackage, BeanDefinitionRegistry beanDefinitionRegistry) {
ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry);
classPathBeanDefinitionScanner.resetFilters(false);
classPathBeanDefinitionScanner.addIncludeFilter(new AssignableTypeFilter(Screen.class));
classPathBeanDefinitionScanner.setBeanNameGenerator(new BeanNameGenerator() {
@Override
public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
String beanClassName = beanDefinition.getBeanClassName();
String beamName = beanClassName.replaceAll(basePackage + ".", SCREEN_PREFIX).replaceAll("\\.","/").toLowerCase();
LogUtil.i("registry screen " + beamName);
return beamName;
}
});
return classPathBeanDefinitionScanner.scan(basePackage);
}
private int registryControl(String basePackage, BeanDefinitionRegistry beanDefinitionRegistry) {
ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry);
classPathBeanDefinitionScanner.resetFilters(false);
classPathBeanDefinitionScanner.addIncludeFilter(new AssignableTypeFilter(Control.class));
classPathBeanDefinitionScanner.setBeanNameGenerator(new BeanNameGenerator() {
@Override
public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
String beanClassName = beanDefinition.getBeanClassName();
String beamName = beanClassName.replaceAll(basePackage + ".", CONTROL_PREFIX).replaceAll("\\.","/").toLowerCase();
LogUtil.i("registry control " + beamName);
return beamName;
}
});
return classPathBeanDefinitionScanner.scan(basePackage);
}
private int registryAjax(String basePackage, BeanDefinitionRegistry beanDefinitionRegistry) {
ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry);
classPathBeanDefinitionScanner.resetFilters(false);
classPathBeanDefinitionScanner.addIncludeFilter(new TypeFilter() {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
return true;
}
});
classPathBeanDefinitionScanner.setBeanNameGenerator(new BeanNameGenerator() {
@Override
public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null && beanClassName.endsWith("Ajax")) {
beanClassName = beanClassName.substring(0, beanClassName.length() - 4);
}
String beamName = beanClassName.replaceAll(basePackage + ".", AJAX_PREFIX).replaceAll("\\.","/").toLowerCase();
LogUtil.i("registry ajax " + beamName);
return beamName;
}
});
return classPathBeanDefinitionScanner.scan(basePackage);
}
private int registryApi(String basePackage, BeanDefinitionRegistry beanDefinitionRegistry) {
ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(beanDefinitionRegistry);
classPathBeanDefinitionScanner.addIncludeFilter(new TypeFilter() {
@Override
public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
return true;
}
});
classPathBeanDefinitionScanner.setBeanNameGenerator(new BeanNameGenerator() {
@Override
public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null && beanClassName.endsWith("Api")) {
beanClassName = beanClassName.substring(0, beanClassName.length() - 3);
}
String beamName = beanClassName.replaceAll(basePackage + ".", API_PREFIX).replaceAll("\\.","/").toLowerCase();
LogUtil.i("registry api " + beamName);
return beamName;
}
});
return classPathBeanDefinitionScanner.scan(basePackage);
}
}

@ -1,114 +0,0 @@
package xyz.wbsite.config;
import xyz.wbsite.frame.utils.MD5Util;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.frame.utils.CookieUtil;
import xyz.wbsite.frame.utils.LocalData;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${web.url.auth.excluded}")
private String[] excluded;
@Value("${spring.mvc.static-path-pattern}")
private String[] staticPath;
@Value("${admin.username}")
private String username;
@Value("${admin.password}")
private String password;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(staticPath).permitAll()
.antMatchers(excluded).permitAll()
.anyRequest().access("@Authorization.hasPermission(request,authentication)")
.and().cors()
.and().headers().frameOptions().disable()
.and().csrf().disable();
}
/**
*
* <p>
* Using generated security password: f6b42a66-71b1-4c31-b6a8-942838c81408
*
* @return
* @throws Exception
*/
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean("Authorization")
public Object getAuthorization() {
return new Object() {
public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
// 获取Token
String token = request.getParameter("token");
if (token == null || token.isEmpty()) {
token = CookieUtil.getCookieValue(request.getCookies(), "token");
}
String yyyyMMdd = new SimpleDateFormat("yyyyMMdd").format(new Date());
String encode = MD5Util.encode(yyyyMMdd + username + password);
if (token == null) {
LocalData.setToken(LocalData.getTempToken());
} else if (!encode.equals(token)) {
LocalData.setToken(LocalData.getTempToken());
} else {
Token token1 = new Token();
token1.setId(1L);
token1.setUserId(1L);
token1.setUserName(username);
token1.putResource("/");
token1.putResource("/mapping.htm");
token1.putResource("/sse/.*");
token1.putResource("/ajax");
token1.putResource("ajax.login");
token1.putResource("nginx.start");
token1.putResource("nginx.stop");
token1.putResource("nginx.reload");
token1.putResource("ajax.admin.mapping.find");
token1.putResource("ajax.admin.mapping.create");
token1.putResource("ajax.admin.mapping.delete");
token1.putResource("ajax.admin.mapping.update");
token1.putResource("ajax.admin.config.flush");
LocalData.setToken(token1);
}
String servletPath = request.getServletPath();
// 授权
Token token_ = LocalData.getToken();
if (token_.hasResource(request.getServletPath())) {
return true;
}
// try {
// LocalData.getResponse().sendRedirect("/login.htm");
// } catch (IOException e) {
// e.printStackTrace();
// }
return false;
}
};
}
}

@ -1,46 +0,0 @@
package xyz.wbsite.config;
import xyz.wbsite.module.admin.ent.Mapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import xyz.wbsite.wsqlite.ObjectClient;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
@Configuration
public class SqliteConfig {
@Autowired
public Environment environment;
@Bean
public ObjectClient registry() {
try {
String dbpath = environment.getProperty("dbpath");
if (StringUtils.isEmpty(dbpath)) {
ApplicationHome home = new ApplicationHome(getClass());
// 当前运行jar文件
File jarFile = home.getSource() != null ? home.getSource() : home.getDir();
//jar同目录
dbpath = jarFile.getParent();
}
ArrayList<Class> objects = new ArrayList<>();
objects.add(Mapping.class);
ObjectClient objectClient = new ObjectClient(new File(dbpath, "data.db"), objects);
return objectClient;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}

@ -1,51 +0,0 @@
package xyz.wbsite.config;
import xyz.wbsite.action.GlobalController;
import xyz.wbsite.frame.base.Message;
import xyz.wbsite.frame.base.MessageType;
import xyz.wbsite.module.admin.ent.NginxCtrl;
import xyz.wbsite.module.admin.ent.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executors;
/**
* Task,Task
* :@Profile("dev") () @Profile("prod")()
*/
@Configuration
@EnableScheduling
//@Profile("prod")
public class TaskConfig implements SchedulingConfigurer {
@Autowired
private GlobalController globalController;
@Autowired
private NginxCtrl nginxCtrl;
@Scheduled(cron = "0/3 * * * * ? ")
public void task() {
Message message = new Message();
message.setType(MessageType.NGINX_STATE);
State state = new State();
state.setRun(nginxCtrl.isRunning());
message.setObject(state);
globalController.pushAll(message);
}
/**
* Spring Schedule 线
* 线 SchedulingConfigurerconfigureTasks
*
* @param scheduledTaskRegistrar
*/
@Override
public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
scheduledTaskRegistrar.setScheduler(Executors.newScheduledThreadPool(3));
}
}

@ -1,56 +0,0 @@
package xyz.wbsite.config;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class ThreadPoolConfig implements AsyncConfigurer {
private ThreadPoolTaskExecutor executor;
private int corePoolSize = 10;//线程池维护线程的最少数量
private int maxPoolSize = 30;//线程池维护线程的最大数量
private int queueCapacity = 8; //缓存队列
private int keepAlive = 60;//允许的空闲时间
@Nullable
@Override
public Executor getAsyncExecutor() {
executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix("mqExecutor-");
// rejection-policy当pool已经达到max size的时候如何处理新任务
// CALLER_RUNS不在新线程中执行任务而是由调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); //对拒绝task的处理策略
executor.setKeepAliveSeconds(keepAlive);
executor.initialize();
return executor;
}
@Nullable
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
System.out.println("-------------》》》捕获线程异常信息");
}
};
}
}

@ -1,159 +0,0 @@
package xyz.wbsite.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.frame.utils.LocalData;
import xyz.wbsite.frame.utils.LogUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Value("${web.welcome.page}")
private String homePage;
/**
*
*
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptorAdapter() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 处理根Url
String servletPath = request.getServletPath();
if (servletPath.matches("(.+)\\.htm")) {
Pattern compile = Pattern.compile("(.+)\\.htm");
Matcher matcher = compile.matcher(servletPath);
if (matcher.find()) {
servletPath = matcher.group(1);
}
}
LocalData.setTarget(servletPath);
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
//当请求为@ResponseBodymodelAndView为null,不处理
if (modelAndView == null) {
return;
}
//获取当前用户信息
Token token = LocalData.getToken();
modelAndView.addObject("token", token);
//主页
modelAndView.addObject("homePath", homePage);
//获取项目路径,在项目非根路径下用于拼接URL
String contextPath = request.getContextPath();
modelAndView.addObject("contextPath", contextPath);
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
super.afterCompletion(request, response, handler, ex);
if (ex != null) {
LogUtil.dumpException(ex);
}
}
}).addPathPatterns("/**/*.htm").order(-1);
}
/**
* Jackson
*
* 1LonglongStringjavascriptNumber
*
* @param converters
*/
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingJackson2HttpMessageConverter){
ObjectMapper objectMapper = ((MappingJackson2HttpMessageConverter)converter).getObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
objectMapper.registerModule(simpleModule);
}
}
}
// @Bean
// @Profile("prod")
// public ServletWebServerFactory servletContainer() {
// TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
//
// // 基本参数
// String keyStore = "1754557_www.wbsite.xyz.pfx";
// String keyStorePassword = "s98n7CLd";
// String keyStoreType = "PKCS12";
// int httpsPort = 443;
//
// File keystore = null;
// // 正常开发可以通过getFile()获取打包jar后无法直接获取File对象需将文件考出
// try {
// keystore = new ClassPathResource(keyStore).getFile();
// } catch (IOException ex) {
// try {
// ApplicationHome home = new ApplicationHome(getClass());
// // 当前运行jar文件
// File jarFile = home.getSource();
// //jar同目录
// keystore = new File(jarFile.getParent(), keyStore);
//
// InputStream inputStream = new ClassPathResource(keyStore).getInputStream();
// byte[] bytes = new byte[inputStream.available()];
//
// inputStream.read(bytes);
//
// inputStream.close();
//
// FileOutputStream fileOutputStream = new FileOutputStream(keystore);
// fileOutputStream.write(bytes);
// fileOutputStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// // 创建Connector
// Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
// Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
// connector.setScheme("https");
// connector.setSecure(true);
// connector.setPort(httpsPort);
// protocol.setSSLEnabled(true);
// protocol.setKeystoreFile(keystore.getAbsolutePath());
// protocol.setKeystorePass(keyStorePassword);
// protocol.setKeystoreType(keyStoreType);
//
// // 添加
// tomcat.addAdditionalTomcatConnectors(connector);
// return tomcat;
// }
}

@ -1,99 +0,0 @@
package xyz.wbsite.frame.base;
import com.fasterxml.jackson.annotation.JsonIgnore;
import java.io.Serializable;
import java.util.Date;
/**
* Base -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseEntity implements Serializable {
/**
*
*/
private long rowVersion;
/**
*
*/
@JsonIgnore
private long createBy;
/**
*
*/
@JsonIgnore
private Date createTime;
/**
*
*/
@JsonIgnore
private long lastUpdateBy;
/**
*
*/
@JsonIgnore
private Date lastUpdateTime;
/**
*
*/
@JsonIgnore
private boolean isDeleted;
public boolean getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
public long getRowVersion() {
return rowVersion;
}
public void setRowVersion(long rowVersion) {
this.rowVersion = rowVersion;
}
public long getCreateBy() {
return createBy;
}
public void setCreateBy(long createBy) {
this.createBy = createBy;
}
public long getLastUpdateBy() {
return lastUpdateBy;
}
public void setLastUpdateBy(long lastUpdateBy) {
this.lastUpdateBy = lastUpdateBy;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
}

@ -1,29 +0,0 @@
package xyz.wbsite.frame.base;
/**
* BaseFindRequest -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseFindRequest extends BaseGetAllRequest {
private int pageNumber = 1;
private int pageSize = 10;
public int getPageNumber() {
return pageNumber;
}
public void setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}

@ -1,33 +0,0 @@
package xyz.wbsite.frame.base;
import java.util.List;
/**
* BaseFindResponse -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseFindResponse<T> extends BaseResponse{
private List<T> result;
private Long totalCount;
public List<T> getResult() {
return result;
}
public void setResult(List<T> result) {
this.result = result;
}
public Long getTotalCount() {
return totalCount;
}
public void setTotalCount(Long totalCount) {
this.totalCount = totalCount;
}
}

@ -1,32 +0,0 @@
package xyz.wbsite.frame.base;
/**
* BaseFindRequest -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseGetAllRequest extends BaseRequest {
private String sortKey;
private SortType sortType;
public String getSortKey() {
return sortKey;
}
public void setSortKey(String sortKey) {
this.sortKey = sortKey;
}
public SortType getSortType() {
return sortType;
}
public void setSortType(SortType sortType) {
this.sortType = sortType;
}
}

@ -1,12 +0,0 @@
package xyz.wbsite.frame.base;
/**
* BaseRequest -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseRequest {
}

@ -1,38 +0,0 @@
package xyz.wbsite.frame.base;
import java.util.ArrayList;
import java.util.List;
/**
* BaseResponse -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseResponse {
private List<Error> errors = new ArrayList();
public void addError(Error error){
this.errors.add(error);
}
public void addError(ErrorType type,String message){
this.errors.add(new Error(type,message));
}
public void addErrors(List<Error> errors){
this.errors.addAll(errors);
}
public boolean hasError(){
return this.errors.size() > 0;
}
/**
*
*/
public List<Error> getErrors() {
return new ArrayList<Error>(errors);
}
}

@ -1,24 +0,0 @@
package xyz.wbsite.frame.base;
/**
* BaseSearchRequest -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseSearchRequest extends BaseFindRequest {
/**
*
*/
private String keyword;
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
}

@ -1,24 +0,0 @@
package xyz.wbsite.frame.base;
/**
* BaseUpdateRequest -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class BaseUpdateRequest extends BaseRequest{
/**
*
*/
private long rowVersion;
public long getRowVersion() {
return rowVersion;
}
public void setRowVersion(long rowVersion) {
this.rowVersion = rowVersion;
}
}

@ -1,10 +0,0 @@
package xyz.wbsite.frame.base;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Control {
public abstract void exec(Model model, HttpServletRequest request, HttpServletResponse response);
}

@ -1,41 +0,0 @@
package xyz.wbsite.frame.base;
/**
* Error -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class Error {
/*错误类型*/
private ErrorType type;
/*错误内容*/
private String message;
public Error() {
}
public Error(ErrorType type, String message) {
this.type = type;
this.message = message;
}
public ErrorType getType() {
return type;
}
public void setType(ErrorType type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

@ -1,17 +0,0 @@
package xyz.wbsite.frame.base;
/**
* ErrorType -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public enum ErrorType {
BUSINESS_ERROR,
SYSTEM_ERROR,
UNKNOWN_ERROR,
UNIQUENESS_ERROR,
EXPECTATION_NULL,
INVALID_PARAMETER
}

@ -1,34 +0,0 @@
package xyz.wbsite.frame.base;
public class FileUploadResponse extends BaseResponse {
private Long id;
private String url;
private String downloadUrl;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
}

@ -1,10 +0,0 @@
package xyz.wbsite.frame.base;
import org.springframework.ui.Model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Screen {
public abstract void exec(Model model, HttpServletRequest request, HttpServletResponse response);
}

@ -1,17 +0,0 @@
package xyz.wbsite.frame.base;
/**
* SortTypeEnum -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public enum SortType {
//升序
ASC,
//降序
DESC
}

@ -1,74 +0,0 @@
package xyz.wbsite.frame.base;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* Token -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class Token implements Serializable {
private static final Long serialVersionUID = 1L;
/** ID */
private long id;
/** 用户ID */
private long userId;
/** 用户名称 */
private String userName;
private Set<String> resourceSet = new HashSet();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public boolean hasResource(String resource){
for (String s : resourceSet) {
if (resource.matches(s)){
return true;
}
}
return false;
}
public void putResource(String resource){
resourceSet.add(resource);
}
public Set<String> getResourceSet() {
return resourceSet;
}
public void addResourceSet(Set<String> resourceSet){
this.resourceSet.addAll(resourceSet);
}
public void addResourceSet(Token token){
addResourceSet(token.getResourceSet());
}
}

@ -1,95 +0,0 @@
package xyz.wbsite.frame.freemarker;
import java.io.File;
import xyz.wbsite.config.ActionConfig;
import freemarker.template.TemplateModelException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.support.BindingAwareModelMap;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
import xyz.wbsite.frame.base.Control;
import xyz.wbsite.frame.utils.LocalData;
/**
*
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Component
public class Layout {
@Autowired
private FreeMarkerViewResolver viewResolver;
private String screenPrefix = "/screen/";
private String controlPrefix = "/control/";
private String suffix = ".ftl";
public String setScreen() throws TemplateModelException {
try {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
LocaleResolver localeResolver = (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
String servletPath = LocalData.getTarget();
servletPath = servletPath.replaceAll("^/", "");
String[] split = servletPath.split("/");
StringBuilder sb = new StringBuilder("");
// 分割组装路径
for (int i = 0; i < split.length; i++) {
sb.append(split[i]);
if (i != split.length - 1) {
sb.append(File.separator);
}
}
Locale locale = localeResolver.resolveLocale(request);
String viewName = "screen" + File.separator + sb.toString();
View view = viewResolver.resolveViewName(viewName, locale);
//无法找到对应screen
if (view == null) {
return "";
} else {
return screenPrefix + servletPath + suffix;
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public String setControl(String control) {
// 查找是否存在对应控制面板执行器
Control controlExec = null;
try {
controlExec = LocalData.getApplicationContext().getBean(ActionConfig.CONTROL_PREFIX + "." + control, Control.class);
HttpServletRequest request = LocalData.getRequest();
HttpServletResponse response = LocalData.getResponse();
BindingAwareModelMap modelMap = new BindingAwareModelMap();
controlExec.exec(modelMap, request, response);
for (String key : modelMap.keySet()) {
request.setAttribute(key, modelMap.get(key));
}
} catch (BeansException e) {
}
control = control.replaceAll("/", File.separator);
return controlPrefix + control + suffix;
}
}

@ -1,41 +0,0 @@
package xyz.wbsite.frame.freemarker;
import freemarker.template.TemplateModelException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
/**
* Url
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Component
public class Uri {
public String getUrl(String path) throws TemplateModelException {
if (path == null) {
return "";
}
if (!path.startsWith("/")) {
return "/" + path;
}
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
// 协议
String scheme = request.getScheme();
// 域名
String serverName = request.getServerName();
// 端口
int serverPort = request.getServerPort();
// 上下文路径
String contextPath = request.getContextPath();
return String.format(Locale.CHINA, "%s://%s:%d%s%s", scheme, serverName, serverPort, contextPath, path);
}
}

@ -1,106 +0,0 @@
package xyz.wbsite.frame.freemarker;
import xyz.wbsite.frame.utils.LocalData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Locale;
import java.util.Map;
/**
* FreemarkerViewName
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@Component("viewNameTranslator")
public class ViewNameTranslator extends DefaultRequestToViewNameTranslator {
@Autowired
private FreeMarkerViewResolver viewResolver;
@Autowired
private Layout layout;
@Autowired
private Uri uri;
@PostConstruct
public void setSharedVariable() {
//设置基本工具类
Map<String, Object> attributesMap = viewResolver.getAttributesMap();
attributesMap.put("Layout", layout);
attributesMap.put("Uri", uri);
}
@Override
public String getViewName(HttpServletRequest request) {
String viewName = "";
try {
LocaleResolver localeResolver = (LocaleResolver) request.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
String servletPath = LocalData.getTarget();
servletPath = servletPath.replaceAll("^/", "");
Locale locale = localeResolver.resolveLocale(request);
{//查询screen
String[] split = servletPath.split("/");
StringBuilder sb = new StringBuilder("");
sb.append("screen");
for (int i = 0; i < split.length; i++) {
sb.append(File.separator);
sb.append(split[i]);
}
viewName = sb.toString();
View view = viewResolver.resolveViewName(viewName, locale);
if (view == null) {
// LogUtil.e("can not find screen.");
// HttpServletResponse response = LocalData.getResponse();
// response.setStatus(HttpStatus.NOT_FOUND.value());
}
}
{//查找layout
String[] split = servletPath.split("/");
int lt = split.length;
while (lt > 0) {
StringBuilder sb = new StringBuilder("");
sb.append("layout");
for (int i = 0; i < lt - 1; i++) {
sb.append(File.separator);
sb.append(split[i]);
}
viewName = sb.toString() + File.separator + split[split.length - 1];
View view = viewResolver.resolveViewName(viewName, locale);
//无法找到对应layout使用默认layout
if (view == null) {
viewName = sb.toString() + File.separator + "default";
View defaultView = viewResolver.resolveViewName(viewName, locale);
if (null == defaultView && lt == 1) {
System.err.println("can not find layout/default.ftl");
} else if (null == defaultView) {
lt--;
} else {
break;
}
} else {
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return viewName;
}
}

@ -1,110 +0,0 @@
package xyz.wbsite.frame.utils;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* AESUtil
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String ALGORITHM_STR = "AES/ECB/PKCS5Padding";
/**
*
*
* @param data
* @param secret
* @return base64
*/
public static byte[] encrypt(byte[] data, String secret) {
try {
if (secret.length() != 16) {
throw new IllegalArgumentException("secret's length is not 16");
}
SecretKeySpec key = new SecretKeySpec(secret.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR); // 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
return cipher.doFinal(data);// 加密
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
*
*
* @param data
* @param secret
* @return base64
*/
public static String encrypt2Base64(byte[] data, String secret) {
byte[] encrypt = encrypt(data, secret);
return Base64Util.encodeToString(encrypt, false);
}
/**
*
*
* @param data
* @param secret
* @return
*/
public static byte[] decrypt(byte[] data, String secret) {
try {
if (secret.length() != 16) {
throw new IllegalArgumentException("secret's length is not 16");
}
SecretKeySpec key = new SecretKeySpec(secret.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM_STR);
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(data);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
public static byte[] decryptBase64(String base64Data, String secret) {
byte[] decode = Base64Util.decode(base64Data);
return decrypt(decode, secret);
}
public static String decrypt2String(String base64Data, String secret) {
byte[] bytes = decryptBase64(base64Data, secret);
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}

@ -1,497 +0,0 @@
package xyz.wbsite.frame.utils;
import java.util.Arrays;
/**
* Base64Util
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class Base64Util {
private static final char[] CA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
private static final int[] IA = new int[256];
static {
Arrays.fill(IA, -1);
for (int i = 0, iS = CA.length; i < iS; i++)
IA[CA[i]] = i;
IA['='] = 0;
}
public final static String encodeToString(byte[] sArr) {
return new String(encodeToChar(sArr, false));
}
public final static char[] encodeToChar(byte[] sArr, boolean lineSep) {
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new char[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
char[] dArr = new char[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen; ) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = CA[(i >>> 18) & 0x3f];
dArr[d++] = CA[(i >>> 12) & 0x3f];
dArr[d++] = CA[(i >>> 6) & 0x3f];
dArr[d++] = CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = CA[i >> 12];
dArr[dLen - 3] = CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? CA[i & 0x3f] : '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
/**
* Encodes a raw byte array into a BASE64 <code>String</code> representation i accordance with RFC 2045.
*
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static String encodeToString(byte[] sArr, boolean lineSep) {
// Reuse char[] since we can't create a String incrementally anyway and StringBuffer/Builder would be slower.
return new String(encodeToChar(sArr, lineSep));
}
/**
* Encodes a raw byte array into a BASE64 <code>byte[]</code> representation i accordance with RFC 2045.
*
* @param sArr The bytes to convert. If <code>null</code> or length 0 an empty array will be returned.
* @param lineSep Optional "\r\n" after 76 characters, unless end of file.<br>
* No line separator will be in breach of RFC 2045 which specifies max 76 per line but will be a
* little faster.
* @return A BASE64 encoded array. Never <code>null</code>.
*/
public final static byte[] encodeToByte(byte[] sArr, boolean lineSep) {
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
int eLen = (sLen / 3) * 3; // Length of even 24-bits.
int cCnt = ((sLen - 1) / 3 + 1) << 2; // Returned character count
int dLen = cCnt + (lineSep ? (cCnt - 1) / 76 << 1 : 0); // Length of returned array
byte[] dArr = new byte[dLen];
// Encode even 24-bits
for (int s = 0, d = 0, cc = 0; s < eLen; ) {
// Copy next three bytes into lower 24 bits of int, paying attension to sign.
int i = (sArr[s++] & 0xff) << 16 | (sArr[s++] & 0xff) << 8 | (sArr[s++] & 0xff);
// Encode the int into four chars
dArr[d++] = (byte) CA[(i >>> 18) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 12) & 0x3f];
dArr[d++] = (byte) CA[(i >>> 6) & 0x3f];
dArr[d++] = (byte) CA[i & 0x3f];
// Add optional line separator
if (lineSep && ++cc == 19 && d < dLen - 2) {
dArr[d++] = '\r';
dArr[d++] = '\n';
cc = 0;
}
}
// Pad and encode last bits if source isn't an even 24 bits.
int left = sLen - eLen; // 0 - 2.
if (left > 0) {
// Prepare the int
int i = ((sArr[eLen] & 0xff) << 10) | (left == 2 ? ((sArr[sLen - 1] & 0xff) << 2) : 0);
// Set last four chars
dArr[dLen - 4] = (byte) CA[i >> 12];
dArr[dLen - 3] = (byte) CA[(i >>> 6) & 0x3f];
dArr[dLen - 2] = left == 2 ? (byte) CA[i & 0x3f] : (byte) '=';
dArr[dLen - 1] = '=';
}
return dArr;
}
public final static byte[] decode(char[] sArr) {
// Check special case
int sLen = sArr != null ? sArr.length : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[i]] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[--i]] <= 0; )
if (sArr[i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[sArr[s++]];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++] = (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/**
* Decodes a BASE64 encoded byte array. All illegal characters will be ignored and can handle both arrays with
* and without line separators.
*
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(byte[] sArr) {
// Check special case
int sLen = sArr.length;
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[sArr[i] & 0xff] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
int pad = 0;
for (int i = sLen; i > 1 && IA[sArr[--i] & 0xff] <= 0; )
if (sArr[i] == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[sArr[s++] & 0xff];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++] = (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/**
* Decodes a BASE64 encoded byte array that is known to be resonably well formatted. The method is about twice as
* fast as {@link =#=decode(byte[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(byte[] sArr) {
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx] & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx] & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
/**
* Decodes a BASE64 encoded char array that is known to be resonably well formatted. The method is about twice as
* fast as {@link =#=decode(char[])}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param sArr The source array. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(char[] sArr) {
// Check special case
int sLen = sArr.length;
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[sArr[sIx]] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[sArr[eIx]] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = sArr[eIx] == '=' ? (sArr[eIx - 1] == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (sArr[76] == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[sArr[sIx++]] << 18 | IA[sArr[sIx++]] << 12 | IA[sArr[sIx++]] << 6 | IA[sArr[sIx++]];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[sArr[sIx++]] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
/**
* Decodes a BASE64 encoded <code>String</code>. All illegal characters will be ignored and can handle both strings with
* and without line separators.<br>
* <b>Note!</b> It can be up to about 2x the speed to call <code>decode(str.toCharArray())</code> instead. That
* will create a temporary array though. This version will use <code>str.charAt(i)</code> to iterate the string.
*
* @param str The source string. <code>null</code> or length 0 will return an empty array.
* @return The decoded array of bytes. May be of length 0. Will be <code>null</code> if the legal characters
* (including '=') isn't divideable by 4. (I.e. definitely corrupted).
*/
public final static byte[] decode(String str) {
// Check special case
int sLen = str != null ? str.length() : 0;
if (sLen == 0)
return new byte[0];
// Count illegal characters (including '\r', '\n') to know what size the returned array will be,
// so we don't have to reallocate & copy it later.
int sepCnt = 0; // Number of separator characters. (Actually illegal characters, but that's a bonus...)
for (int i = 0; i < sLen; i++) // If input is "pure" (I.e. no line separators or illegal chars) base64 this loop can be commented out.
if (IA[str.charAt(i)] < 0)
sepCnt++;
// Check so that legal chars (including '=') are evenly divideable by 4 as specified in RFC 2045.
if ((sLen - sepCnt) % 4 != 0)
return null;
// Count '=' at end
int pad = 0;
for (int i = sLen; i > 1 && IA[str.charAt(--i)] <= 0; )
if (str.charAt(i) == '=')
pad++;
int len = ((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
for (int s = 0, d = 0; d < len; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = 0;
for (int j = 0; j < 4; j++) { // j only increased if a valid char was found.
int c = IA[str.charAt(s++)];
if (c >= 0)
i |= c << (18 - j * 6);
else
j--;
}
// Add the bytes
dArr[d++] = (byte) (i >> 16);
if (d < len) {
dArr[d++] = (byte) (i >> 8);
if (d < len)
dArr[d++] = (byte) i;
}
}
return dArr;
}
/**
* Decodes a BASE64 encoded string that is known to be resonably well formatted. The method is about twice as
* fast as {@link =#=decode(String)}. The preconditions are:<br>
* + The array must have a line length of 76 chars OR no line separators at all (one line).<br>
* + Line separator must be "\r\n", as specified in RFC 2045
* + The array must not contain illegal characters within the encoded string<br>
* + The array CAN have illegal characters at the beginning and end, those will be dealt with appropriately.<br>
*
* @param str The source string. Length 0 will return an empty array. <code>null</code> will throw an exception.
* @return The decoded array of bytes. May be of length 0.
*/
public final static byte[] decodeFast(String str) {
// Check special case
int sLen = str.length();
if (sLen == 0)
return new byte[0];
int sIx = 0, eIx = sLen - 1; // Start and end index after trimming.
// Trim illegal chars from start
while (sIx < eIx && IA[str.charAt(sIx) & 0xff] < 0)
sIx++;
// Trim illegal chars from end
while (eIx > 0 && IA[str.charAt(eIx) & 0xff] < 0)
eIx--;
// get the padding count (=) (0, 1 or 2)
int pad = str.charAt(eIx) == '=' ? (str.charAt(eIx - 1) == '=' ? 2 : 1) : 0; // Count '=' at end.
int cCnt = eIx - sIx + 1; // Content count including possible separators
int sepCnt = sLen > 76 ? (str.charAt(76) == '\r' ? cCnt / 78 : 0) << 1 : 0;
int len = ((cCnt - sepCnt) * 6 >> 3) - pad; // The number of decoded bytes
byte[] dArr = new byte[len]; // Preallocate byte[] of exact length
// Decode all but the last 0 - 2 bytes.
int d = 0;
for (int cc = 0, eLen = (len / 3) * 3; d < eLen; ) {
// Assemble three bytes into an int from four "valid" characters.
int i = IA[str.charAt(sIx++)] << 18 | IA[str.charAt(sIx++)] << 12 | IA[str.charAt(sIx++)] << 6 | IA[str.charAt(sIx++)];
// Add the bytes
dArr[d++] = (byte) (i >> 16);
dArr[d++] = (byte) (i >> 8);
dArr[d++] = (byte) i;
// If line separator, jump over it.
if (sepCnt > 0 && ++cc == 19) {
sIx += 2;
cc = 0;
}
}
if (d < len) {
// Decode last 1-3 bytes (incl '=') into 1-3 bytes
int i = 0;
for (int j = 0; sIx <= eIx - pad; j++)
i |= IA[str.charAt(sIx++)] << (18 - j * 6);
for (int r = 16; d < len; r -= 8)
dArr[d++] = (byte) (i >> r);
}
return dArr;
}
}

@ -1,34 +0,0 @@
package xyz.wbsite.frame.utils;
import javax.servlet.http.Cookie;
/**
* CookieUtil
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class CookieUtil {
/**
* Cookies
*
* @param cookies Cookies
* @return passportID
*/
public static String getCookieValue(Cookie[] cookies, String key) {
if (cookies != null) {
for (Cookie cookie : cookies) {
// Cookie中存放的为passport的id Cookie名称通过ConfigToolObject获取
if (cookie != null && cookie.getName().equals(key)) {
try {
return cookie.getValue();
} catch (Exception ignored) {
}
}
}
}
return null;
}
}

@ -1,915 +0,0 @@
package xyz.wbsite.frame.utils;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class FileUtil {
/**
*
*/
private FileUtil() {
}
/**
* 访
*
* <b></b>
*
* @param file 访
* @since 1.0
*/
public static void touch(File file) {
long currentTime = System.currentTimeMillis();
if (!file.exists()) {
System.err.println("file not found:" + file.getName());
System.err.println("Create a new file:" + file.getName());
try {
if (file.createNewFile()) {
System.out.println("Succeeded!");
} else {
System.err.println("Create file failed!");
}
} catch (IOException e) {
System.err.println("Create file failed!");
e.printStackTrace();
}
}
boolean result = file.setLastModified(currentTime);
if (!result) {
System.err.println("touch failed: " + file.getName());
}
}
/**
* 访
*
* <b></b>
*
* @param fileName 访
* @since 1.0
*/
public static void touch(String fileName) {
File file = new File(fileName);
touch(file);
}
/**
* 访
*
* <b></b>
*
* @param files 访
* @since 1.0
*/
public static void touch(File[] files) {
for (int i = 0; i < files.length; i++) {
touch(files[i]);
}
}
/**
* 访
*
* <b></b>
*
* @param fileNames 访
* @since 1.0
*/
public static void touch(String[] fileNames) {
File[] files = new File[fileNames.length];
for (int i = 0; i < fileNames.length; i++) {
files[i] = new File(fileNames[i]);
}
touch(files);
}
/**
*
*
* @param fileName
* @return truefalse
* @since 1.0
*/
public static boolean isFileExist(String fileName) {
return new File(fileName).isFile();
}
/**
*
*
* <b>false</b>
*
* @param file
* @return truefalse
* @since 1.0
*/
public static boolean makeDirectory(File file) {
File parent = file.getParentFile();
if (parent != null) {
return parent.mkdirs();
}
return false;
}
/**
*
*
* <b>false</b>
*
* @param fileName
* @return truefalse
* @since 1.0
*/
public static boolean makeDirectory(String fileName) {
File file = new File(fileName);
return makeDirectory(file);
}
/**
*
* false
*
*
* @param directory
* @return truefalse.
* @since 1.0
*/
public static boolean emptyDirectory(File directory) {
boolean result = true;
File[] entries = directory.listFiles();
for (int i = 0; i < entries.length; i++) {
if (!entries[i].delete()) {
result = false;
}
}
return result;
}
/**
*
* false
*
*
* @param directoryName
* @return truefalse
* @since 1.0
*/
public static boolean emptyDirectory(String directoryName) {
File dir = new File(directoryName);
return emptyDirectory(dir);
}
/**
*
*
* @param dirName
* @return truefalse
* @since 1.0
*/
public static boolean deleteDirectory(String dirName) {
return deleteDirectory(new File(dirName));
}
/**
*
*
* @param dir
* @return truefalse
* @since 1.0
*/
public static boolean deleteDirectory(File dir) {
if ((dir == null) || !dir.isDirectory()) {
throw new IllegalArgumentException("Argument " + dir +
" is not a directory. ");
}
File[] entries = dir.listFiles();
int sz = entries.length;
for (int i = 0; i < sz; i++) {
if (entries[i].isDirectory()) {
if (!deleteDirectory(entries[i])) {
return false;
}
} else {
if (!entries[i].delete()) {
return false;
}
}
}
if (!dir.delete()) {
return false;
}
return true;
}
/**
*
*
* @param file
* @param filter
* @return
* @since 1.0
*/
public static File[] listAll(File file,
javax.swing.filechooser.FileFilter filter) {
ArrayList list = new ArrayList();
File[] files;
if (!file.exists() || file.isFile()) {
return null;
}
list(list, file, filter);
files = new File[list.size()];
list.toArray(files);
return files;
}
/**
*
*
* @param list
* @param filter
* @param file
*/
private static void list(ArrayList list, File file,
javax.swing.filechooser.FileFilter filter) {
if (filter.accept(file)) {
list.add(file);
if (file.isFile()) {
return;
}
}
if (file.isDirectory()) {
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
list(list, files[i], filter);
}
}
}
/**
* URL
*
* @param file
* @return URL
* @throws MalformedURLException
* @since 1.0
* @deprecated FiletoURLURL
* 使File.toURL
*/
public static URL getURL(File file) throws MalformedURLException {
String fileURL = "file:/" + file.getAbsolutePath();
URL url = new URL(fileURL);
return url;
}
/**
*
*
* @param filePath
* @return
* @since 1.0
*/
public static String getFileName(String filePath) {
File file = new File(filePath);
return file.getName();
}
/**
*
*
* @param fileName
* @return
* @since 1.0
*/
public static String getFilePath(String fileName) {
File file = new File(fileName);
return file.getAbsolutePath();
}
/**
* DOS/WindowsUNIX/Linux
* "\"全部换为"/"便
* "/""\"DOS/Windows
*
* @param filePath
* @return
* @since 1.0
*/
public static String toUNIXpath(String filePath) {
return filePath.replace('\\', '/');
}
/**
* UNIX
*
* @param fileName
* @return UNIX
* @see #toUNIXpath(String filePath) toUNIXpath
* @since 1.0
*/
public static String getUNIXfilePath(String fileName) {
File file = new File(fileName);
return toUNIXpath(file.getAbsolutePath());
}
/**
*
* .
*
* @param fileName
* @return
* @since 1.0
*/
public static String getTypePart(String fileName) {
int point = fileName.lastIndexOf('.');
int length = fileName.length();
if (point == -1 || point == length - 1) {
return "";
} else {
return fileName.substring(point + 1, length);
}
}
/**
*
* .
*
* @param file
* @return
* @since 1.0
*/
public static String getFileType(File file) {
return getTypePart(file.getName());
}
/**
*
*
*
* @param fileName
* @return
* @since 1.0
*/
public static String getNamePart(String fileName) {
int point = getPathLsatIndex(fileName);
int length = fileName.length();
if (point == -1) {
return fileName;
} else if (point == length - 1) {
int secondPoint = getPathLsatIndex(fileName, point - 1);
if (secondPoint == -1) {
if (length == 1) {
return fileName;
} else {
return fileName.substring(0, point);
}
} else {
return fileName.substring(secondPoint + 1, point);
}
} else {
return fileName.substring(point + 1);
}
}
/**
*
*
* ""
* "/path/"""
*
* @param fileName
* @return ""
* @since 1.0
*/
public static String getPathPart(String fileName) {
int point = getPathLsatIndex(fileName);
int length = fileName.length();
if (point == -1) {
return "";
} else if (point == length - 1) {
int secondPoint = getPathLsatIndex(fileName, point - 1);
if (secondPoint == -1) {
return "";
} else {
return fileName.substring(0, secondPoint);
}
} else {
return fileName.substring(0, point);
}
}
/**
*
* DOSUNIX
*
* @param fileName
* @return -1
* @since 1.0
*/
public static int getPathIndex(String fileName) {
int point = fileName.indexOf('/');
if (point == -1) {
point = fileName.indexOf('\\');
}
return point;
}
/**
*
* DOSUNIX
*
* @param fileName
* @param fromIndex
* @return -1
* @since 1.0
*/
public static int getPathIndex(String fileName, int fromIndex) {
int point = fileName.indexOf('/', fromIndex);
if (point == -1) {
point = fileName.indexOf('\\', fromIndex);
}
return point;
}
/**
*
* DOSUNIX
*
* @param fileName
* @return -1
* @since 1.0
*/
public static int getPathLsatIndex(String fileName) {
int point = fileName.lastIndexOf('/');
if (point == -1) {
point = fileName.lastIndexOf('\\');
}
return point;
}
/**
*
* DOSUNIX
*
* @param fileName
* @param fromIndex
* @return -1
* @since 1.0
*/
public static int getPathLsatIndex(String fileName, int fromIndex) {
int point = fileName.lastIndexOf('/', fromIndex);
if (point == -1) {
point = fileName.lastIndexOf('\\', fromIndex);
}
return point;
}
/**
*
*
* @param filename
* @return
* @since 1.0
*/
public static String trimType(String filename) {
int index = filename.lastIndexOf(".");
if (index != -1) {
return filename.substring(0, index);
} else {
return filename;
}
}
/**
*
*
*
* @param pathName
* @param fileName
* @return
* @since 1.0
*/
public static String getSubpath(String pathName, String fileName) {
int index = fileName.indexOf(pathName);
if (index != -1) {
return fileName.substring(index + pathName.length() + 1);
} else {
return fileName;
}
}
/**
*
*
*
* @param path
* @return
* @since 1.0
*/
public static final boolean pathValidate(String path) {
//String path="d:/web/www/sub";
//System.out.println(path);
//path = getUNIXfilePath(path);
//path = ereg_replace("^\\/+", "", path);
//path = ereg_replace("\\/+$", "", path);
String[] arraypath = path.split("/");
String tmppath = "";
for (int i = 0; i < arraypath.length; i++) {
tmppath += "/" + arraypath[i];
File d = new File(tmppath.substring(1));
if (!d.exists()) { //检查Sub目录是否存在
System.out.println(tmppath.substring(1));
if (!d.mkdir()) {
return false;
}
}
}
return true;
}
/**
*
*
*
* @param path
* @return
* @since 1.0
*/
public static final String getFileContent(String path) throws IOException {
String filecontent = "";
try {
File f = new File(path);
if (f.exists()) {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr); //建立BufferedReader对象并实例化为br
String line = br.readLine(); //从文件读取一行字符串
//判断读取到的字符串是否不为空
while (line != null) {
filecontent += line + "\n";
line = br.readLine(); //从文件中继续读取一行数据
}
br.close(); //关闭BufferedReader对象
fr.close(); //关闭文件
}
} catch (IOException e) {
throw e;
}
return filecontent;
}
/**
*
*
* @param path
* @param modulecontent
* @return
* @since 1.0
*/
public static final boolean genModuleTpl(String path, String modulecontent) throws IOException {
path = getUNIXfilePath(path);
String[] patharray = path.split("\\/");
String modulepath = "";
for (int i = 0; i < patharray.length - 1; i++) {
modulepath += "/" + patharray[i];
}
File d = new File(modulepath.substring(1));
if (!d.exists()) {
if (!pathValidate(modulepath.substring(1))) {
return false;
}
}
try {
FileWriter fw = new FileWriter(path); //建立FileWriter对象并实例化fw
//将字符串写入文件
fw.write(modulecontent);
fw.close();
} catch (IOException e) {
throw e;
}
return true;
}
/**
*
*
* @param pic_path
* @return
* @since 1.0
*/
public static final String getPicExtendName(String pic_path) {
pic_path = getUNIXfilePath(pic_path);
String pic_extend = "";
if (isFileExist(pic_path + ".gif")) {
pic_extend = ".gif";
}
if (isFileExist(pic_path + ".jpeg")) {
pic_extend = ".jpeg";
}
if (isFileExist(pic_path + ".jpg")) {
pic_extend = ".jpg";
}
if (isFileExist(pic_path + ".png")) {
pic_extend = ".png";
}
return pic_extend; //返回图片扩展名
}
/**
*
*
* @param in
* @param out
* @return
* @throws Exception
*/
public static final boolean CopyFile(File in, File out) throws Exception {
try {
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
byte[] buf = new byte[1024];
int i = 0;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
fis.close();
fos.close();
return true;
} catch (IOException ie) {
ie.printStackTrace();
return false;
}
}
/**
*
*
* @param infile
* @param outfile
* @return
* @throws Exception
*/
public static final boolean CopyFile(String infile, String outfile) throws Exception {
try {
File in = new File(infile);
File out = new File(outfile);
return CopyFile(in, out);
} catch (IOException ie) {
ie.printStackTrace();
return false;
}
}
/**
* contentpath
*
* @param content
* @param path
* @return
*/
public static boolean SaveFileAs(String content, String path) {
FileWriter fw = null;
try {
fw = new FileWriter(new File(path), false);
if (content != null) {
fw.write(content);
}
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (fw != null) {
try {
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
*
*/
public static byte[] readFileByBytes(String fileName) throws IOException {
FileInputStream in = new FileInputStream(fileName);
byte[] bytes = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] temp = new byte[1024];
int size = 0;
while ((size = in.read(temp)) != -1) {
out.write(temp, 0, size);
}
in.close();
bytes = out.toByteArray();
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
return bytes;
}
/**
*
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下\r\n这两个字符在一起时表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r或者屏蔽\n。否则将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
*
*/
public static List<String> readFileByLines(String fileName) {
List<String> returnString = new ArrayList<String>();
File file = new File(fileName);
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
returnString.add(tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return returnString;
}
/**
*
*/
public static void readFileByRandomAccess(String fileName) {
RandomAccessFile randomFile = null;
try {
System.out.println("随机读取一段文件内容:");
// 打开一个随机访问文件流,按只读方式
randomFile = new RandomAccessFile(fileName, "r");
// 文件长度,字节数
long fileLength = randomFile.length();
// 读文件的起始位置
int beginIndex = (fileLength > 4) ? 4 : 0;
// 将读文件的开始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[] bytes = new byte[10];
int byteread = 0;
// 一次读10个字节如果文件内容不足10个字节则读剩下的字节。
// 将一次读取的字节数赋给byteread
while ((byteread = randomFile.read(bytes)) != -1) {
System.out.write(bytes, 0, byteread);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (randomFile != null) {
try {
randomFile.close();
} catch (IOException e1) {
}
}
}
}
/**
*
*
* @param fileName
* @return
*/
public static String readFileAll(String fileName) {
String encoding = "UTF-8";
File file = new File(fileName);
Long filelength = file.length();
byte[] filecontent = new byte[filelength.intValue()];
try {
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
return new String(filecontent, encoding);
} catch (UnsupportedEncodingException e) {
System.err.println("The OS does not support " + encoding);
e.printStackTrace();
return "";
}
}
/**
*
*/
private static void showAvailableBytes(InputStream in) {
try {
System.out.println("当前字节输入流中的字节数为:" + in.available());
} catch (IOException e) {
e.printStackTrace();
}
}
public static void inputStream2File(InputStream is, File target) {
try {
if (!target.exists() && !target.createNewFile()) {
throw new RuntimeException(target.getName() + "not exists");
}
OutputStream outStream = new FileOutputStream(target);
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = is.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

@ -1,73 +0,0 @@
package xyz.wbsite.frame.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* IDgenerator - ID
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class IDgenerator {
private static long workerId = 1L;
private static long datacenterId = 1L;
private static long sequence = 0L;
// 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
private static long twepoch = 1531130104852L;
// 机器标识位数
private static long workerIdBits = 2L;//分布应用可设置为5这里减少占位增加可支持时间
// 数据中心标识位数
private static long datacenterIdBits = 2L;//分布应用可设置为5这里减少占位增加可支持时间
// 机器ID最大值
private static long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 数据中心ID最大值
private static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
// 毫秒内自增位
private static long sequenceBits = 12L;
// 机器ID偏左移12位
private static long workerIdShift = sequenceBits;
// 数据中心ID左移17位
private static long datacenterIdShift = sequenceBits + workerIdBits;
// 时间毫秒左移22位
private static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private static long sequenceMask = -1L ^ (-1L << sequenceBits);
// 上次生产id时间戳
private static long lastTimestamp = -1L;
public static synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence;
}
protected static long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
protected static long timeGen() {
return System.currentTimeMillis();
}
}

@ -1,86 +0,0 @@
package xyz.wbsite.frame.utils;
import xyz.wbsite.frame.base.Token;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* LocalData -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class LocalData {
private static Token temp = null;
private static Token system = null;
static {
// 组装临时Token和系统Token
temp = new Token();
temp.setId(-1);
temp.setUserId(-1);
temp.setUserName("游客");
temp.putResource("/login.htm");
temp.putResource("/ajax");
temp.putResource("ajax.login");
system = new Token();
system.setId(0);
system.setUserId(0);
system.setUserName("system");
system.putResource(".*");
}
public static Token getTempToken(){
return temp;
}
public static Token getSysToken() {
return system;
}
/**
* target = '/aa/bb'
*/
private static final ThreadLocal<String> targetHolder = new ThreadLocal();
public static String getTarget() {
return targetHolder.get();
}
public static void setTarget(String target) {
targetHolder.set(target);
}
/**
*
*/
private static final ThreadLocal<Token> tokenHolder = new ThreadLocal();
public static Token getToken() {
return tokenHolder.get();
}
public static void setToken(Token token) {
tokenHolder.set(token);
}
public static HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
public static HttpServletResponse getResponse() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
}
public static ApplicationContext getApplicationContext() {
return WebApplicationContextUtils.getWebApplicationContext(getRequest().getServletContext());
}
}

@ -1,70 +0,0 @@
package xyz.wbsite.frame.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* LogUtil -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class LogUtil {
//定义一个全局的记录器通过LoggerFactory获取
private final static Logger logger = LoggerFactory.getLogger(LogUtil.class);
/**
* info
* @param context
*/
public static void i(String context){
logger.info(context);
}
/**
* debug
* @param context
*/
public static void d(String context){
logger.debug(context);
}
/**
* warn
* @param context
*/
public static void w(String context){
logger.warn(context);
}
/**
* error
* @param context
*/
public static void e(String context){
logger.error(context);
}
/**
*
*/
public static void dumpException(Throwable e){
StringBuffer msg = new StringBuffer("null");
if (e != null) {
msg = new StringBuffer("");
String message = e.toString();
int length = e.getStackTrace().length;
if (length > 0) {
msg.append(message).append("\n");
for (int i = 0; i < length; i++) {
msg.append("\t").append(e.getStackTrace()[i]).append("\n");
}
} else {
msg.append(message);
}
}
logger.error(msg.toString());
}
}

@ -1,58 +0,0 @@
package xyz.wbsite.frame.utils;
import com.fasterxml.jackson.core.TreeNode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
/**
* MD5Util - MD5
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class MD5Util {
/**
*
*
* @param value
* @return
*/
public static String encode(String value) {
try {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] e = md.digest(value.getBytes());
return toHexString(e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return value;
}
}
public static String encode(byte[] bytes) {
try {
MessageDigest md = MessageDigest.getInstance("md5");
byte[] e = md.digest(bytes);
return toHexString(e);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return "";
}
}
private static String toHexString(byte bytes[]) {
StringBuilder hs = new StringBuilder();
String stmp = "";
for (int n = 0; n < bytes.length; n++) {
stmp = Integer.toHexString(bytes[n] & 0xff);
if (stmp.length() == 1)
hs.append("0").append(stmp);
else
hs.append(stmp);
}
return hs.toString();
}
}

@ -1,133 +0,0 @@
package xyz.wbsite.frame.utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.TreeNode;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* MapUtil -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class MapperUtil {
private static ObjectMapper om;
private static Mapper mapper;
static {
//初始化
om = new ObjectMapper();
//序列化时忽略null属性
om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//序列化时排序
om.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
//反序列化是忽略多余字段
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//支持空类序列化时出错InvalidDefinitionException
om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
mapper = new DozerBeanMapper();
}
public static TreeNode toTree(String json) {
try {
return om.readTree(json);
} catch (IOException e) {
e.printStackTrace();
return om.createObjectNode();
}
}
public static TreeNode toTree(Object json) {
return om.valueToTree(json);
}
public static String toJson(Object object) {
return toJson(object, false);
}
public static String toJson(Object object, boolean pretty) {
try {
if (pretty) {
return om.writerWithDefaultPrettyPrinter().writeValueAsString(object);
} else {
return om.writeValueAsString(object);
}
} catch (JsonProcessingException e) {
e.printStackTrace();
return "{}";
}
}
public static String toJson(JsonNode jsonNode) {
return jsonNode.asText();
}
public static <T> T toJava(String json, Class<T> cls) {
try {
if (json == null || "".equals(json)) {
return cls.newInstance();
}
return om.readValue(json, cls);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
public static <T> T toJava(TreeNode treeNode, Class<T> cls) {
try {
return om.treeToValue(treeNode, cls);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static <T> T toJava(String json, TypeReference<T> valueTypeRef) {
try {
return om.readValue(json, valueTypeRef);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> List<T> toJavaList(String json, TypeReference<List<T>> reference) {
try {
return om.readValue(json, reference);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> List<T> toJavaList(InputStream json, TypeReference<List<T>> reference) {
try {
return om.readValue(json, reference);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static <T> T map(Object o, Class<T> aClass) {
return mapper.map(o, aClass);
}
public static void map(Object o, Object o1) {
mapper.map(o, o1);
}
}

@ -1,21 +0,0 @@
package xyz.wbsite.frame.utils;
/**
* Message -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class Message {
public static final String ERROR_500 = "服务器走了下神,稍后再试一次";
public static final String NOT_EXIST_METHOD = "调用的方法不存在";
public static String CREATE_FAILURE = "创建失败,请刷新后重新尝试";
public static String DELETE_FAILURE = "删除失败,请刷新后重新尝试";
public static String UPDATE_FAILURE = "更新失败,请刷新后重新尝试";
public static String FIND_FAILURE = "查询失败,请刷新后重新尝试";
public static String GET_FAILURE = "未获取相应内容";
public static String INSERT_DUPLICATE = "已经存在相同数据,返回列表页面确认";
}

@ -1,121 +0,0 @@
package xyz.wbsite.frame.utils;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ProcessUtil {
/**
* windowsexe
*
* @param exe exe
*/
public static void execExe(String exe) {
try {
Runtime.getRuntime().exec(exe);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* windows
*
* @param bat
*/
public static void execBat(String bat) {
if (!bat.endsWith(".bat")) {
throw new RuntimeException(bat + "is not a file of .bat");
}
try {
Runtime.getRuntime().exec(bat);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* windows cmd
*
* @param command cmd
*/
public static String execCmd(String command) {
return exec("cmd /c " + command);
}
/**
*
*
* @param command cmd
*/
public static String exec(String command) {
StringBuilder build = new StringBuilder();
Runtime runtime = Runtime.getRuntime();
Process process = null;
try {
System.out.println("==>>" + command);
process = runtime.exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
String line = null;
while ((line = br.readLine()) != null) {
build.append(line);
}
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return build.toString();
}
/**
* @throws IOException
* @desc
* @author zp
* @date 2018-3-29
*/
public static void killProc(String processName) throws IOException {
if (processName != null && !"".equals(processName)) {
execCmd("taskkill /F /IM " + processName);
}
}
/**
* @desc
* @author zp
* @date 2018-3-29
*/
public static boolean findProcess(String processName) {
BufferedReader bufferedReader = null;
try {
Process proc = Runtime.getRuntime().exec("tasklist -fi " + '"' + "imagename eq " + processName + '"');
bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains(processName)) {
return true;
}
}
return false;
} catch (Exception ex) {
ex.printStackTrace();
return false;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (Exception ex) {
}
}
}
}
}

@ -1,308 +0,0 @@
package xyz.wbsite.frame.utils;
import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
/**
* RSAUtil - RSA
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class RSAUtil {
private static String cryptPublicKeyBase64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTrwfsrJjCF+pP4S3A/wrD4U1txg53EuBC1mPt" +
"3vGXvSK2U0YNRVR3Q65ooHnPKmk4LwI8v+7+ATTxUg3qkuRiDuzBa5zLkYKM50LOgEWSdOKzbnbx" +
"a5FnE7IXawNt1p8+MVN1TTI7J/fZy6g1x0WBy1odE5Osru4WfZNOqQtjHwIDAQAB";
private static String cryptPrivateKeyBase64 = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJOvB+ysmMIX6k/hLcD/CsPhTW3G" +
"DncS4ELWY+3e8Ze9IrZTRg1FVHdDrmigec8qaTgvAjy/7v4BNPFSDeqS5GIO7MFrnMuRgoznQs6A" +
"RZJ04rNudvFrkWcTshdrA23Wnz4xU3VNMjsn99nLqDXHRYHLWh0Tk6yu7hZ9k06pC2MfAgMBAAEC" +
"gYBjLRjKRMI1HfBZgmPChsPI9YWU4XuXVVLLL8Rd2uktOHOWM2gIw3VMvmPimVoT2GxesZr0BwTN" +
"CSxvnuX/kHPTqtsIu1r5Iup3mGbvlj3sn8RvG0yvUDglDN7QVDqqN7XWvHJSBVfBzDXeExA/WGnE" +
"6BOocNT9qkqA/UWNbCXGKQJBAN0Fd/P2D6EvCd2RztHhzVE6V8s/LwOTDnGn/YhdMpddy9TwZpBi" +
"r7I6lzcLWQ1HfDUive3t+DGXqPqr/4FfkG0CQQCrDlZKf216QrXOmJ70LQSbflgvGYU+b6kLFyEh" +
"+15HcIBfKUQCU+XUK4UzLMQDYxdngTNMNyq4AQ9Sh0tUTUI7AkEAtkq9XayzxWhLhcCtyTOoqPcq" +
"1Aqf1x3iCuHYXTEo+ek1pcJFhY6vhJuIfrDQWQB9tEGcTvI4A4cnquBTkzvjnQJAYid58ImqYmuB" +
"M6l0HJzwdeFL7MryIF+mWozNIFjDQq8VmoVtVwCZcuP+LN1VJLRpq6UBsIw/YRKKnkqwORGUHQJA" +
"UuR0G/3Hai+vKDA14tIYIH6C4zNmbULxAEuQVh9thfafWNmiDcifApvkxQ2ewXwEGeJtz44zv6iY" +
"3f3yq+a2OQ==";
private static String signPublicKeyBase64 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCTrwfsrJjCF+pP4S3A/wrD4U1txg53EuBC1mPt" +
"3vGXvSK2U0YNRVR3Q65ooHnPKmk4LwI8v+7+ATTxUg3qkuRiDuzBa5zLkYKM50LOgEWSdOKzbnbx" +
"a5FnE7IXawNt1p8+MVN1TTI7J/fZy6g1x0WBy1odE5Osru4WfZNOqQtjHwIDAQAB";
private static String signPrivateKeyBase64 = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJOvB+ysmMIX6k/hLcD/CsPhTW3G" +
"DncS4ELWY+3e8Ze9IrZTRg1FVHdDrmigec8qaTgvAjy/7v4BNPFSDeqS5GIO7MFrnMuRgoznQs6A" +
"RZJ04rNudvFrkWcTshdrA23Wnz4xU3VNMjsn99nLqDXHRYHLWh0Tk6yu7hZ9k06pC2MfAgMBAAEC" +
"gYBjLRjKRMI1HfBZgmPChsPI9YWU4XuXVVLLL8Rd2uktOHOWM2gIw3VMvmPimVoT2GxesZr0BwTN" +
"CSxvnuX/kHPTqtsIu1r5Iup3mGbvlj3sn8RvG0yvUDglDN7QVDqqN7XWvHJSBVfBzDXeExA/WGnE" +
"6BOocNT9qkqA/UWNbCXGKQJBAN0Fd/P2D6EvCd2RztHhzVE6V8s/LwOTDnGn/YhdMpddy9TwZpBi" +
"r7I6lzcLWQ1HfDUive3t+DGXqPqr/4FfkG0CQQCrDlZKf216QrXOmJ70LQSbflgvGYU+b6kLFyEh" +
"+15HcIBfKUQCU+XUK4UzLMQDYxdngTNMNyq4AQ9Sh0tUTUI7AkEAtkq9XayzxWhLhcCtyTOoqPcq" +
"1Aqf1x3iCuHYXTEo+ek1pcJFhY6vhJuIfrDQWQB9tEGcTvI4A4cnquBTkzvjnQJAYid58ImqYmuB" +
"M6l0HJzwdeFL7MryIF+mWozNIFjDQq8VmoVtVwCZcuP+LN1VJLRpq6UBsIw/YRKKnkqwORGUHQJA" +
"UuR0G/3Hai+vKDA14tIYIH6C4zNmbULxAEuQVh9thfafWNmiDcifApvkxQ2ewXwEGeJtz44zv6iY" +
"3f3yq+a2OQ==";
/**
*
*/
public static void createKey() {
try {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
//公钥
RSAPublicKey aPublic = (RSAPublicKey) keyPair.getPublic();
//私钥
RSAPrivateKey aPrivate = (RSAPrivateKey) keyPair.getPrivate();
//把密钥对象对应的字节转为Base64字符存储
System.err.println("publicKeyBase64-->" + Base64Util.encodeToString(aPublic.getEncoded()));
System.err.println("privateKeyBase64-->" + Base64Util.encodeToString(aPrivate.getEncoded()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public static String encrypt2Base64(byte[] data) {
byte[] encrypt = encrypt(data);
return Base64Util.encodeToString(encrypt);
}
public static byte[] encrypt(String data) {
return encrypt(data.getBytes());
}
/**
*
*
* @param data
*/
public static byte[] encrypt(byte[] data) {
try {
//生成公钥对象
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64Util.decode(cryptPublicKeyBase64));
PublicKey aPublic = keyFactory.generatePublic(x509EncodedKeySpec);
//分段加密开始
ByteArrayOutputStream bs = new ByteArrayOutputStream();
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, aPublic);
int offset = 0;
while (offset < data.length) {
byte[] bytes = rsa.doFinal(Arrays.copyOfRange(data, offset, Math.min(offset + 117, data.length)));
bs.write(bytes);
offset += 117;
}
return bs.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
*
* @param data
*/
public static byte[] encrypt(String data, PublicKey aPublic) {
try {
if (aPublic == null) {
System.err.println("PublicKey can not be null");
return null;
}
//分段加密开始
ByteArrayOutputStream bs = new ByteArrayOutputStream();
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.ENCRYPT_MODE, aPublic);
int offset = 0;
byte[] b = data.getBytes();
while (offset < b.length) {
byte[] bytes = rsa.doFinal(Arrays.copyOfRange(b, offset, Math.min(offset + 117, b.length)));
bs.write(bytes);
offset += 117;
}
return bs.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param base64String base64
* @return
*/
public static byte[] decrypt(String base64String) {
return decrypt(Base64Util.decode(base64String));
}
public static String decrypt2String(String base64String) {
byte[] decrypt = decrypt(Base64Util.decode(base64String));
try {
return new String(decrypt, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
/**
*
*
* @param data
*/
public static byte[] decrypt(byte[] data) {
try {
//生成私钥对象
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64Util.decode(cryptPrivateKeyBase64));
PrivateKey aPrivate = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, aPrivate);
//获得密文字节
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int offset = 0;
while (offset < data.length) {
byte[] bytes = rsa.doFinal(Arrays.copyOfRange(data, offset, Math.min(offset + 128, data.length)));
bs.write(bytes);
offset += 128;
}
return bs.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
*
*
* @param data
* @param aPrivate
* @return
*/
public static byte[] decrypt(byte[] data, PublicKey aPrivate) {
try {
if (aPrivate == null) {
System.err.println("PublicKey can not be null");
return null;
}
Cipher rsa = Cipher.getInstance("RSA");
rsa.init(Cipher.DECRYPT_MODE, aPrivate);
//获得密文字节
ByteArrayOutputStream bs = new ByteArrayOutputStream();
int offset = 0;
while (offset < data.length) {
byte[] bytes = rsa.doFinal(Arrays.copyOfRange(data, offset, Math.min(offset + 128, data.length)));
bs.write(bytes);
offset += 128;
}
return bs.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String sign2Base64(byte[] data) {
return sign2Base64(data, signPrivateKeyBase64);
}
public static String sign2Base64(byte[] data, String privateKey) {
byte[] sign = sign(data, privateKey);
return Base64Util.encodeToString(sign);
}
/**
* RSA
*
* @param data
* @param privateKey
* @return
*/
public static byte[] sign(byte[] data, String privateKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Util.decode(privateKey));
PrivateKey aPrivate = keyFactory.generatePrivate(priPKCS8);
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initSign(aPrivate);
signature.update(data);
return signature.sign();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* RSA
*
* @param data
* @param sign base64
* @param publicKey
* @return
*/
public static boolean doCheck(byte[] data, String sign, String publicKey) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
byte[] encodedKey = Base64Util.decode(publicKey);
PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));
Signature signature = Signature.getInstance("SHA1WithRSA");
signature.initVerify(pubKey);
signature.update(data);
return signature.verify(Base64Util.decode(sign));
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean doCheck(byte[] data, String sign) {
return doCheck(data, sign, signPublicKeyBase64);
}
public static PublicKey parsePublicKey(String cryptPublicKeyBase64) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64Util.decode(cryptPublicKeyBase64));
return keyFactory.generatePublic(x509EncodedKeySpec);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
public static PrivateKey parsePrivateKey(String cryptPrivateKeyBase64) {
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Util.decode(cryptPrivateKeyBase64));
return keyFactory.generatePrivate(priPKCS8);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return null;
}
}

@ -1,79 +0,0 @@
package xyz.wbsite.frame.utils;
import javax.servlet.http.HttpServletRequest;
/**
* RequestUtil
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class RequestUtil {
/**
* IP
*
* @param request
* @return
*/
public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} else if (ip.length() > 15) {
String[] ips = ip.split(",");
for (int index = 0; index < ips.length; index++) {
String strIp = (String) ips[index];
if (!("unknown".equalsIgnoreCase(strIp))) {
ip = strIp;
break;
}
}
}
return ip;
}
/**
*
*
* @param request
* @return
*/
public static String getUserAgent(HttpServletRequest request) {
return request.getHeader("User-Agent");
}
/**
* URL
*
* @param request
* @return URL
*/
public static String getErrorUrl(HttpServletRequest request) {
if (request.getAttribute("javax.servlet.error.request_uri") != null) {
return (String) request.getAttribute("javax.servlet.error.request_uri");
} else {
return "";
}
}
}

@ -1,47 +0,0 @@
package xyz.wbsite.frame.utils;
import xyz.wbsite.frame.base.BaseRequest;
import xyz.wbsite.frame.base.BaseResponse;
import xyz.wbsite.frame.base.ErrorType;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;
/**
*
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class ValidationUtil {
private static ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
public static <T extends BaseResponse> T validate(BaseRequest req, T response) {
if (req == null) {
response.addError(ErrorType.EXPECTATION_NULL, "请求对象不能为空");
return response;
}
try {
Validator validator = factory.getValidator();
Set<ConstraintViolation<BaseRequest>> constraintViolations = validator.validate(req);
if (constraintViolations.size() > 0) {
for (ConstraintViolation<BaseRequest> violation : constraintViolations) {
response.addError(ErrorType.INVALID_PARAMETER, violation.getMessage());
}
}
} catch (Exception e) {
e.printStackTrace();
LogUtil.dumpException(e);
response.addError(ErrorType.BUSINESS_ERROR, e.getMessage());
}
return response;
}
}

@ -1,459 +0,0 @@
package xyz.wbsite.frame.utils;
import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* WebUtils - http访
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
public class WebUtils {
private static final String DEFAULT_CHARSET = "UTF-8";
private static final String METHOD_POST = "POST";
private static final String METHOD_GET = "GET";
//private static final Certificate verisign; //
private static boolean ignoreSSLCheck; // 忽略SSL检查
private static class TrustAllTrustManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
}
private WebUtils() {
}
public static void setIgnoreSSLCheck(boolean ignoreSSLCheck) {
WebUtils.ignoreSSLCheck = ignoreSSLCheck;
}
/**
* HTTP POST
*
* @param url
* @param params
* @return
*/
public static String doPost(String url, Map<String, String> params, int connectTimeout, int readTimeout) throws IOException {
return doPost(url, params, DEFAULT_CHARSET, connectTimeout, readTimeout);
}
/**
* HTTP POST
*
* @param url
* @param params
* @param charset UTF-8, GBK, GB2312
* @return
*/
public static String doPost(String url, Map<String, String> params, String charset, int connectTimeout, int readTimeout) throws IOException {
return doPost(url, params, charset, connectTimeout, readTimeout, null);
}
public static String doPost(String url, Map<String, String> params, String charset, int connectTimeout, int readTimeout, Map<String, String> headerMap) throws IOException {
String ctype = "application/x-www-form-urlencoded;charset=" + charset;
String query = buildQuery(params, charset);
byte[] content = {};
if (query != null) {
content = query.getBytes(charset);
}
return _doPost(url, ctype, content, connectTimeout, readTimeout, headerMap);
}
/**
* HTTP POST
*
* @param url
* @param ctype
* @param content
* @return
*/
public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws IOException {
return _doPost(url, ctype, content, connectTimeout, readTimeout, null);
}
private static String _doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout, Map<String, String> headerMap) throws IOException {
HttpURLConnection conn = null;
OutputStream out = null;
String rsp = null;
try {
try {
conn = getConnection(new URL(url), METHOD_POST, ctype, headerMap);
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);
} catch (IOException e) {
throw e;
}
try {
out = conn.getOutputStream();
out.write(content);
rsp = getResponseAsString(conn);
} catch (IOException e) {
throw e;
}
} finally {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
private static byte[] getTextEntry(String fieldName, String fieldValue, String charset) throws IOException {
StringBuilder entry = new StringBuilder();
entry.append("Content-Disposition:form-data;name=\"");
entry.append(fieldName);
entry.append("\"\r\nContent-Type:text/plain\r\n\r\n");
entry.append(fieldValue);
return entry.toString().getBytes(charset);
}
private static byte[] getFileEntry(String fieldName, String fileName, String mimeType, String charset) throws IOException {
StringBuilder entry = new StringBuilder();
entry.append("Content-Disposition:form-data;name=\"");
entry.append(fieldName);
entry.append("\";filename=\"");
entry.append(fileName);
entry.append("\"\r\nContent-Type:");
entry.append(mimeType);
entry.append("\r\n\r\n");
return entry.toString().getBytes(charset);
}
/**
* HTTP GET
*
* @param url
* @param params
* @return
*/
public static String doGet(String url, Map<String, String> params) throws IOException {
return doGet(url, params, DEFAULT_CHARSET);
}
/**
* HTTP GET
*
* @param url
* @param params
* @param charset UTF-8, GBK, GB2312
* @return
*/
public static String doGet(String url, Map<String, String> params, String charset) throws IOException {
HttpURLConnection conn = null;
String rsp = null;
try {
String ctype = "application/x-www-form-urlencoded;charset=" + charset;
String query = buildQuery(params, charset);
try {
conn = getConnection(buildGetUrl(url, query), METHOD_GET, ctype, null);
} catch (IOException e) {
throw e;
}
try {
rsp = getResponseAsString(conn);
} catch (IOException e) {
throw e;
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
private static HttpURLConnection getConnection(URL url, String method, String ctype, Map<String, String> headerMap) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection connHttps = (HttpsURLConnection) conn;
if (ignoreSSLCheck) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{new TrustAllTrustManager()}, new SecureRandom());
connHttps.setSSLSocketFactory(ctx.getSocketFactory());
connHttps.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
} catch (Exception e) {
throw new IOException(e);
}
} else {
try {
//SSLContext ctx = SSLContext.getInstance("TLS");
//ctx.init(null, new TrustManager[] { new VerisignTrustManager() }, new SecureRandom());
//connHttps.setSSLSocketFactory(ctx.getSocketFactory());
} catch (Exception e) {
throw new IOException(e);
}
}
conn = connHttps;
}
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "text/xml,text/javascript");
conn.setRequestProperty("User-Agent", "top-sdk-java");
conn.setRequestProperty("Content-Type", ctype);
if (headerMap != null) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return conn;
}
private static URL buildGetUrl(String strUrl, String query) throws IOException {
URL url = new URL(strUrl);
if (isEmpty(query)) {
return url;
}
if (isEmpty(url.getQuery())) {
if (strUrl.endsWith("?")) {
strUrl = strUrl + query;
} else {
strUrl = strUrl + "?" + query;
}
} else {
if (strUrl.endsWith("&")) {
strUrl = strUrl + query;
} else {
strUrl = strUrl + "&" + query;
}
}
return new URL(strUrl);
}
public static String buildQuery(Map<String, String> params, String charset) throws IOException {
if (params == null || params.isEmpty()) {
return null;
}
StringBuilder query = new StringBuilder();
Set<Map.Entry<String, String>> entries = params.entrySet();
boolean hasParam = false;
for (Map.Entry<String, String> entry : entries) {
String name = entry.getKey();
String value = entry.getValue();
// 忽略参数名或参数值为空的参数
if (areNotEmpty(name, value)) {
if (hasParam) {
query.append("&");
} else {
hasParam = true;
}
query.append(name).append("=").append(URLEncoder.encode(value, charset));
}
}
return query.toString();
}
public static boolean isEmpty(String value) {
int strLen;
if (value == null || (strLen = value.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(value.charAt(i)) == false)) {
return false;
}
}
return true;
}
/**
*
*/
public static boolean areNotEmpty(String... values) {
boolean result = true;
if (values == null || values.length == 0) {
result = false;
} else {
for (String value : values) {
result &= !isEmpty(value);
}
}
return result;
}
protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsString(conn.getInputStream(), charset);
} else {
String msg = getStreamAsString(es, charset);
if (isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
}
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
Reader reader = new InputStreamReader(stream, charset);
StringBuilder response = new StringBuilder();
final char[] buff = new char[1024];
int read = 0;
while ((read = reader.read(buff)) > 0) {
response.append(buff, 0, read);
}
return response.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
private static String getResponseCharset(String ctype) {
String charset = DEFAULT_CHARSET;
if (!isEmpty(ctype)) {
String[] params = ctype.split(";");
for (String param : params) {
param = param.trim();
if (param.startsWith("charset")) {
String[] pair = param.split("=", 2);
if (pair.length == 2) {
if (!isEmpty(pair[1])) {
charset = pair[1].trim();
}
}
break;
}
}
}
return charset;
}
/**
* 使UTF-8
*
* @param value
* @return
*/
public static String decode(String value) {
return decode(value, DEFAULT_CHARSET);
}
/**
* 使UTF-8
*
* @param value
* @return
*/
public static String encode(String value) {
return encode(value, DEFAULT_CHARSET);
}
/**
* 使
*
* @param value
* @param charset
* @return
*/
public static String decode(String value, String charset) {
String result = null;
if (!isEmpty(value)) {
try {
result = URLDecoder.decode(value, charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return result;
}
/**
* 使
*
* @param value
* @param charset
* @return
*/
public static String encode(String value, String charset) {
String result = null;
if (!isEmpty(value)) {
try {
result = URLEncoder.encode(value, charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return result;
}
private static Map<String, String> getParamsFromUrl(String url) {
Map<String, String> map = null;
if (url != null && url.indexOf('?') != -1) {
map = splitUrlQuery(url.substring(url.indexOf('?') + 1));
}
if (map == null) {
map = new HashMap<String, String>();
}
return map;
}
/**
* URL
*
* @param query URL
* @return
*/
public static Map<String, String> splitUrlQuery(String query) {
Map<String, String> result = new HashMap<String, String>();
String[] pairs = query.split("&");
if (pairs != null && pairs.length > 0) {
for (String pair : pairs) {
String[] param = pair.split("=", 2);
if (param != null && param.length == 2) {
result.put(param[0], param[1]);
}
}
}
return result;
}
}

@ -1,18 +0,0 @@
package xyz.wbsite.frame.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DictValidator.class)
public @interface Dict {
String message() default "字典项错误";
String name() default "";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

@ -1,36 +0,0 @@
package xyz.wbsite.frame.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
public class DictValidator implements ConstraintValidator<Dict, String> {
private String name;
@Override
public void initialize(Dict constraint) {
name = constraint.name();
}
@Override
public boolean isValid(String o, ConstraintValidatorContext constraintValidatorContext) {
if (null == o) {
return true;
} else if (name == null) {
constraintValidatorContext.disableDefaultConstraintViolation();
constraintValidatorContext.buildConstraintViolationWithTemplate("字典名称为空").addConstraintViolation();
return false;
} else {
// name 字典名称
HashSet<String> codeSet = new HashSet();
if (codeSet.contains(o)) {
return true;
} else {
constraintValidatorContext.disableDefaultConstraintViolation();
constraintValidatorContext.buildConstraintViolationWithTemplate("非法的字典[" + name + "]值").addConstraintViolation();
return false;
}
}
}
}

@ -1,110 +0,0 @@
package xyz.wbsite.module.admin.ent;
import com.fasterxml.jackson.annotation.JsonFormat;
import xyz.wbsite.wsqlite.anonation.TableField;
import java.util.Date;
/**
* MAPPING -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class Mapping {
/**
* ID -
*/
@TableField
private Long id;
@TableField
private String servicePort;
@TableField
private String name;
@TableField
private String context;
@TableField
private String type;
@TableField
private String location;
@TableField
private String bz;
@TableField
private Date createTime;
@TableField
private boolean isDeleted;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getServicePort() {
return servicePort;
}
public void setServicePort(String servicePort) {
this.servicePort = servicePort;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean deleted) {
isDeleted = deleted;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
}

@ -1,58 +0,0 @@
package xyz.wbsite.module.admin.mgr;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import java.io.*;
public class FreeMarkerManager {
private FreeMarkerConfigurer freeMarkerConfigurer;
public FreeMarkerManager() {
freeMarkerConfigurer = new FreeMarkerConfigurer();
// 初始化一些配置
Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setNumberFormat("0.##");
MultiTemplateLoader multiTemplateLoader = new MultiTemplateLoader(new TemplateLoader[]{
new ClassTemplateLoader(ClassUtils.getDefaultClassLoader(), "/modules"),
});
cfg.setTemplateLoader(multiTemplateLoader);
freeMarkerConfigurer.setConfiguration(cfg);
}
public void outputTemp(File outfile, String template, Object model) {
try {
if (!outfile.exists()) {
outfile.createNewFile();
}
//获取连接
Configuration configuration = freeMarkerConfigurer.getConfiguration();
//设置编码
configuration.setDefaultEncoding("UTF-8");
//获取ftl,由于已经在配置文件中配置了路径所以在这里直接写模板名称就可以
Template temp = configuration.getTemplate(template);
//输出文件路径
Writer wr = new OutputStreamWriter(new FileOutputStream(outfile),"UTF-8");
//写入
temp.process(model, wr);
//关闭流
wr.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
}
}

@ -1,60 +0,0 @@
package xyz.wbsite.module.admin.mgr;
import com.example.module.admin.req.*;
import com.example.module.admin.rsp.*;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.module.admin.req.MappingCreateRequest;
import xyz.wbsite.module.admin.req.MappingDeleteRequest;
import xyz.wbsite.module.admin.req.MappingFindRequest;
import xyz.wbsite.module.admin.req.MappingUpdateRequest;
import xyz.wbsite.module.admin.rsp.MappingCreateResponse;
import xyz.wbsite.module.admin.rsp.MappingDeleteResponse;
import xyz.wbsite.module.admin.rsp.MappingFindResponse;
import xyz.wbsite.module.admin.rsp.MappingUpdateResponse;
/**
*
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public interface MappingManager {
/**
*
*
* @param request
* @param token
* @return
*/
MappingCreateResponse create(MappingCreateRequest request, Token token);
/**
*
*
* @param request
* @param token
* @return
*/
MappingDeleteResponse delete(MappingDeleteRequest request, Token token);
/**
*
*
* @param request
* @param token
* @return
*/
MappingUpdateResponse update(MappingUpdateRequest request, Token token);
/**
*
*
* @param request
* @param token
* @return
*/
MappingFindResponse find(MappingFindRequest request, Token token);
}

@ -1,166 +0,0 @@
package xyz.wbsite.module.admin.mgr;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.frame.utils.IDgenerator;
import xyz.wbsite.frame.utils.MapperUtil;
import xyz.wbsite.frame.utils.ValidationUtil;
import xyz.wbsite.module.admin.ent.Mapping;
import xyz.wbsite.module.admin.req.MappingCreateRequest;
import xyz.wbsite.module.admin.req.MappingDeleteRequest;
import xyz.wbsite.module.admin.req.MappingFindRequest;
import xyz.wbsite.module.admin.req.MappingUpdateRequest;
import xyz.wbsite.module.admin.rsp.MappingCreateResponse;
import xyz.wbsite.module.admin.rsp.MappingDeleteResponse;
import xyz.wbsite.module.admin.rsp.MappingFindResponse;
import xyz.wbsite.module.admin.rsp.MappingUpdateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.wbsite.wsqlite.ObjectClient;
import xyz.wbsite.wsqlite.Where;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
/**
* MAPPING -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
@Service
public class MappingManagerImpl implements MappingManager {
@Autowired
private ObjectClient objectClient;
/**
*
*
* @param request
* @param token
* @return
*/
public MappingCreateResponse create(MappingCreateRequest request, Token token) {
MappingCreateResponse response = new MappingCreateResponse();
ValidationUtil.validate(request, response);
if (response.hasError()) {
return response;
}
try {
Where where = Where.builder().eq("SERVICEPORT", request.getServicePort()).eq("CONTEXT", request.getContext()).build();
List<Mapping> select = objectClient.select(Mapping.class, where, 1, 0);
if (select.size() > 0) {
response.addError(ErrorType.BUSINESS_ERROR, request.getServicePort() + ":" + request.getContext() + "已经被占用");
return response;
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
long id = IDgenerator.nextId();
Mapping entity = MapperUtil.map(request, Mapping.class);
entity.setId(id);
entity.setCreateTime(new Date());
try {
int insert = objectClient.insert(Mapping.class, entity);
if (insert != 1) {
response.addError(ErrorType.BUSINESS_ERROR, "新增错误");
return response;
}
response.setId(id);
} catch (SQLException | ClassNotFoundException e) {
response.addError(ErrorType.BUSINESS_ERROR, "新增错误");
}
response.setId(id);
return response;
}
/**
*
*
* @param request
* @param token
* @return
*/
public MappingDeleteResponse delete(MappingDeleteRequest request, Token token) {
MappingDeleteResponse response = new MappingDeleteResponse();
ValidationUtil.validate(request, response);
if (response.hasError()) {
return response;
}
try {
int update = objectClient.delete(Mapping.class, Where.builder().eq("ID", request.getId()).build());
response.setResult((long) update);
} catch (SQLException | ClassNotFoundException e) {
response.addError(ErrorType.BUSINESS_ERROR, "删除错误");
}
return response;
}
/**
*
*
* @param request
* @param token
* @return
*/
public MappingUpdateResponse update(MappingUpdateRequest request, Token token) {
MappingUpdateResponse response = new MappingUpdateResponse();
ValidationUtil.validate(request, response);
if (response.hasError()) {
return response;
}
Mapping mapping = MapperUtil.map(request, Mapping.class);
try {
int update = objectClient.update(Mapping.class, mapping, Where.builder().eq("ID", request.getId()).build());
response.setResult((long) update);
} catch (SQLException | ClassNotFoundException e) {
response.addError(ErrorType.BUSINESS_ERROR, "更新错误");
}
return response;
}
/**
*
*
* @param request
* @param token
* @return
*/
public MappingFindResponse find(MappingFindRequest request, Token token) {
MappingFindResponse response = new MappingFindResponse();
ValidationUtil.validate(request, response);
if (response.hasError()) {
return response;
}
try {
List<Mapping> select = objectClient.select(Mapping.class, Where.builder().build(), 1, 0);
response.setResult(select);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
response.addError(ErrorType.BUSINESS_ERROR, "Sqlite错误");
}
return response;
}
}

@ -1,37 +0,0 @@
package xyz.wbsite.module.admin.req;
import xyz.wbsite.frame.base.BaseRequest;
import javax.validation.constraints.NotNull;
/**
* MappingCreateRequest -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class LoginRequest extends BaseRequest {
@NotNull(message = "用户名不能为空")
private String username;
@NotNull(message = "密码不能为空")
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

@ -1,83 +0,0 @@
package xyz.wbsite.module.admin.req;
import xyz.wbsite.frame.base.BaseRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
/**
* MappingCreateRequest -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class MappingCreateRequest extends BaseRequest {
@NotBlank(message = "映射名称不能为空")
private String name;
@NotBlank(message = "服务端口不能为空")
@Pattern(regexp = "^[0-9]*$", message = "服务端口必须是数字")
private String servicePort;
@NotBlank(message = "映射路径不能为空")
@Pattern(regexp = "/|/[a-zA-Z][a-zA-Z0-9_]*/", message = "映射路径须是/开始结束中间为字母数字及_组合")
private String context;
@NotBlank(message = "映射类型不能为空")
private String type;
@NotBlank(message = "映射地址不能为空")
private String location;
private String bz;
public String getServicePort() {
return servicePort;
}
public void setServicePort(String servicePort) {
this.servicePort = servicePort;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContext() {
return context;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setContext(String context) {
this.context = context;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
}

@ -1,28 +0,0 @@
package xyz.wbsite.module.admin.req;
import xyz.wbsite.frame.base.BaseUpdateRequest;
import javax.validation.constraints.NotNull;
/**
* MappingDeleteRequest -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class MappingDeleteRequest extends BaseUpdateRequest {
/**
*
*/
@NotNull(message = "主键不能为空")
private long id;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
}

@ -1,23 +0,0 @@
package xyz.wbsite.module.admin.req;
import xyz.wbsite.frame.base.BaseFindRequest;
/**
* MappingRequest -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class MappingFindRequest extends BaseFindRequest {
private String search;
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
}

@ -1,95 +0,0 @@
package xyz.wbsite.module.admin.req;
import xyz.wbsite.frame.base.BaseUpdateRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
/**
* MappingUpdateRequest -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class MappingUpdateRequest extends BaseUpdateRequest {
@NotNull(message = "主键不能为NULL")
private Long id;
@NotBlank(message = "服务端口不能为空")
private String servicePort;
@NotBlank(message = "映射名称不能为空")
private String name;
@NotBlank(message = "映射路径不能为空")
@Pattern(regexp = "/|/[a-zA-Z][a-zA-Z0-9_]*/", message = "映射路径须是/开始结束中间为字母数字及_组合")
private String context;
@NotBlank(message = "映射类型不能为空")
private String type;
@NotBlank(message = "映射地址不能为空")
private String location;
private String bz;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContext() {
return context;
}
public void setContext(String context) {
this.context = context;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBz() {
return bz;
}
public void setBz(String bz) {
this.bz = bz;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getServicePort() {
return servicePort;
}
public void setServicePort(String servicePort) {
this.servicePort = servicePort;
}
}

@ -1,9 +0,0 @@
package xyz.wbsite.module.admin.rsp;
import xyz.wbsite.frame.base.BaseResponse;
public class LoginResponse extends BaseResponse {
}

@ -1,26 +0,0 @@
package xyz.wbsite.module.admin.rsp;
import xyz.wbsite.frame.base.BaseResponse;
/**
* MappingCreateResponse -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class MappingCreateResponse extends BaseResponse {
/**
* ID
*/
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

@ -1,26 +0,0 @@
package xyz.wbsite.module.admin.rsp;
import xyz.wbsite.frame.base.BaseResponse;
/**
* MappingDeleteResponse -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class MappingDeleteResponse extends BaseResponse {
/**
*
*/
private Long result;
public Long getResult() {
return this.result;
}
public void setResult(Long result) {
this.result = result;
}
}

@ -1,15 +0,0 @@
package xyz.wbsite.module.admin.rsp;
import xyz.wbsite.frame.base.BaseFindResponse;
import xyz.wbsite.module.admin.ent.Mapping;
/**
* MappingFindResponse -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class MappingFindResponse extends BaseFindResponse<Mapping> {
}

@ -1,26 +0,0 @@
package xyz.wbsite.module.admin.rsp;
import xyz.wbsite.frame.base.BaseResponse;
/**
* MappingUpdateResponse -
*
* @author author
* @version 0.0.1
* @since 2019-09-28
*/
public class MappingUpdateResponse extends BaseResponse {
/**
*
*/
private Long result;
public Long getResult() {
return this.result;
}
public void setResult(Long result) {
this.result = result;
}
}

@ -1,50 +0,0 @@
# 开发环境
server.port=8888
server.servlet.context-path=/
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
spring.application.name=nginx-admin
spring.main.banner-mode=OFF
spring.devtools.restart.enabled=true
# 编码配置
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
# 根路径、欢迎页
web.welcome.page=/mapping.htm
# 不需要验证授权, 或该请求有自己的验证机制
web.url.auth.excluded=/favicon.ico,/static/**,/api,/login.htm,/sse/**
# jackson 相关配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.default-property-inclusion=use_defaults
spring.jackson.mapper.sort-properties-alphabetically=true
spring.jackson.deserialization.fail-on-unknown-properties=false
# freemarker
spring.freemarker.enabled=true
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.settings.template_update_delay=1
spring.freemarker.settings.locale=zh_CN
spring.freemarker.settings.datetime_format=yyyy-MM-dd HH:mm:ss
spring.freemarker.settings.date_format=yyyy-MM-dd
spring.freemarker.settings.number_format=#.##
spring.freemarker.settings.classic_compatible=true
spring.freemarker.settings.whitespace_stripping=true
spring.freemarker.settings.url_escaping_charset=utf-8
# 文件上传配置
spring.servlet.multipart.resolveLazily=false
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
dbpath=
nginx-path=
admin.username=admin
admin.password=admin
mapping.default.port=80

@ -1,26 +0,0 @@
${AnsiColor.BRIGHT_YELLOW}
/////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
/////////////////////////////////////////////////////////
佛祖保佑 永无BUG
:: Spring Boot :: ${spring-boot.formatted-version} (${spring.profiles.active})

@ -1,3 +0,0 @@
@echo off
cd %cd%
start java -Dfile.encoding=UTF-8 -jar EXAMPLE-WEB-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev

@ -1,3 +0,0 @@
@echo off
cd %cd%
start java -Dfile.encoding=UTF-8 -jar EXAMPLE-WEB-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

@ -1,687 +0,0 @@
* {
-webkit-box-sizing: border-box;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
margin: 0;
padding: 0;
font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
html {
line-height: 1.15;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%
}
body {
margin: 0;
font-size: 12px;
line-height: 1.5;
color: #515a6e;
background-color: #fff;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale
}
html, body {
width: 100%;
height: 100%;
}
article, aside, footer, header, nav, section {
display: block
}
h1 {
font-size: 2em;
margin: .67em 0
}
pre {
font-family: monospace, monospace;
font-size: 1em
}
button, input, optgroup, select, textarea {
font-family: sans-serif;
font-size: 100%;
line-height: 1.15;
margin: 0
}
button, select {
text-transform: none
}
[type=reset], [type=submit], button, html [type=button] {
-webkit-appearance: button
}
[type=button]::-moz-focus-inner, [type=reset]::-moz-focus-inner, [type=submit]::-moz-focus-inner, button::-moz-focus-inner {
border-style: none;
padding: 0
}
[type=button]:-moz-focusring, [type=reset]:-moz-focusring, [type=submit]:-moz-focusring, button:-moz-focusring {
outline: 1px dotted ButtonText
}
fieldset {
border: 1px solid silver;
margin: 0 2px;
padding: .35em .625em .75em
}
legend {
-webkit-box-sizing: border-box;
box-sizing: border-box;
color: inherit;
display: table;
max-width: 100%;
padding: 0;
white-space: normal
}
progress {
display: inline-block;
vertical-align: baseline
}
textarea {
overflow: auto;
resize: vertical
}
[type=checkbox], [type=radio] {
-webkit-box-sizing: border-box;
box-sizing: border-box;
padding: 0
}
[type=number]::-webkit-inner-spin-button, [type=number]::-webkit-outer-spin-button {
height: auto
}
[type=search] {
-webkit-appearance: textfield;
outline-offset: -2px
}
[type=search]::-webkit-search-cancel-button, [type=search]::-webkit-search-decoration {
-webkit-appearance: none
}
::-webkit-file-upload-button {
-webkit-appearance: button;
font: inherit
}
details, menu {
display: block
}
summary {
display: list-item
}
canvas {
display: inline-block
}
template {
display: none
}
[hidden] {
display: none
}
:after, :before {
-webkit-box-sizing: border-box;
box-sizing: border-box
}
a {
text-decoration: none;
outline: 0;
cursor: pointer;
-webkit-transition: color .2s ease;
transition: color .2s ease;
-webkit-text-decoration-skip: objects;
color: #757575;
}
a:active, a:hover {
outline-width: 0
}
a:hover {
opacity: 0.7;
}
a:active {
opacity: 0.9;
}
a:active, a:hover {
outline: 0;
text-decoration: none
}
a[disabled] {
color: #ccc;
cursor: not-allowed;
pointer-events: none
}
code, kbd, pre, samp {
font-family: Consolas, Menlo, Courier, monospace
}
a {
text-decoration: none;
}
/*主标题*/
h1 {
font-size: 20px;
padding: 10px 0px;
margin: 20px 0px 10px 0px;
}
/*标题*/
h2 {
font-size: 18px;
padding: 9px 0px;
margin: 18px 0px 8px 0px;
}
/*小标题*/
h3 {
font-size: 16px;
padding: 8px 0px;
margin: 16px 0px 6px 0px;
}
/*次要标题*/
h4 {
font-size: 14px;
padding: 4px 0px;
margin: 4px 0px 4px 0px;
}
p {
font-size: 14px;
padding: 7px 0px;
color: #545C64;;
}
p.text-indent {
text-indent: 2em
}
/*正文*/
.text-regular {
font-size: 14px;
}
/*正文(小)*/
.text-small {
font-size: 13px
}
/*辅助文字*/
.text-smaller {
font-size: 12px
}
/*中文字体*/
.typo-PingFang {
font-family: PingFang SC
}
.typo-Hiragino {
font-family: Hiragino Sans GB
}
.typo-Microsoft {
font-family: Microsoft YaHei
}
/*英文/数字字体*/
.typo-Helvetica-Neue {
font-family: Helvetica Neue
}
.typo-Helvetica {
font-family: Helvetica
}
.typo-Arial {
font-family: Arial
}
.bg-blue {
background-color: #409eff
}
.bg-success {
background-color: #67c23a
}
.bg-warning {
background-color: #e6a23c
}
.bg-danger {
background-color: #f56c6c
}
.bg-info {
background-color: #909399
}
.text-color-primary {
color: #303133
}
.text-color-regular {
color: #606266
}
.text-color-secondary {
color: #909399
}
.text-color-placeholder {
color: #c0c4cc
}
.bg-border-base {
background-color: #dcdfe6
}
.bg-border-light {
background-color: #e4e7ed
}
.bg-border-lighter {
background-color: #ebeef5
}
.bg-border-extra-light {
background-color: #f2f6fc
}
[class*="bg-border-"] {
color: #303133
}
code {
background-color: #f9fafc;
padding: 0 4px;
border: 1px solid #eaeefb;
border-radius: 4px;
display: inline-block;
}
.remarks {
font-size: 12px;
color: #909399
}
.table {
display: table;
}
.table-cell {
display: table-cell;
}
.table-cell.center {
text-align: center;
vertical-align: middle;
}
.table-cell.v-center {
vertical-align: middle;
}
.table-cell.h-center {
text-align: center;
}
.table-cell.right {
text-align: right;
}
.table-cell.left {
text-align: left;
}
.table-cell.top {
vertical-align: top;
}
.table-cell.bottom {
vertical-align: bottom;
}
.m-t-10 {
margin-top: 10px;
}
.m-t-20 {
margin-top: 20px;
}
.m-t-30 {
margin-top: 30px;
}
.m-t-40 {
margin-top: 40px;
}
.m-t-50 {
margin-top: 50px;
}
.center{
text-align: center;
}
.full {
width: 100%;
height: 100%;
}
.nowrap {
white-space: nowrap;
overflow: hidden;
word-break: keep-all;
}
[v-cloak] {
display: none;
}
/* 可以设置不同的进入和离开动画 */
/* 设置持续时间和动画函数 */
.left-in-right-out-enter-active, .left-in-right-out-leave-active {
transition: all 0.3s linear;
position: absolute;
}
.left-in-right-out-enter
/* .slide-fade-leave-active for below version 2.1.8 */
{
transform: translateX(-100%);
opacity: 0;
}
.left-in-right-out-leave-to
/* .slide-fade-leave-active for below version 2.1.8 */
{
transform: translateX(100%);
opacity: 0;
}
.right-in-left-out-enter-active, .right-in-left-out-leave-active {
transition: all .3s linear;
position: absolute;
}
.right-in-left-out-enter {
transform: translateX(100%);
}
.right-in-left-out-leave-to {
transform: translateX(-100%);
}
.el-switch__input:focus ~ .el-switch__core {
position: relative;
box-sizing: border-box;
outline: none !important;
}
.row {
position: relative;
box-sizing: border-box;
}
[class*=col-] {
float: left;
box-sizing: border-box;
}
.col-1 {
width: 4.16667%;
}
.col-2 {
width: 8.33333%;
}
.col-3 {
width: 12.5%;
}
.col-4 {
width: 16.66667%;
}
.col-5 {
width: 20.83333%;
}
.col-6 {
width: 25%;
}
.col-7 {
width: 29.16667%;
}
.col-8 {
width: 33.33333%;
}
.col-9 {
width: 37.5%;
}
.col-10 {
width: 41.66667%;
}
.col-11 {
width: 45.83333%;
}
.col-12 {
width: 50%;
}
.col-13 {
width: 54.16667%;
}
.col-14 {
width: 58.33333%;
}
.col-15 {
width: 62.5%;
}
.col-16 {
width: 66.66667%;
}
.col-17 {
width: 70.83333%;
}
.col-18 {
width: 75%;
}
.col-19 {
width: 79.16667%;
}
.col-20 {
width: 83.33333%;
}
.col-21 {
width: 87.5%;
}
.col-22 {
width: 91.66667%;
}
.col-23 {
width: 95.83333%;
}
.col-24 {
width: 100%;
}
.page_list {
display: flex;
}
.page_list a {
display: inline-block;
height: 35px;
width: 35px;
line-height: 35px;
text-align: center;
cursor: pointer;
background-color: #2a2a2a;
color: #ffffff;
}
.page_list a.disabled {
opacity: 0.7;
}
.page_list a.current {
background-color: #16C0F8;
color: #ffffff;
}
.page_list a:hover {
background-color: #16C0F8;
color: #ffffff;
}
.page_list a.disabled:hover {
background-color: #373737;
color: #ffffff;
}
.page_list a.top_page,
.page_list a.page_prev,
.page_list a.page_next,
.page_list a.end_page {
width: 55px;
padding: 0px 5px;
}
.page_list p{
padding: 0px 20px;
line-height: 35px;
}
::-webkit-scrollbar {
width: 7px;
height: 7px;
background-color: #ffffff;
}
::-webkit-scrollbar-thumb {
background-color: #16C0F8;
}
::-webkit-scrollbar-track {
background-color: #ffffff;
}
.el-scrollbar.hidden_x > .el-scrollbar__wrap {
overflow-x: hidden !important;
}
.el-scrollbar.hidden_x > .el-scrollbar__wrap > .el-scrollbar__view {
height: 100%;
}
.el-menu--horizontal {
border-bottom: solid 0px #e6e6e6 !important;
}
.el-message {
min-width: 100px;
padding: 10px 60px 10px 20px;
background-color: #ffffff;
box-shadow: 0 1px 6px rgba(0, 0, 0, .2);
}
.loading-bar {
width: 100%;
padding: 0px;
top: 0px;
box-shadow: 0px 0px 0px 0px;
border: 0px;
}
.loading-bar .el-message__content {
display: block;
width: 100%;
height: 2px;
}
.loading-bar .el-message__content .bar {
display: block;
height: 2px;
background-color: #2d8cf0;
}
.loading-bar .el-message__content .bar.error {
background-color: #ff1a0e;
}
/* 带有固定title布局,title保持固定*/
.wb-layout-title-fix {
width: 100%;
height: 100%;
overflow: hidden;
}
.wb-layout-title-fix > .wb-head {
height: 60px;
overflow: hidden;
}
.wb-layout-title-fix > .wb-body {
height: calc(100% - 60px);
}
/* 保持页脚绝对底部,当内容足够或高于屏幕,会自动将页面撑开,底部依旧保持在底部*/
.wb-layout-foot-absolute {
position: relative;
width: 100%;
height: auto;
min-height: 100%;
}
.wb-layout-foot-absolute > .wb-body {
padding-bottom: 50px;
}
.wb-layout-foot-absolute > .wb-foot {
position: absolute;
bottom: 0;
left: 0;
height: 50px;
width: 100%;
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

@ -1,161 +0,0 @@
//创建axios实例
instance = axios.create({
method: 'post',
timeout: 30000,
});
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
nav.bar.show();
if (config.url == '/upload') {
nav.tip.show("上传中 ...");
} else {
nav.tip.show();
}
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
instance.interceptors.response.use(function (response) {
// 对响应数据做点什么
nav.tip.close();
try {//确保服务器正确返回Json
if(response.data.errors.length > 0){
console.error(response.data.errors)
}
nav.bar.finish();
}catch (e){
nav.bar.error();
response.data = {errors: [{message: '服务器错误'}]};
}
return response;
}, function (error) {
// 对响应错误做点什么,保准化返回结果
nav.tip.close();
nav.bar.error();
const rsp = {errors: []};
if (!error.response) {
rsp.errors.push({message: error.message});
} else {
switch (error.response.status) {
case 401:
rsp.errors.push({message: "未授权,请登录(401)"});
break
case 403:
rsp.errors.push({message: "拒绝访问(403)"});
break
case 404:
rsp.errors.push({message: "请求地址错误(404)"});
break
case 408:
rsp.errors.push({message: "请求超时(408)"});
break
case 500:
rsp.errors.push({message: "服务器内部错误(500)"});
break
case 501:
rsp.errors.push({message: "服务未实现(501)"});
break
default:
rsp.errors.push({message: "请求错误(" + error.response.status + ")"});
break
}
}
return Promise.reject(rsp);
});
jsonRequest = function (config) {
return instance.request({
params: {
method: config.method
},
url: '/ajax',
headers: {'Content-Type': 'text/plain'},
data: config.data
}).then(function (response) {
return Promise.resolve(response.data);
}, function (response) {
return Promise.resolve(response);
})
};
fileRequest = function (config) {
return instance.request({
url: '/upload',
data: config.data,
headers: {'Content-Type': 'multipart/form-data'},
onUploadProgress: function (progressEvent) {
var complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
nav.tip.show("上传中(" + complete + ")")
}
}).then(function (response) {
return Promise.resolve(response.data);
}, function (response) {
return Promise.resolve(response);
})
};
window.ajax = {
login: function (data) {
return jsonRequest({
method: "ajax.login",
data: data
})
},
nginxStart: function (data) {
return jsonRequest({
method: "nginx.start",
data: data
})
},
nginxStop: function (data) {
return jsonRequest({
method: "nginx.stop",
data: data
})
},
nginxReload: function (data) {
return jsonRequest({
method: "nginx.reload",
data: data
})
},
fileUpload: function (file) {
var fd = new FormData();
fd.append("file", file);
return fileRequest({
data: fd
})
},
mappingFind: function (data) {
return jsonRequest({
method:"ajax.admin.mapping.find",
data: JSON.stringify(data),
})
},
mappingCreate: function (data) {
return jsonRequest({
method:"ajax.admin.mapping.create",
data: JSON.stringify(data),
})
},
mappingDelete: function (data) {
return jsonRequest({
method:"ajax.admin.mapping.delete",
data: JSON.stringify(data),
})
},
mappingUpdate: function (data) {
return jsonRequest({
method:"ajax.admin.mapping.update",
data: JSON.stringify(data),
})
},
configFlush: function(data) {
return jsonRequest({
method:"ajax.admin.config.flush",
data: JSON.stringify(data),
})
},
}

@ -1,249 +0,0 @@
<head>
<style>
body {
margin: 0px;
padding: 0px;
background-color: #f2f2f2;
}
.box {
width: 700px;
margin: 50px auto;
display: table;
}
.container {
display: table-cell;
vertical-align: middle;
}
.code {
font-weight: 500;
top: 100px;
left: 400px;
text-align: center;
width: 300px;
margin-top: 30px;
margin-bottom: 10px;
font-family: 'Varela Round', sans-serif;
font-size: 60px;
color: #6bbee0;
letter-spacing: 3px;
text-shadow: 0 0 5px #78d0ec;
animation: flux 2s linear infinite;
}
.message {
font-family: 'Poppins', sans-serif;
font-size: 20px;
color: #505050;
font-weight: 500;
}
.message2 {
font-family: 'Poppins', sans-serif;
font-size: 15px;
color: #505050;
font-weight: 300;
width: 360px;
white-space: nowrap;
}
.door-frame {
height: 340px;
width: 220px;
border-radius: 90px 90px 0 0;
background-color: #8594A5;
display: flex;
justify-content: center;
align-items: center;
}
.door {
height: 280px;
width: 170px;
border-radius: 70px 70px 0 0;
background-color: #A0AEC0;
}
.eye {
top: 15px;
left: 25px;
height: 5px;
width: 15px;
border-radius: 50%;
background-color: white;
animation: eye 7s ease-in-out infinite;
position: absolute;
}
.eye2 {
left: 65px;
}
.window {
height: 40px;
width: 130px;
background-color: #1C2127;
border-radius: 3px;
margin: 80px auto;
position: relative;
}
.leaf {
height: 40px;
width: 130px;
background-color: #8594A5;
border-radius: 3px;
margin: 80px auto;
animation: leaf 7s infinite;
transform-origin: right;
}
.handle {
height: 8px;
width: 30px;
border-radius: 4px;
background-color: #EBF3FC;
position: absolute;
margin-top: 195px;
margin-left: 30px;
}
.rectangle {
height: 60px;
width: 20px;
background-color: #CBD8E6;
border-radius: 4px;
position: absolute;
margin-top: 160px;
margin-left: 20px;
}
.message3 {
margin-top: 20px;
font-size: 12px;
}
a.login {
font-size: 15px;
text-decoration: none;
color: rgba(0, 130, 192, 0.69);
}
a.login:hover {
color: #0074c0;
}
@keyframes leaf {
0% {
transform: scaleX(1);
}
5% {
transform: scaleX(0.2);
}
70% {
transform: scaleX(0.2);
}
75% {
transform: scaleX(1);
}
100% {
transform: scaleX(1);
}
}
@keyframes eye {
0% {
opacity: 0;
transform: translateX(0)
}
5% {
opacity: 0;
}
15% {
opacity: 1;
transform: translateX(0)
}
20% {
transform: translateX(15px)
}
35% {
transform: translateX(15px)
}
40% {
transform: translateX(-15px)
}
60% {
transform: translateX(-15px)
}
65% {
transform: translateX(0)
}
}
@keyframes flux {
0%,
100% {
text-shadow: 0 0 5px #00FFC6, 0 0 15px #00FFC6, 0 0 50px #00FFC6, 0 0 50px #00FFC6, 0 0 2px #B9FFE8, 2px 2px 3px #12E29C;
color: #4BFFEF;
}
50% {
text-shadow: 0 0 3px #00B58D, 0 0 7px #00B58D, 0 0 25px #00B58D, 0 0 25px #00B58D, 0 0 2px #00B58D, 2px 2px 3px #006A60;
color: #63D3AE;
}
}
</style>
<script>
window.onload = function () {
var count = 0;
function go() {
if (count > 0) {
var e = document.getElementById("timer");
e.innerHTML = count + " 秒后自动跳转登录页"
count--;
} else {
location.href = '${Uri.getUrl("/login.htm")}';
}
}
setInterval(go, 1000);
};
</script>
</head>
<body>
<div class="box">
<div class="container">
<div class="door-frame">
<div class="door">
<div class="rectangle">
</div>
<div class="handle">
</div>
<div class="window">
<div class="eye">
</div>
<div class="eye eye2">
</div>
<div class="leaf">
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="code">403</div>
<div class="message">您没有足够的权限哦!</div>
<div class="message2">您正在试图访问一个没有事先授权的页面.或登录已失效。</div>
<div class="message3" id="timer">5 秒后自动跳转登录页</div>
<a class="login" href="${Uri.getUrl("/login.htm")}">立即跳转</a>
</div>
</div>
</body>

File diff suppressed because it is too large Load Diff

@ -1,40 +0,0 @@
<head>
<style>
html,body{
overflow: hidden;
}
.box{
width: 100%;
height: 100%;
overflow: scroll;
}
.box a{
color: #c38168;
line-height: 18px;
text-decoration: underline;
}
.box::-webkit-scrollbar {/*滚动条整体样式*/
width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
height: 1px;
}
.box::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
border-radius: 10px;
-webkit-box-shadow: inset 0 0 5px rgba(73, 73, 73, 0.2);
background: #828282;
}
.box::-webkit-scrollbar-track {/*滚动条里面轨道*/
-webkit-box-shadow: inset 0 0 5px rgba(125, 125, 125, 0.2);
border-radius: 10px;
background: #EDEDED;
}
</style>
</head>
<body>
<div class="box">
<p>
${msg}
</p>
</div>
</body>

@ -1,5 +0,0 @@
<div style="height: 50px;background-color: #303133">
<center>
<h3 style="color: #ffffff">------------------------------this is footer html------------------------------</h3>
</center>
</div>

@ -1,119 +0,0 @@
<div id="header">
<div class="logo">
<img @click="this.nav.toHome()" src="${Uri.getUrl('/static/img/logo.png')}">
</div>
<a class="home" href="${Uri.getUrl('/')}">Home</a>
<div class="menu">
<ul>
<li>
<a href="${Uri.getUrl('/1')}">首页</a>
</li>
<li>
<a href="${Uri.getUrl('/2')}">工作台</a>
</li>
<li>
<a href="${Uri.getUrl('/3')}">消息中心</a>
</li>
<li>
<a href="${Uri.getUrl('/4')}">关于我</a>
</li>
</ul>
</div>
</div>
<style>
#header {
width: 100%;
height: 50px;
line-height: 50px;
overflow: hidden;
background: #2a2a2a;
box-shadow: 0px 2px 8px 0px;
}
#header .logo {
display: inline-block;
height: 50px;
width: 50px;
margin-left: 10px;
text-align: center;
}
#header .logo img {
width: 50%;
height: 50%;
vertical-align: middle;
}
.home {
display: inline-block;
color: #ffffff;
font-weight: bold;
transition: all 0.3s;
}
.home:hover {
color: #ffffff;
transform: translate(2px);
}
#header .menu {
display: inline-block;
float: right;
}
#header .menu ul {
display: inline-block;
}
#header .menu ul li {
display: inline-block;
vertical-align: top;
}
#header .menu ul li a {
color: #ffffff;
display: inline-block;
text-align: center;
position: relative;
margin: 0px 15px;
height: 50px;
}
#header .menu ul li a:after {
content: "";
display: inline-block;
background: #ffffff;
width: 0%;
height: 2px;
position: absolute;
bottom: 2px;
left: 50%;
transition: all 0.3s;
}
#header .menu ul li a img {
margin-top: 8px;
height: 32px;
}
#header .menu ul li a:hover:after {
width: 100%;
left: 0%;
}
#header .tx {
display: inline-block;
float: right;
height: 50px;
width: 50px;
margin-left: 20px;
}
#header .tx img {
width: 50%;
height: 50%;
vertical-align: middle;
}
</style>

@ -1,63 +0,0 @@
<#macro print items >
<#nested>:
<#list items as item>
<a>${item}</a>
</#list>
</#macro>
<#--
参数说明:
pageNumber当前的页码
pageSize页码大小
totalCount总数
showPages显示的页码个数
callback回调函数
-->
<#macro page pageNumber pageSize totalCount showPages callback>
<#if totalCount gt 0>
<div class="page_list">
<#assign totalPage = 0/>
<#assign totalPage = (totalCount/pageSize)?ceiling/>
<#if pageNumber==1>
<a href="javascript:;" class="top_page disabled">首页</a>
<a href="javascript:;" class="page_prev disabled">上一页</a>
</#if>
<#if pageNumber!=1>
<a href="javascript:${callback+'('+1+')'};" class="top_page">首页</a>
<a href="javascript:${callback+'('+(pageNumber-1)+')'};" class="page_prev">上一页</a>
</#if>
<#if pageNumber-showPages/2 gt 0>
<#assign start = pageNumber-(showPages-1)/2/>
<#if showPages gt totalPage>
<#assign start = 1/>
</#if>
<#else>
<#assign start = 1/>
</#if>
<#if totalPage gt showPages>
<#assign end = (start+showPages-1)/>
<#if end gt totalPage>
<#assign start = totalPage-showPages+1/>
<#assign end = totalPage/>
</#if>
<#else>
<#assign end = totalPage/>
</#if>
<#assign pages=start..end/>
<#list pages as page>
<#if page==pageNumber>
<a href="javascript:${callback+'('+page+')'};" class="current">${page}</a>
<#else>
<a href="javascript:${callback+'('+page+')'};">${page}</a>
</#if>
</#list>
<#if pageNumber==totalPage>
<a href="javascript:;" class="page_next disabled">下一页</a>
<a href="javascript:;" class="end_page disabled">尾页</a>
</#if>
<#if pageNumber!=totalPage>
<a href="javascript:${callback+'('+(pageNumber+1)+')'};" class="page_next">下一页</a>
<a href="javascript:${callback+'('+totalPage+')'};" class="end_page">尾页</a>
</#if>
</div>
</#if>
</#macro>

@ -1,160 +0,0 @@
<script>
window.nav = new Vue({
data: {
activeIndex: 'home',
contextPath: '${contextPath?default("")}',
homePath: '${homePath?default("")}',
loadingTip: '',
loadingBar: '',
tip: {
show: function (msg) {
var message = "<i class='el-icon-loading'></i> 正在加载 ..."
if (msg) {
message = "<i class='el-icon-loading'></i> " + msg
}
if (!nav.loadingTip) {
nav.loadingTip = nav.$message({
type: '',
duration: 0,
dangerouslyUseHTMLString: true,
message: message
});
} else {
nav.loadingTip.message = message;
}
},
close: function () {
if (nav.loadingTip) {
nav.loadingTip.close();
nav.loadingTip = '';
}
}
},
bar: {
show: function () {
if (!nav.loadingBar) {
nav.loadingBar = nav.$message({
type: '',
duration: 0,
customClass: 'loading-bar',
dangerouslyUseHTMLString: true,
message: '<i class="bar" style="width: 90%"></i>'
});
} else {
nav.loadingBar.message = '<i class="bar" style="width: 90%"></i>'
}
},
finish: function () {
if (nav.loadingBar) {
nav.loadingBar.message = '<i class="bar" style="width: 100%"></i>'
setTimeout(function(){
if (nav.loadingBar) {
nav.loadingBar.close();
nav.loadingBar = '';
}
},500);
}
},
error: function () {
if (nav.loadingBar) {
nav.loadingBar.message = '<i class="bar error" style="width: 100%"></i>'
setTimeout(function(){
if(nav.loadingBar){
nav.loadingBar.close();
nav.loadingBar = '';
}
},500);
}
}
}
},
methods: {
i: function (message, callback) {
this.$message({
type: "info",
showClose: true,
message: message,
duration: 1500,
onClose: callback
});
},
e: function (message, callback) {
this.$message({
type: "error",
showClose: true,
message: message,
duration: 1500,
onClose: callback
});
},
w: function (message, callback) {
this.$message({
type: "warning",
showClose: true,
message: message,
duration: 1500,
onClose: callback
});
},
s: function (message, callback) {
this.$message({
type: "success",
showClose: true,
message: message,
duration: 1500,
onClose: callback
});
},
toOpen: function (url) {
nav.tip.show();
var url = url.substring(0, 1) == "/" ? url.substring(1) : url;
$("body").append($("<a id='wb-open' href='" + this.contextPath + "/" + url + "' target='_self' style='dispaly:none;'></a>"))
document.getElementById("wb-open").click();
$("#wb-open").remove();
},
toOpenNew: function (url) {
var url = url.substring(0, 1) == "/" ? url.substring(1) : url;
$("body").append($("<a id='wb-open' href='" + this.contextPath + "/" + url + "' target='_blank' style='dispaly:none;'></a>"))
document.getElementById("wb-open").click();
$("#wb-open").remove();
},
toHome: function () {
nav.tip.show();
location.href = this.contextPath + "/"
},
/**
* 滚动屏蔽至顶部
*/
scrollToTop: function () {
var distance = document.documentElement.scrollTop || document.body.scrollTop;
var step = distance / 10;
(function jump() {
if (distance > 0) {
distance -= step;
window.scrollTo(0, distance);
setTimeout(jump, 10)
}
})();
},
/**
* 控制任一目标滚动到顶部
* select jquery对象
*/
scrollToTop: function (select) {
var distance = $(select).scrollTop();
var step = distance / 10;
(function jump() {
if (distance > 0) {
distance -= step;
$(select).scrollTop(distance);
setTimeout(jump, 10)
} else {
$(select).scrollTop(distance);
}
})();
}
}
});
</script>

@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<#--baseJs-->
<script src="${Uri.getUrl('/static/dist/lib.min.js')}" type="text/javascript"></script>
<#--element-ui-->
<script src="${Uri.getUrl('/static/dist/index.min.js')}" type="text/javascript"></script>
<link href="${Uri.getUrl('/static/dist/index.min.css')}" rel="stylesheet"/>
<#--ajax接口-->
<script src="${Uri.getUrl('/static/js/ajax.js')}" type="text/javascript"></script>
<link href="${Uri.getUrl('/static/css/base.css')}" rel="stylesheet"/>
</head>
<body>
<#include Layout.setControl("macro")/>
<#include Layout.setControl("nav")/>
<#include Layout.setScreen()/>
</body>
</html>

@ -1,15 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<#--baseJs-->
<script src="${Uri.getUrl('/static/dist/lib.min.js')}" type="text/javascript"></script>
<#--element-ui-->
<script src="${Uri.getUrl('/static/dist/index.min.js')}" type="text/javascript"></script>
<link href="${Uri.getUrl('/static/dist/index.min.css')}" rel="stylesheet"/>
</head>
<body>
<#include Layout.setScreen()/>
</body>
</html>

@ -1,19 +0,0 @@
<div id="app" v-cloak>
</div>
<style>
</style>
<script>
var app = new Vue({
el: "#app",
data: {},
methods: {},
filters: {},
created: function () {
},
mounted: function () {
},
watch: {}
})
</script>

File diff suppressed because it is too large Load Diff

@ -1,327 +0,0 @@
<div id="index" v-cloak>
<div id="aside">
<el-menu
:style="{width:(properties.isCollapse?'64px':'200px')}"
:default-active="properties.defaultActive"
@open="handleOpen"
@close="handleClose"
@select="handleSelect"
:unique-opened="properties.uniqueOpened"
:collapse="properties.isCollapse"
:collapse-transition="properties.transition"
background-color="#252a2f"
text-color="#d6d6d6"
active-text-color="#ffd04b">
<el-submenu index="1">
<template slot="title">
<i class="el-icon-setting"></i>
<span>系统设置</span>
</template>
<el-menu-item index="1-1">映射管理</el-menu-item>
</el-submenu>
</el-menu>
</div>
<div id="main">
<div id="head">
<div class="collapseSwitch" @click="collapseSwitch">
<a :class="properties.isCollapse?'reversal':''"><i class="el-icon-s-grid"></i></a>
</div>
<el-link :underline="false" @click="onHome" icon="el-icon-s-home">首页</el-link>
<div class="menu">
<ul>
<li>
<el-link :underline="false" @click="onHome" icon="el-icon-message-solid"><span
style="line-height: 20px;"><el-badge is-dot class="item">消息</el-badge></span></el-link>
</li>
<li>
<el-dropdown>
<el-link :underline="false" @click="onHome" icon="el-icon-example-solid">我的</el-link>
<el-dropdown-menu slot="dropdown">
<el-dropdown-item>修改信息</el-dropdown-item>
<el-dropdown-item>修改密码</el-dropdown-item>
<el-dropdown-item>退出登录</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</li>
<li>
<el-link :underline="false" @click="onHome" icon="el-icon-warning">关于</el-link>
</li>
</ul>
</div>
</div>
<div id="content">
<el-tabs v-model="activeTabName" type="border-card" closable @tab-remove="removeTab">
<el-tab-pane
v-for="(item, index) in tabs"
:key="item.name"
:label="item.title"
:name="item.name">
<iframe :src="item.url" style="width: 100%;height: 100%;border: 0;"></iframe>
</el-tab-pane>
</el-tabs>
</div>
</div>
</div>
<style>
* {
-webkit-box-sizing: border-box;
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
margin: 0;
padding: 0;
font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
html, body, #index, #main, #content {
width: 100%;
height: 100%;
}
a {
text-decoration: none;
outline: 0;
cursor: pointer;
-webkit-transition: color .2s ease;
transition: color .2s ease;
-webkit-text-decoration-skip: objects;
color: #757575;
}
a:active, a:hover {
outline-width: 0
}
a:hover {
opacity: 0.7;
}
a:active {
opacity: 0.9;
}
a:active, a:hover {
outline: 0;
text-decoration: none
}
a[disabled] {
color: #ccc;
cursor: not-allowed;
pointer-events: none
}
body {
overflow: hidden;
}
#index {
display: flex;
}
#aside {
background: #252a2f;
}
#aside .el-menu {
transition: all .5s;
border-right: 0
}
#aside .el-menu-item, .el-submenu__title {
height: 40px;
line-height: 40px;
}
#main {
flex-grow: 1;
}
#head {
width: 100%;
height: 40px;
line-height: 40px;
overflow: hidden;
background: #252a2f;
}
#head .collapseSwitch {
display: inline-block;
height: 40px;
width: 40px;
text-align: center;
font-size: 24px;
border-left: 1px solid #424242;
border-right: 1px solid #424242;
}
#head .collapseSwitch a {
display: inline-block;
transition: all 1s;
}
#head .collapseSwitch a.reversal {
transform: rotate(90deg);
}
#head a {
color: #d6d6d6;
vertical-align: top;
}
#head a:hover {
color: #409EFF;
opacity: 1;
}
#head .collapseSwitch:hover {
background: #3b4146;
}
#head .menu {
display: inline-block;
float: right;
}
#head .menu ul {
display: inline-block;
}
#head .menu ul li {
display: inline-block;
vertical-align: top;
}
#head .menu ul li a {
display: inline-block;
text-align: center;
position: relative;
margin: 0 10px;
height: 40px;
vertical-align: top;
}
#head .menu ul li a:after {
content: "";
display: inline-block;
background: #409EFF;
width: 0;
height: 2px;
position: absolute;
bottom: 2px;
left: 50%;
transition: all 0.3s;
}
#head .menu ul li a:hover:after {
width: 100%;
left: 0%;
}
#content {
height: calc(100% - 35px);
}
#content > div {
height: 100%;
}
#content > div > .el-tabs__content {
padding: 0;
height: calc(100% - 43px);
}
#content .el-tabs__item {
padding: 0 10px;
}
#content .el-tabs__nav {
white-space: normal !important;
}
#content > div > .el-tabs__content .el-tab-pane {
height: 100%;
background: #f0f2f5;
}
</style>
<script>
window.index = new Vue({
el: "#index",
data: {
tabs: [],//所有Tabs
activeTabName: '',
properties: {
uniqueOpened: true,//是否保持一个子菜单展开
isCollapse: false,//左侧菜单是否收缩
transition: false,
defaultActive: "1-1",
}
},
methods: {
onHome: function () {
this.addTab({
title: '首页',
name: 'home',
url: '${contextPath}/home.htm'
})
},
collapseSwitch: function () {
this.properties.isCollapse = !this.properties.isCollapse;
},
handleOpen: function () {
},
handleClose: function () {
},
handleSelect: function (index) {
switch (index) {
case "1-1":
this.addTab({title: "映射管理", name: "mapping", url: "/mapping.htm"});
break;
}
return false;
},
addTab: function (tab) {
//查找是否存在该tab
var tempTabs = this.tabs.filter(function (tab_) {
return tab_.name === tab.name;
})
//不存在则添加
if (tempTabs.length <= 0) {
this.tabs.push(tab)
}
this.activeTabName = tab.name;
},
removeTab: function (tabName) {
var activeName = this.activeTabName;
var tempTabs = this.tabs;
if (activeName === tabName) {
tempTabs.forEach(function (tab, index) {
if (tab.name === tabName) {
var nextTab = tempTabs[index + 1] || tempTabs[index - 1];
if (nextTab) {
activeName = nextTab.name;
}
}
});
}
this.activeTabName = activeName;
this.tabs = tempTabs.filter(function (tab) {
return tab.name !== tabName
})
}
},
created: function () {
},
mounted: function () {
this.onHome();//页面初始好后打开首页
},
watch: {}
})
</script>

@ -1,137 +0,0 @@
<div id="app" v-cloak>
<div class="frame">
<div class="login-box">
<div class="login-title">系统登录</div>
<el-form :model="form" :rules="rules" ref="form" class="form">
<el-form-item prop="username">
<el-input placeholder="用户名" v-model="form.username">
<template slot="prepend"><i class="icon iconfont el-icon-user"></i></template>
</el-input>
</el-form-item>
<el-form-item prop="password">
<el-input placeholder="密码" v-model="form.password" type="password">
<template slot="prepend"><i class="icon iconfont el-icon-lock"></i></template>
</el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" style="width: 100%" :loading="isLogin" :disabled="isLogin"
@click="submitForm('form')">登录
</el-button>
</el-form-item>
</el-form>
<a class="tip">系统登录</a>
</div>
</div>
</div>
<style>
#app {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
display: flex;
background: #001d3a;
justify-content: center;
align-items: center;
}
.frame {
width: 600px;
height: 500px;
background: #42424263;
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
box-shadow: 0 0 10px 0 #afafaf52;
}
.login-box {
display: inline-block;
background: #fff;
border-radius: 5px;
text-align: left;
}
.login-title {
line-height: 50px;
border-bottom: 1px solid #e8e8e8;
font-weight: bold;
text-align: left;
padding-left: 20px;
font-size: 15px;
height: 50px;
color: #757575;
}
.form {
width: 300px;
margin-top: 20px;
margin-left: 20px;
margin-right: 20px;
}
.form .el-input-group__prepend {
padding: 10px;
}
.tip {
padding: 5px;
display: inline-block;
text-align: center;
color: #b7b7b7;
width: 100%;
margin-bottom: 10px;
}
</style>
<script type="text/javascript">
var app = new Vue({
el: "#app",
data: {
form: {
username: '',
password: ''
},
rules: {
username: [
{required: true, message: '请输入用户名', trigger: 'blur'}
],
password: [
{required: true, message: '请输入密码', trigger: 'change'}
],
},
isLogin: false
},
mounted: function () {
},
methods: {
submitForm: function (formName) {
this.$refs[formName].validate(function (valid) {
if (valid) {
this.isLogin = true;
ajax.login(this.form).then(function (response) {
this.isLogin = false;
if (response.errors.length > 0) {
nav.e(response.errors[0].message);
} else {
location.href = "/"
}
}.bind(this))
} else {
return false;
}
}.bind(this));
},
resetForm: function (formName) {
this.$refs[formName].resetFields();
}
},
})
</script>

@ -1,426 +0,0 @@
<div id="app" v-cloak>
<el-card class="box-card control">
<el-row>
<el-col :span="3">
<a>Nginx 控制中心</a>
</el-col>
<el-col :span="5">
<a @click="nginxStart">
<el-image v-if="run" :src="'${Uri.getUrl('/static/img/start_.png')}'"
style="width: 50px; height: 50px"
fit="fill"></el-image>
<el-image v-if="!run" :src="'${Uri.getUrl('/static/img/start.png')}'"
style="width: 50px; height: 50px"
fit="fill"></el-image>
</a>
<a @click="nginxStop">
<el-image v-if="run" :src="'${Uri.getUrl('/static/img/stop.png')}'"
style="width: 50px; height: 50px"
fit="fill"></el-image>
<el-image v-if="!run" :src="'${Uri.getUrl('/static/img/stop_.png')}'"
style="width: 50px; height: 50px"
fit="fill"></el-image>
</a>
<a @click="nginxReload">
<el-image v-if="run" :src="'${Uri.getUrl('/static/img/reload.png')}'"
style="width: 50px; height: 50px"
fit="fill"></el-image>
<el-image v-if="!run" :src="'${Uri.getUrl('/static/img/reload_.png')}'"
style="width: 50px; height: 50px"
fit="fill"></el-image>
</a>
</el-col>
</el-row>
</el-card>
<el-row>
<el-col :span="24">
<span>
<el-button type="success" size="small" icon="el-icon-plus" @click="onAction(['create',{}])">新增
</el-button>
<el-button size="small" icon="el-icon-refresh" @click="onRefresh"></el-button>
</span>
</el-col>
</el-row>
<el-table
:data="result.filter(
data => !vm.search
|| data.name.toLowerCase().includes(vm.search.toLowerCase())
|| data.context.toLowerCase().includes(vm.search.toLowerCase())
|| data.location.toLowerCase().includes(vm.search.toLowerCase()))"
style="width: 100%">
<el-table-column
width="150px"
label="名称"
prop="name">
<template slot-scope="scope">
<span style="margin-left: 10px">{{ scope.row.name }}</span>
<el-popover
placement="top-start"
width="200"
trigger="hover"
:content="scope.row.bz">
<i slot="reference" class="el-icon-warning-outline"></i>
</el-popover>
</template>
</el-table-column>
<el-table-column
width="130px"
label="端口"
prop="servicePort">
</el-table-column>
<el-table-column
width="130px"
label="路径"
prop="context">
</el-table-column>
<el-table-column
width="220px"
label="地址"
prop="location">
</el-table-column>
<el-table-column
width="150px"
label="创建日期"
prop="createTime">
</el-table-column>
<el-table-column
label="备注"
prop="bz">
</el-table-column>
<el-table-column
width="150px"
align="right">
<template slot="header" slot-scope="scope">
<el-input
v-model="vm.search"
size="small"
placeholder="输入关键字搜索"/>
</template>
<template slot-scope="scope">
<el-button
size="mini"
@click="onAction(['edit',scope.row])">编辑
</el-button>
<el-button
size="mini"
type="danger"
@click="onAction(['delete', scope.row])">删除
</el-button>
</template>
</el-table-column>
</el-table>
<el-dialog :title="form.title" :visible.sync="form.dialog" width="550px">
<el-form :model="form" :rules="formRules" ref="form" label-width="80px"
style="width: 400px;margin: 0 auto">
<el-form-item label="映射名称" prop="name">
<el-row>
<el-col :span="22">
<el-input v-model="form.name" clearable size="small" placeholder="映射名称"></el-input>
</el-col>
</el-row>
</el-form-item>
<el-form-item label="端口路径" prop="context">
<el-row>
<el-col :span="8">
<el-input v-model="form.servicePort" type="number" clearable size="small"
placeholder="映射端口"></el-input>
</el-col>
<el-col :span="1">
</el-col>
<el-col :span="13">
<el-input v-model="form.context" clearable size="small" placeholder="字母数字组合">
</el-input>
</el-col>
</el-row>
</el-form-item>
<el-form-item label="映射类型" prop="type">
<el-radio v-model="form.type" label="HTTP">HTTP</el-radio>
<el-radio v-model="form.type" label="FILE">FILE</el-radio>
<el-radio v-model="form.type" label="转HTTPS">转HTTPS</el-radio>
</el-form-item>
<el-form-item label="映射地址" prop="location">
<el-row>
<el-col :span="22">
<el-input v-if="form.type=='HTTP'" v-model="form.location" clearable size="small"
placeholder="代理地址http://"></el-input>
<el-input v-if="form.type=='FILE'" v-model="form.location" clearable size="small"
placeholder="文件地址D:\ or /root"></el-input>
</el-col>
<el-col :span="2" style="text-align: right">
<el-popover
placement="top-start"
width="200"
trigger="hover"
content="映射类型为文件时,映射路径名需和即将映射的文件夹一样,且不以“\”结尾,映射地址为该文件夹的上一层,则可正常访问。">
<i slot="reference" class="el-icon-warning-outline"></i>
</el-popover>
</el-col>
</el-row>
</el-form-item>
<el-form-item label="映射备注" prop="bz">
<el-row>
<el-col :span="22">
<el-input type="textarea" :autosize="{ minRows: 3, maxRows: 5}" v-model="form.bz" clearable
size="small"
placeholder="备注信息"></el-input>
</el-col>
</el-row>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button size="small" @click="form.dialog = false">取 消</el-button>
<el-button size="small" type="primary" @click="onAction(['save',''])">保存</el-button>
</span>
</el-dialog>
</div>
<style>
#app {
padding: 10px;
margin: 0 auto;
width: 1080px;
}
.box-card {
margin: 10px;
}
.control a:first-child {
padding-right: 10px;
}
.control a {
display: inline-block;
line-height: 50px;
height: 50px;
vertical-align: top;
}
.control a:hover {
background: #e7e7e7;
}
.control a:first-child:hover {
background: #ffffff;
}
</style>
<script>
var app = new Vue({
el: "#app",
data: {
vm: {
search: ""
},
form: {
title: "",
dialog: false,
id: '',
type: 'HTTP',
servicePort: '',
context: '',
location: '',
name: '',
bz: ''
},
formRules: {
name: [
{required: true, message: '映射名称不能为空', trigger: 'blur'},
{min: 1, max: 50, message: '长度在 1 到 50 字符', trigger: 'blur'}
],
servicePort: [
{required: true, message: '映射端口不能为空', trigger: 'blur'},
{pattern: "^[0-9]*$", message: '映射端口只能为数字', trigger: 'blur'},
],
context: [
{required: true, message: '映射上下文不能为空', trigger: 'blur'},
{pattern: "/|([a-zA-Z][a-zA-Z0-9_]*/)", message: '上下文须是(/)开始结果中间为字母、数字、_等组合', trigger: 'blur'},
],
location: [
{required: true, message: '映射地址不能为空', trigger: 'change'},
{
validator: function (rule, value, callback) {
if (app.form.type == "HTTP") {
if (value.match("http:\/\/.*")) {
callback();
} else {
callback(new Error("需以http://协议开始"))
}
}
if (app.form.type == "FILE") {
if (value.match("^[A-Z]:\\\\.*$|^[A-Z]:/.*$|^/.*$")) {
callback();
} else {
callback(new Error("windows目录(C:\\)或linux目录(\\)"))
}
}
}, trigger: 'blur'
}
],
},
result: [],
run: ${run?default('false')}
},
methods: {
onFind: function () {
ajax.mappingFind(this.vm).then(function (response) {
if (response.errors.length > 0) {
nav.e(response.errors[0].message);
} else {
this.result = response.result;
}
}.bind(this))
},
onAction: function (arg) {
const action = arg[0];
switch (action) {
case "create":
this.form.title = '新增';
this.form.servicePort = "${serverPort?default("8080")}";
this.form.port = arg[1].value;
this.form.id = '';
this.form.name = '';
this.form.context = '';
this.form.type = 'HTTP';
this.form.location = '';
this.form.bz = '';
this.form.dialog = true;
break;
case "edit":
this.form.title = '编辑';
this.form.id = arg[1].id;
this.form.servicePort = arg[1].servicePort;
this.form.name = arg[1].name;
this.form.context = arg[1].context;
this.form.type = arg[1].type;
this.form.location = arg[1].location;
this.form.bz = arg[1].bz;
this.form.dialog = true;
break;
case "save":
this.$refs['form'].validate(function (valid) {
if (valid) {
if (this.form.id) {
ajax.mappingUpdate(this.form).then(function (response) {
if (response.errors.length > 0) {
nav.e(response.errors[0].message);
} else {
this.onFind();
this.form.dialog = false;
this.configFlush();
if (this.run) {
this.nginxReload();
}
}
}.bind(this))
} else {
ajax.mappingCreate(this.form).then(function (response) {
if (response.errors.length > 0) {
nav.e(response.errors[0].message);
} else {
this.onFind();
this.form.dialog = false;
this.configFlush();
if (this.run) {
this.nginxReload();
}
}
}.bind(this))
}
} else {
return false;
}
}.bind(this));
break;
case "delete":
this.$confirm('将删除该项, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(function () {
ajax.mappingDelete({id: arg[1].id}).then(function (response) {
if (response.errors.length > 0) {
nav.e(response.errors[0].message);
} else {
nav.s("删除成功");
this.onFind();
this.configFlush();
if (this.run) {
this.nginxReload();
}
}
}.bind(this))
}.bind(this)).catch(function (action) {
});
break;
}
},
startMonitor: function () {
if (window.EventSource) {
window.evtSource = new EventSource('${Uri.getUrl("/sse/1")}');
window.evtSource.addEventListener('message', function (e) {
var msg = JSON.parse(e.data);
if (msg.type == 'NGINX_STATE') {//状态推送
if (this.run != msg.object.run) {
this.$notify.info({
title: '提示',
message: "Nginx 运行状态发生变化。",
duration: 5000
});
this.run = msg.object.run;
}
}
}.bind(this))
}
},
nginxStart: function () {
ajax.nginxStart().then(function (response) {
if (response.errors.length > 0) {
nav.e(response.errors[0].message);
} else {
this.onFind();
this.form.dialog = false;
}
}.bind(this))
},
nginxStop: function () {
ajax.nginxStop().then(function (response) {
if (response.errors.length > 0) {
nav.e(response.errors[0].message);
} else {
this.onFind();
this.form.dialog = false;
}
}.bind(this))
},
configFlush: function () {
ajax.configFlush();
},
onRefresh: function () {
this.configFlush();
this.onFind();
},
nginxReload: function () {
ajax.nginxReload().then(function (response) {
if (response.errors.length > 0) {
nav.e(response.errors[0].message);
} else {
}
}.bind(this))
}
},
created: function () {
},
mounted: function () {
this.onFind();
this.startMonitor();
},
watch: {}
})
</script>

@ -1,92 +0,0 @@
package xyz.wbsite;
import com.example.frame.utils.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import xyz.wbsite.frame.utils.AESUtil;
import xyz.wbsite.frame.utils.Base64Util;
import xyz.wbsite.frame.utils.IDgenerator;
import xyz.wbsite.frame.utils.MD5Util;
import xyz.wbsite.frame.utils.ProcessUtil;
import xyz.wbsite.frame.utils.RSAUtil;
/**
* UtilTest - -
*
* @author wangbing
* @version 0.0.1
* @since 2017-01-01
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class UtilTest {
@Test
public void testIDgenerator() {
for (int i = 0; i < 10; i++) {
long l = IDgenerator.nextId();
System.out.println(l);
}
}
@Test
public void testAESUtil() {
// 加密
String data = "我有一个苹果";
String secret = "1234567890123456";
System.out.println("加密后的Base64密文是:" + AESUtil.encrypt2Base64(data.getBytes(), secret));
// 解密
String encrypt2Base64 = AESUtil.encrypt2Base64(data.getBytes(), secret);
byte[] decrypt = AESUtil.decrypt(Base64Util.decode(encrypt2Base64), secret);
System.out.println("解密后的明文是:" + new String(decrypt));
}
@Test
public void testBase64Util() {
String s = Base64Util.encodeToString(("我搜搜").getBytes());
System.out.println(s);
byte[] decode = Base64Util.decode(s);
System.out.println(new String(decode));
}
@Test
public void testMD5Util() {
String encode = MD5Util.encode("123456");
System.out.println(encode);
}
@Test
public void testProcessUtil() {
ProcessUtil.execExe("D:\\example.exe");
ProcessUtil.execBat("D:\\example.bat");
}
@Test
public void testRSAUtil() {
{//创建秘钥对
RSAUtil.createKey();
}
{//加解密
//加密
String encrypt = RSAUtil.encrypt2Base64("我有一个苹果".getBytes());
System.out.println(encrypt);
//解密
String decrypt = RSAUtil.decrypt2String(encrypt);
System.out.println(decrypt);
}
String sign = RSAUtil.sign2Base64("我有一个苹果".getBytes());
System.out.println(sign);
boolean b = RSAUtil.doCheck("我有一个苹果".getBytes(), sign);
System.out.println(b);
}
}

@ -1,17 +0,0 @@
package xyz.wbsite.config;
import xyz.wbsite.frame.base.Token;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TestConfig {
@Bean
public Token getTestToken() {
Token token = new Token();
token.setId(0);
token.setUserId(0);
token.setUserName("system");
return token;
}
}

@ -1,41 +0,0 @@
package xyz.wbsite.mapping;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.module.admin.mgr.MappingManager;
import xyz.wbsite.module.admin.req.MappingCreateRequest;
import xyz.wbsite.module.admin.req.MappingFindRequest;
import xyz.wbsite.module.admin.rsp.MappingCreateResponse;
import xyz.wbsite.module.admin.rsp.MappingFindResponse;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static junit.framework.TestCase.assertTrue;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MappingTest {
@Autowired
private MappingManager mappingManager;
@Autowired
private Token token;
@Test
public void createMapping() {
MappingCreateRequest createRequest = new MappingCreateRequest();
createRequest.setName("测试");
createRequest.setContext("test");
createRequest.setLocation("test");
MappingCreateResponse mappingCreateResponse = mappingManager.create(createRequest, token);
assertTrue(!mappingCreateResponse.hasError());
MappingFindRequest mappingFindRequest = new MappingFindRequest();
MappingFindResponse mappingFindResponse = mappingManager.find(mappingFindRequest, token);
assertTrue(!mappingFindResponse.hasError());
}
}

@ -1,52 +0,0 @@
# 测试环境
server.service=8080
server.servlet.context-path=/
spring.mvc.static-path-pattern=/static/**
spring.resources.static-locations=classpath:static/
spring.application.name=SpringBoot
spring.main.banner-mode=CONSOLE
spring.devtools.restart.enabled=true
# 编码配置
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
# 根路径、欢迎页
web.welcome.page=/index.htm
# 需要验证授权, 既访问时组装Token
web.url.auth.included=/**
# 不需要验证授权, 或该请求有自己的验证机制
web.url.auth.excluded=/favicon.ico,/static/**,/api,/login.htm
# 日志配置
logging.path=D://
logging.levels=DEBUG
logging.config=classpath:logback-config.xml
# jackson 相关配置
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.default-property-inclusion=use_defaults
spring.jackson.mapper.sort-properties-alphabetically=true
spring.jackson.deserialization.fail-on-unknown-properties=false
# freemarker
spring.freemarker.enabled=true
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=false
spring.freemarker.settings.template_update_delay=1
spring.freemarker.settings.locale=zh_CN
spring.freemarker.settings.datetime_format=yyyy-MM-dd
spring.freemarker.settings.date_format=yyyy-MM-dd
spring.freemarker.settings.number_format=#.##
spring.freemarker.settings.classic_compatible=true
spring.freemarker.settings.whitespace_stripping=true
spring.freemarker.settings.url_escaping_charset=utf-8
# 文件上传配置
spring.servlet.multipart.resolveLazily=false
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
dbpath=

@ -1,22 +0,0 @@
<?xml version="1.0"?>
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 控制台输出 -->
<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
debug级别及以上
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>DEBUG</level>
</filter>
<encoder>
<pattern>%highlight(%d{yyyy-MM-dd HH:mm:ss.SSS} [%-4level] [%thread] [%logger{36}-%method] %ex %msg%n)</pattern>
</encoder>
</appender>
<logger name="java.sql" level="INFO"></logger>
<!-- 日志总入口 -->
<root level="DEBUG">
<appender-ref ref="Console"/>
</root>
</configuration>

Binary file not shown.

@ -1,49 +1,53 @@
package xyz.wbsite.action.ajax.conf;
import com.fasterxml.jackson.core.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import xyz.wbsite.frame.excel.WExcel;
import xyz.wbsite.frame.utils.LogUtil;
import xyz.wbsite.frame.auth.LocalData;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.utils.MapperUtil;
import xyz.wbsite.frame.base.BaseResponse;
import xyz.wbsite.frame.utils.ResponseUtil;
import xyz.wbsite.frame.utils.ValidationUtil;
import xyz.wbsite.frame.excel.exception.ReadErrorException;
import xyz.wbsite.frame.excel.exception.TemplateNotMatchException;
import xyz.wbsite.module.conf.ent.Mapping;
import xyz.wbsite.module.conf.mgr.MappingManager;
import xyz.wbsite.module.conf.req.MappingCreateRequest;
import xyz.wbsite.module.conf.req.MappingDeleteRequest;
import xyz.wbsite.module.conf.req.MappingFindRequest;
import xyz.wbsite.module.conf.req.MappingGetRequest;
import xyz.wbsite.module.conf.req.MappingUpdateRequest;
import xyz.wbsite.module.conf.req.NginxReloadRequest;
import xyz.wbsite.module.conf.rsp.MappingCreateResponse;
import xyz.wbsite.module.conf.rsp.MappingDeleteResponse;
import xyz.wbsite.module.conf.rsp.MappingFindResponse;
import xyz.wbsite.module.conf.rsp.MappingGetResponse;
import xyz.wbsite.module.conf.rsp.MappingUpdateResponse;
import java.io.IOException;
import java.util.List;
public class MappingAjax{
public class MappingAjax {
@Autowired
private MappingManager mappingManager;
public MappingCreateResponse create(MappingCreateRequest request) {
return mappingManager.create(request, LocalData.getToken());
MappingCreateResponse response = mappingManager.create(request, LocalData.getToken());
if (!response.hasError()) {
NginxAjax nginxAjax = LocalData.getBean(NginxAjax.class);
nginxAjax.flushConfig();
nginxAjax.reload(new NginxReloadRequest());
}
return response;
}
public MappingDeleteResponse delete(MappingDeleteRequest request) {
return mappingManager.delete(request, LocalData.getToken());
MappingDeleteResponse response = mappingManager.delete(request, LocalData.getToken());
if (!response.hasError()) {
NginxAjax nginxAjax = LocalData.getBean(NginxAjax.class);
nginxAjax.flushConfig();
nginxAjax.reload(new NginxReloadRequest());
}
return response;
}
public MappingUpdateResponse update(MappingUpdateRequest request) {
return mappingManager.update(request, LocalData.getToken());
MappingUpdateResponse response = mappingManager.update(request, LocalData.getToken());
if (!response.hasError()) {
NginxAjax nginxAjax = LocalData.getBean(NginxAjax.class);
nginxAjax.flushConfig();
nginxAjax.reload(new NginxReloadRequest());
}
return response;
}
public MappingFindResponse find(MappingFindRequest request) {

@ -0,0 +1,119 @@
package xyz.wbsite.action.ajax.conf;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import xyz.wbsite.frame.auth.LocalData;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.base.SortType;
import xyz.wbsite.frame.utils.ProcessUtil;
import xyz.wbsite.module.conf.ent.Mapping;
import xyz.wbsite.module.conf.ent.NginxCtrl;
import xyz.wbsite.module.conf.mgr.MappingManager;
import xyz.wbsite.module.conf.req.MappingFindRequest;
import xyz.wbsite.module.conf.req.NginxReloadRequest;
import xyz.wbsite.module.conf.req.NginxStartRequest;
import xyz.wbsite.module.conf.req.NginxStopRequest;
import xyz.wbsite.module.conf.rsp.MappingFindResponse;
import xyz.wbsite.module.conf.rsp.NginxReloadResponse;
import xyz.wbsite.module.conf.rsp.NginxStartResponse;
import xyz.wbsite.module.conf.rsp.NginxStopResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class NginxAjax {
@Autowired
private NginxCtrl nginxCtrl;
@Autowired
private MappingManager mappingManager;
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
public NginxStartResponse start(NginxStartRequest request) {
NginxStartResponse response = new NginxStartResponse();
if (nginxCtrl.isRunning()) {
response.addError(ErrorType.BUSINESS_ERROR, "程序已经运行");
return response;
}
ProcessUtil.execBat(nginxCtrl.getStartCmd());
return response;
}
public NginxStopResponse stop(NginxStopRequest request) {
NginxStopResponse response = new NginxStopResponse();
if (!nginxCtrl.isRunning()) {
response.addError(ErrorType.BUSINESS_ERROR, "程序尚未运行");
return response;
}
ProcessUtil.execBat(nginxCtrl.getStopCmd());
return response;
}
public NginxReloadResponse reload(NginxReloadRequest request) {
NginxReloadResponse response = new NginxReloadResponse();
if (!nginxCtrl.isRunning()) {
response.addError(ErrorType.BUSINESS_ERROR, "程序尚未运行");
return response;
}
// 刷新配置文件
flushConfig();
// 重新加载配置文件
ProcessUtil.execBat(nginxCtrl.getReloadCmd());
return response;
}
public synchronized void flushConfig() {
Writer wr = null;
try {
File config = nginxCtrl.getConfig();
HashMap<String, Object> context = new HashMap<>();
MappingFindRequest mappingFindRequest = new MappingFindRequest();
mappingFindRequest.setPageSize(0);
mappingFindRequest.setSortKey("PORT");
mappingFindRequest.setSortType(SortType.ASC);
MappingFindResponse mappingFindResponse = mappingManager.find(mappingFindRequest, LocalData.getSysToken());
Map<String, List<Mapping>> services = new HashMap<>();
for (Mapping mapping : mappingFindResponse.getResult()) {
List<Mapping> mappings = services.get(mapping.getPort());
if (mappings == null) {
mappings = new ArrayList<>();
services.put(mapping.getPort(), mappings);
}
mappings.add(mapping);
}
context.put("services", services);
Template template = freeMarkerConfigurer.getConfiguration().getTemplate("nginx.conf.ftl");
wr = new OutputStreamWriter(new FileOutputStream(config), "UTF-8");
//写入
template.process(context, wr);
//关闭流
wr.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
} finally {
try {
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

@ -1,15 +1,15 @@
package xyz.wbsite.action.screen;
import xyz.wbsite.frame.base.Screen;
import xyz.wbsite.module.admin.ent.NginxCtrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import xyz.wbsite.frame.base.Screen;
import xyz.wbsite.module.conf.ent.NginxCtrl;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Mapping extends Screen {
public class Home extends Screen {
@Autowired
private NginxCtrl nginxCtrl;
@Value("${mapping.default.port}")

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

Loading…
Cancel
Save

Powered by TurnKey Linux.