0.0.1-SNAPSHOT
wangbing 5 years ago
parent 93a4d99f25
commit 8e5a42930e

@ -6,6 +6,7 @@ import com.example.frame.base.ErrorType;
import com.example.frame.base.Screen;
import com.example.frame.utils.LocalData;
import com.example.config.ActionConfig;
import com.example.frame.utils.MapperUtil;
import org.springframework.beans.BeansException;
import org.apache.commons.io.FileUtils;
import org.springframework.boot.web.servlet.error.ErrorController;
@ -26,6 +27,14 @@ import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -178,4 +187,37 @@ public class GlobalController implements ErrorController {
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(file)),
headers, HttpStatus.CREATED);
}
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 void pushAll(Object data) {
try {
for (String s : sseMap.keySet()) {
sseMap.get(s).send(MapperUtil.toJson(data), MediaType.APPLICATION_JSON);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

@ -0,0 +1,72 @@
package com.example.config;
import com.example.frame.utils.FileUtil;
import com.example.frame.utils.ZipUtil;
import com.example.module.admin.ent.Mapping;
import com.example.module.admin.ent.NginxCtrl;
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.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import xyz.wbsite.wsqlite.ObjectClient;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
@Configuration
public class NginxConfig {
@Autowired
private Environment environment;
@Bean
public NginxCtrl initNginx() {
String property = environment.getProperty("nginx-path");
File nginxHome = null;
if (StringUtils.isEmpty(property)) {
ApplicationHome home = new ApplicationHome(getClass());
// 当前运行jar文件
File jarFile = home.getSource() != null ? home.getSource() : home.getDir();
//jar同目录
nginxHome = new File(jarFile.getParent(), "nginx");
if (!nginxHome.exists()) {
ClassPathResource classPathResource = new ClassPathResource("nginx-1.14.2.zip");
try {
InputStream inputStream = classPathResource.getInputStream();
File nginxDir = new File(jarFile.getParent(), "nginx");
File nginxZip = new File(jarFile.getParent(), "nginx.zip");
FileUtil.inputStream2File(inputStream, nginxZip);
ZipUtil.unZip(nginxZip, nginxDir);
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
nginxHome = new File(property);
}
if (!nginxHome.exists()) {
throw new RuntimeException("nginx home not exists!");
}
File exe = new File(nginxHome, "nginx.exe");
NginxCtrl nginxCtrl = new NginxCtrl();
nginxCtrl.setStartCmd("start " + exe.getAbsolutePath());
nginxCtrl.setStopCmd(exe.getAbsolutePath() + " -s quit");
nginxCtrl.setReloadCmd(exe.getAbsolutePath() + " - s reload ");
nginxCtrl.setVersionCmd(exe.getAbsolutePath() + " -v ");
return nginxCtrl;
}
}

@ -17,19 +17,18 @@ import javax.servlet.http.HttpServletRequest;
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${web.url.auth.excluded}")
private String[] excluded;
@Value("${web.url.auth.included}")
private String[] included;
@Value("${spring.mvc.static-path-pattern}")
private String[] staticPath;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(staticPath).permitAll()
.antMatchers(excluded).permitAll()
.antMatchers(included).access("@Authorization.hasPermission(request,authentication)")
.anyRequest().access("@Authorization.hasPermission(request,authentication)")
.and().cors()
.and().headers().frameOptions().disable()
.and().csrf().disable();

@ -1,5 +1,7 @@
package com.example.config;
import com.example.frame.utils.FileUtil;
import com.example.frame.utils.ZipUtil;
import com.example.module.admin.ent.Mapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@ -7,10 +9,15 @@ 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.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import xyz.wbsite.wsqlite.ObjectClient;
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;

@ -1,7 +1,12 @@
package com.example.config;
import com.example.action.GlobalController;
import com.example.frame.base.Message;
import com.example.frame.base.MessageType;
import com.example.frame.utils.LogUtil;
import com.example.frame.utils.ProcessUtil;
import com.example.module.admin.ent.State;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableScheduling;
@ -17,12 +22,20 @@ import java.util.concurrent.Executors;
*/
@Configuration
@EnableScheduling
@Profile("prod")
//@Profile("prod")
public class TaskConfig implements SchedulingConfigurer {
@Scheduled(cron="0/30 * * * * ? ")
@Autowired
private GlobalController globalController;
@Scheduled(cron = "0/3 * * * * ? ")
public void task() {
LogUtil.i("--------------------Task--------------------");
Message message = new Message();
message.setType(MessageType.NGINX_STATE);
State state = new State();
state.setRun(true);
message.setObject(state);
globalController.pushAll(message);
}
/**

@ -0,0 +1,24 @@
package com.example.frame.base;
public class Message {
private MessageType type;
private Object object;
public MessageType getType() {
return type;
}
public void setType(MessageType type) {
this.type = type;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}

@ -0,0 +1,6 @@
package com.example.frame.base;
public enum MessageType {
NGINX_STATE,
}

@ -0,0 +1,915 @@
package com.example.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();
}
}
}

@ -0,0 +1,138 @@
package com.example.frame.utils;
import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;
public class ZipUtil {
/**
*
*
* @param zipFile Zip
* @param descDir
*/
public static void unZip(File zipFile, File descDir) {
if (!descDir.exists()) {
descDir.mkdirs();
}
ZipFile zip = null;
try {
zip = new ZipFile(zipFile);
Enumeration<?> entries = zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
File dir = new File(descDir, entry.getName());
dir.mkdirs();
} else {
// 如果是文件就先创建一个文件然后用io流把内容copy过去
File targetFile = new File(descDir + "/" + entry.getName());
// 保证这个文件的父文件夹必须要存在
if (!targetFile.getParentFile().exists()) {
targetFile.getParentFile().mkdirs();
}
targetFile.createNewFile();
// 将压缩文件内容写入到这个文件中
InputStream is = zip.getInputStream(entry);
FileOutputStream fos = new FileOutputStream(targetFile);
int len;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
}
// 关流顺序,先打开的后关闭
fos.close();
is.close();
}
}
System.out.println("解压文件" + zipFile.getAbsolutePath() + "成功");
} catch (Exception e) {
throw new RuntimeException("unzip error from ZipUtil", e);
} finally {
if (zip != null) {
try {
zip.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
*
* @param src
* @param zip Zip
*/
public static void toZip(File src, File zip) {
ZipOutputStream zipOutputStream = null;
try {
if (!src.exists()) {
System.err.println("压缩文件或目录不存在");
return;
}
if (!zip.exists()) {
zip.createNewFile();
}
zipOutputStream = new ZipOutputStream(new FileOutputStream(zip));
compress(src, zipOutputStream, null);
zipOutputStream.close();
System.out.println("压缩文件" + zip.getAbsolutePath() + "成功");
} catch (IOException e) {
System.err.println("压缩失败");
e.printStackTrace();
} finally {
if (zipOutputStream != null) {
try {
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param sourceFile
* @param zos Zip
* @param parentPath
* @throws IOException
*/
private static void compress(File sourceFile, ZipOutputStream zos, String parentPath) throws IOException {
byte[] buff = new byte[1024];
if (sourceFile.isDirectory()) {
//确保空文件夹也可以压缩进去
zos.putNextEntry(new ZipEntry((parentPath != null ? parentPath : "") + sourceFile.getName() + "/"));
zos.closeEntry();
//循环压缩子文件或文件夹
for (File file : sourceFile.listFiles()) {
compress(file, zos, (parentPath != null ? parentPath : "") + sourceFile.getName() + "/");
}
} else {
//压缩文件
zos.putNextEntry(new ZipEntry((parentPath != null ? parentPath : "") + sourceFile.getName()));
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buff)) != -1) {
zos.write(buff, 0, len);
}
zos.closeEntry();
in.close();
}
}
public static void main(String[] args) {
//解压
unZip(new File("E:\\AAA.zip"), new File("E:\\AAA"));
//压缩
toZip(new File("E:\\AAA"), new File("E:\\AAA.zip"));
}
}

@ -0,0 +1,56 @@
package com.example.module.admin.ent;
import com.example.frame.utils.ProcessUtil;
public class NginxCtrl {
private String startCmd = "start nginx";
private String stopCmd = "nginx.exe -s quit";
private String reloadCmd = "nginx.exe -s reload";
private String versionCmd = "nginx -v";
public void doStart(){
ProcessUtil.exec(startCmd);
}
public void doStop(){
ProcessUtil.exec(stopCmd);
}
public void doReload(){
ProcessUtil.exec(reloadCmd);
}
public String getStartCmd() {
return startCmd;
}
public void setStartCmd(String startCmd) {
this.startCmd = startCmd;
}
public String getStopCmd() {
return stopCmd;
}
public void setStopCmd(String stopCmd) {
this.stopCmd = stopCmd;
}
public String getReloadCmd() {
return reloadCmd;
}
public void setReloadCmd(String reloadCmd) {
this.reloadCmd = reloadCmd;
}
public String getVersionCmd() {
return versionCmd;
}
public void setVersionCmd(String versionCmd) {
this.versionCmd = versionCmd;
}
}

@ -0,0 +1,18 @@
package com.example.module.admin.ent;
/**
*
*/
public class State {
// 0 为关闭1为运行
private boolean run;
public boolean isRun() {
return run;
}
public void setRun(boolean run) {
this.run = run;
}
}

@ -13,10 +13,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,/mapping.htm
web.url.auth.excluded=/favicon.ico,/static/**,/api,/login.htm,/mapping.htm,/sse/**
# 日志配置
logging.path=D://
logging.levels=DEBUG
@ -50,3 +48,4 @@ spring.servlet.multipart.resolveLazily=false
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
dbpath=
nginx-path=

@ -13,8 +13,6 @@ 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
# 日志配置
@ -49,3 +47,5 @@ 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=

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

@ -14,6 +14,27 @@
</el-form>
</el-card>
<el-card class="box-card control">
<a> Nginx 控制中心</a>
<a>
<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>
<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>
<el-image :src="'${Uri.getUrl('/static/img/restart.png')}'" style="width: 50px; height: 50px"
fit="fill"></el-image>
</a>
</el-card>
<el-card class="box-card">
<el-row>
<el-col :span="12">
@ -86,7 +107,8 @@
<i class="el-icon-edit"></i>编辑资源
<el-dropdown-menu slot="dropdown">
<el-dropdown-item :command="['edit',scope.row]" icon="el-icon-edit">编辑</el-dropdown-item>
<el-dropdown-item :command="['delete',scope.row]" icon="el-icon-delete">删除</el-dropdown-item>
<el-dropdown-item :command="['delete',scope.row]" icon="el-icon-delete">删除
</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
</template>
@ -111,6 +133,21 @@
.box-card {
margin: 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({
@ -143,6 +180,7 @@
},
select: [],
result: [],
run: false
},
methods: {
onSearch: function () {
@ -175,7 +213,7 @@
const item = arg[1];
switch (action) {
case "create":
this.form.title = '新增角色';
this.form.title = '新增';
this.form.id = '';
this.form.roleName = '';
this.form.roleCode = '';
@ -203,20 +241,13 @@
}
break;
case "edit":
this.form.title = '编辑角色';
this.form.title = '编辑';
this.form.id = item.id;
this.form.roleName = item.roleName;
this.form.roleCode = item.roleCode;
this.form.rowVersion = item.rowVersion;
this.form.dialog = true;
break;
case "roleRes":
parent.index.addTab({
title: "编辑角色资源",
name: "roleRes" + item.id,
url: "${Uri.getUrl("/sys/role/roleRes.htm?roleId=")}" + item.id
});
break
case "delete":
this.$confirm('将删除该项, 是否继续?', '提示', {
confirmButtonText: '确定',
@ -237,11 +268,32 @@
break;
}
},
startMonitor: function () {
console.log(this)
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 运行状态发生变化:"
});
this.run = msg.object.run;
}
}
}.bind(this))
}
}
},
created: function () {
},
mounted: function () {
this.onFind();
this.startMonitor();
},
watch: {}
})

Loading…
Cancel
Save

Powered by TurnKey Linux.