diff --git a/src/main/java/com/insigma/HyToolApplication.java b/src/main/java/com/insigma/HyToolApplication.java index 29a1548..52f7fc2 100644 --- a/src/main/java/com/insigma/HyToolApplication.java +++ b/src/main/java/com/insigma/HyToolApplication.java @@ -6,10 +6,11 @@ import com.insigma.service.Computer; import com.insigma.service.Database; import com.insigma.service.Middleware; import com.insigma.ui.SwingFrame; +import com.insigma.utils.DbUtil; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertiesLoaderUtils; @@ -22,7 +23,7 @@ import java.util.Properties; * @author Vivim */ @Slf4j -@SpringBootApplication +@SpringBootApplication(exclude = {SecurityAutoConfiguration.class }) public class HyToolApplication { public static void main(String[] args) { @@ -57,11 +58,10 @@ public class HyToolApplication { Properties loadProperties = PropertiesLoaderUtils .loadProperties(new EncodedResource(new ClassPathResource("application.properties"), "UTF-8")); - String url = loadProperties.getProperty("db.url"); - String usr = loadProperties.getProperty("db.usr"); - String pwd = loadProperties.getProperty("db.pwd"); - String drive = loadProperties.getProperty("db.drive"); - + DbUtil.url = loadProperties.getProperty("db.url"); + DbUtil.usr = loadProperties.getProperty("db.usr"); + DbUtil.pwd = loadProperties.getProperty("db.pwd"); + DbUtil.drive = loadProperties.getProperty("db.drive"); AppCfg.DB = loadProperties.getProperty("hy.db"); AppCfg.MW = loadProperties.getProperty("hy.mw"); AppCfg.HZB = loadProperties.getProperty("hy.hzb"); @@ -70,7 +70,7 @@ public class HyToolApplication { AppCfg.OSArch = loadProperties.getProperty("hy.os-arch"); AppCfg.is32Bit = AppCfg.OSArch.equals(propertiesValue); AppCfg.BROWSER = loadProperties.getProperty("hy.browser"); - log.info("获取参数1:{}, {}, {}, {}", url, usr, pwd, drive); + log.info("获取参数1:{}, {}, {}, {}", DbUtil.url, DbUtil.usr, DbUtil.pwd, DbUtil.drive); log.info("获取参数2:{}, {}, {}, {}", AppCfg.DB, AppCfg.MW, AppCfg.HZB, AppCfg.BEAN); log.info("获取参数3:{}, {}, {}, {}", AppCfg.CODE, AppCfg.OSArch, AppCfg.is32Bit, AppCfg.BROWSER); } diff --git a/src/main/java/com/insigma/command/LocalCommandExecutor.java b/src/main/java/com/insigma/command/LocalCommandExecutor.java new file mode 100644 index 0000000..fadef7c --- /dev/null +++ b/src/main/java/com/insigma/command/LocalCommandExecutor.java @@ -0,0 +1,25 @@ +package com.insigma.command; + +import com.insigma.entry.ExecuteResult; + +/** +* LocalCommandExecutor.java + * @author Vivim + */ +public interface LocalCommandExecutor { + /** + * 执行命令行对象 + * @param command 执行命令行 + * @param timeout 超时控制 + * @return + */ + ExecuteResult executeCommand(String command, long timeout); + /** + * 执行命令行对象 + * @param command 执行命令行 + * @param keyword 检测关键字 + * @param timeout 超时控制 + * @return + */ + String getPort(String command, String keyword, long timeout); +} \ No newline at end of file diff --git a/src/main/java/com/insigma/command/impl/LocalCommandExecutorImpl.java b/src/main/java/com/insigma/command/impl/LocalCommandExecutorImpl.java new file mode 100644 index 0000000..76eeb51 --- /dev/null +++ b/src/main/java/com/insigma/command/impl/LocalCommandExecutorImpl.java @@ -0,0 +1,145 @@ +package com.insigma.command.impl; + +import com.insigma.entry.ExecuteResult; +import com.insigma.command.LocalCommandExecutor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.thymeleaf.util.StringUtils; + +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + + +/** + * @author Vivim + */ +@Slf4j +@Service +public class LocalCommandExecutorImpl implements LocalCommandExecutor { + + static ExecutorService pool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 3L, TimeUnit.SECONDS, new SynchronousQueue()); + + @Override + public ExecuteResult executeCommand(String command, long timeout) { + Process process = null; + InputStream pIn = null; + InputStream pErr = null; + StreamGobbler outputGobbler = null; + StreamGobbler errorGobbler = null; + Future executeFuture = null; + try { + log.debug("执行操作命令:{}", command); + process = Runtime.getRuntime().exec(command); + final Process p = process; + + // close process's output stream. + p.getOutputStream().close(); + + pIn = process.getInputStream(); + outputGobbler = new StreamGobbler(pIn, "OUTPUT"); + outputGobbler.start(); + + pErr = process.getErrorStream(); + errorGobbler = new StreamGobbler(pErr, "ERROR"); + errorGobbler.start(); + + // create a Callable for the command's Process which can be called by an Executor + Callable call = () -> { + p.waitFor(); + return p.exitValue(); + }; + + // submit the command's call and get the result from a + executeFuture = pool.submit(call); + int exitCode = executeFuture.get(timeout, TimeUnit.MILLISECONDS); + return new ExecuteResult(exitCode, outputGobbler.getContent()); + + } catch (IOException ex) { + String errorMessage = "The command [" + command + "] execute failed."; + log.error(errorMessage, ex); + return new ExecuteResult(-1, null); + } catch (TimeoutException ex) { + String errorMessage = "The command [" + command + "] timed out."; + log.error(errorMessage, ex); + return new ExecuteResult(-1, null); + } catch (ExecutionException ex) { + String errorMessage = "The command [" + command + "] did not complete due to an execution error."; + log.error(errorMessage, ex); + return new ExecuteResult(-1, null); + } catch (InterruptedException ex) { + String errorMessage = "The command [" + command + "] did not complete due to an interrupted error."; + log.error(errorMessage, ex); + return new ExecuteResult(-1, null); + } finally { + if (executeFuture != null) { + try { + executeFuture.cancel(true); + } catch (Exception ignore) { + ignore.printStackTrace(); + } + } + if (pIn != null) { + this.closeQuietly(pIn); + if (outputGobbler != null && !outputGobbler.isInterrupted()) { + outputGobbler.interrupt(); + } + } + if (pErr != null) { + this.closeQuietly(pErr); + if (errorGobbler != null && !errorGobbler.isInterrupted()) { + errorGobbler.interrupt(); + } + } + if (process != null) { + process.destroy(); + } + } + } + + private void closeQuietly(Closeable c) { + try { + if (c != null) { + c.close(); + } + } catch (IOException e) { + log.error("exception", e); + } + } + + @Override + public String getPort(String command, String keyword, long timeout){ + if(StringUtils.isEmpty(keyword)){ + return null; + } + ExecuteResult executeResult = executeCommand(command, timeout); + if(Objects.nonNull(executeResult) && executeResult.getExitCode() == 0){ + String executeOut = executeResult.getExecuteOut(); + if(!StringUtils.isEmpty(executeOut)){ + String[] split = executeOut.split("\n"); + Optional first = Arrays.stream(split) + .filter(s -> s.contains(keyword)) + .findFirst(); + if(first.isPresent()){ + Optional listening = first.map(s -> s.split("LISTENING")); + String[] strings = listening.get(); + if(strings.length == 2){ + return strings[1].trim(); + } + } + } + } + return null; + } +} \ No newline at end of file diff --git a/src/main/java/com/insigma/command/impl/StreamGobbler.java b/src/main/java/com/insigma/command/impl/StreamGobbler.java new file mode 100644 index 0000000..81d18d8 --- /dev/null +++ b/src/main/java/com/insigma/command/impl/StreamGobbler.java @@ -0,0 +1,67 @@ +package com.insigma.command.impl; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; + +import lombok.extern.slf4j.Slf4j; + +/** + * @author Vivim + */ +@Slf4j +public class StreamGobbler extends Thread { + private InputStream inputStream; + private String streamType; + private StringBuilder buf; + private volatile boolean isStopped = false; + + /** + * @param inputStream the InputStream to be consumed + * @param streamType the stream type (should be OUTPUT or ERROR) + */ + public StreamGobbler(final InputStream inputStream, final String streamType) { + this.inputStream = inputStream; + this.streamType = streamType; + this.buf = new StringBuilder(); + this.isStopped = false; + } + + /** + * Consumes the output from the input stream and displays the lines consumed + * if configured to do so. + */ + @Override + public void run() { + try { + // 默认编码为UTF-8,这里设置编码为GBK,因为WIN7的编码为GBK + InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "GBK"); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + String line = null; + while ((line = bufferedReader.readLine()) != null) { + this.buf.append(line + "\n"); + } + } catch (IOException ex) { + log.error("Failed to successfully consume and display the input stream of type " + streamType + ".", ex); + } finally { + this.isStopped = true; + synchronized (this) { + notify(); + } + } + } + + public String getContent() { + if (!this.isStopped) { + synchronized (this) { + try { + wait(); + } catch (InterruptedException ignore) { + ignore.printStackTrace(); + } + } + } + return this.buf.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/com/insigma/controller/TestController.java b/src/main/java/com/insigma/controller/TestController.java index b5a7982..604b450 100644 --- a/src/main/java/com/insigma/controller/TestController.java +++ b/src/main/java/com/insigma/controller/TestController.java @@ -1,17 +1,62 @@ package com.insigma.controller; +import com.alibaba.fastjson.JSONObject; +import com.insigma.entry.Vo; +import com.insigma.service.Computer; +import com.insigma.service.Database; +import com.insigma.service.Middleware; import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +/** + * @author Vivim + */ @Slf4j @RestController @RequestMapping("/swing") public class TestController { - @GetMapping("/hello") - public String hello(String helloWord){ - return helloWord; + @Qualifier("windowsTomcatMysql") + @Autowired + private Computer computer; + @Qualifier("windowsTomcatMysql") + @Autowired + private Database database; + @Qualifier("windowsTomcatMysql") + @Autowired + private Middleware middleware; + + @PostMapping("/runShell") + public JSONObject runShell(@RequestBody Vo vo){ + log.info("查询对象参数为:{}", vo); + boolean b = computer.runShell(vo.getShell(), false); + log.info("执行结果:{}", b); + return new JSONObject(); + } + + @PostMapping("/runBak") + public JSONObject runBak(@RequestBody Vo vo){ + log.info("查询对象参数为:{}", vo); + computer.runShell(vo.getShell(), false); + return new JSONObject(); + } + + @PostMapping("/runRestore") + public JSONObject runRestore(@RequestBody Vo vo){ + log.info("查询对象参数为:{}", vo); + computer.runShell(vo.getShell(), false); + return new JSONObject(); + } + + @PostMapping("/openServer") + public JSONObject openServer(@RequestBody Vo vo){ + log.info("查询对象参数为:{}", vo); + computer.openServer(); + return new JSONObject(); } } diff --git a/src/main/java/com/insigma/entry/ExecuteResult.java b/src/main/java/com/insigma/entry/ExecuteResult.java new file mode 100644 index 0000000..8bd83c1 --- /dev/null +++ b/src/main/java/com/insigma/entry/ExecuteResult.java @@ -0,0 +1,19 @@ +package com.insigma.entry; + +import lombok.Data; +import lombok.ToString; + +/** + * @author Vivim + */ +@Data +@ToString +public class ExecuteResult { + private int exitCode; + private String executeOut; + + public ExecuteResult(int exitCode, String executeOut) { + this.exitCode = exitCode; + this.executeOut = executeOut; + } +} \ No newline at end of file diff --git a/src/main/java/com/insigma/entry/TabColObj.java b/src/main/java/com/insigma/entry/TabColObj.java index b38ed69..d20937f 100644 --- a/src/main/java/com/insigma/entry/TabColObj.java +++ b/src/main/java/com/insigma/entry/TabColObj.java @@ -5,6 +5,7 @@ import lombok.Data; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; /** @@ -21,17 +22,7 @@ public class TabColObj { private String col; public static List getSQL(){ - return Arrays.asList( - "", - "", - "", - "", - "", - "", - "", - "", - "" - ); + return Collections.emptyList(); } public static List getData(){ return Arrays.asList( diff --git a/src/main/java/com/insigma/entry/Vo.java b/src/main/java/com/insigma/entry/Vo.java new file mode 100644 index 0000000..87ea50f --- /dev/null +++ b/src/main/java/com/insigma/entry/Vo.java @@ -0,0 +1,29 @@ +package com.insigma.entry; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * (Vo 类) + * + * @author zhangxianwei + * @since 16:40 2022/4/29 + */ +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Vo implements Serializable { + + /** + * 序列化编码ID + */ + private static final long serialVersionUID = 1L; + + private String shell; + private String serverName; + private String path; + private String filePath; +} diff --git a/src/main/java/com/insigma/service/Computer.java b/src/main/java/com/insigma/service/Computer.java index 6ef1d7e..2e48b1f 100644 --- a/src/main/java/com/insigma/service/Computer.java +++ b/src/main/java/com/insigma/service/Computer.java @@ -13,8 +13,8 @@ public interface Computer { * @param shell 执行脚本 * @return 执行执行脚本成功 */ - default boolean runShell(String shell) { - System.out.println(String.format("设置出参数:%s,但是未检测到实现应用调用此方法!", shell)); + default boolean runShell(String shell, boolean isWinCommandUtil) { + System.out.println(String.format("设置出参数:%s,%s,但是未检测到实现应用调用此方法!", shell, isWinCommandUtil)); return false; } /*** diff --git a/src/main/java/com/insigma/service/impl/LinuxTongWebKingBase.java b/src/main/java/com/insigma/service/impl/LinuxTongWebKingBase.java index 8a48f2f..4a75c45 100644 --- a/src/main/java/com/insigma/service/impl/LinuxTongWebKingBase.java +++ b/src/main/java/com/insigma/service/impl/LinuxTongWebKingBase.java @@ -27,7 +27,7 @@ import java.util.List; public class LinuxTongWebKingBase implements Computer, Database, Middleware { @Override - public boolean runShell(String shell) { + public boolean runShell(String shell, boolean isWinCommandUtil) { log.info("准备执行>> shell命令..."); try { new LinuxCommandUtil(shell).run(); @@ -93,7 +93,7 @@ public class LinuxTongWebKingBase implements Computer, Database, Middleware { return false; } log.info("停止 数据库 服务..."); - runShell("systemctl stop " + AppCfg.DB); + runShell("systemctl stop " + AppCfg.DB, false); log.info("设置 数据库 内存参数..."); FileUtil.replaceLine(AppCfg.HZB + "/kingbase/bin//TEST/kingbase.conf", @@ -104,7 +104,7 @@ public class LinuxTongWebKingBase implements Computer, Database, Middleware { String.format("effective_cache_size=%dGB", size[1])); log.info("启动 数据库 服务..."); - runShell("systemctl start " + AppCfg.DB); + runShell("systemctl start " + AppCfg.DB, false); return true; } @@ -153,7 +153,7 @@ public class LinuxTongWebKingBase implements Computer, Database, Middleware { public boolean cleanMwCache() { log.info("准备执行>> 清楚应用缓存命令..."); log.info("停止 中间件 服务..."); - runShell("systemctl stop " + AppCfg.MW); + runShell("systemctl stop " + AppCfg.MW, false); // TODO 无法确定浏览器 log.info("退出 浏览器..."); @@ -161,13 +161,13 @@ public class LinuxTongWebKingBase implements Computer, Database, Middleware { log.info("解压 新浏览器 文件..."); log.info("删除 应用 缓存文件..."); - runShell(String.format("rm -rf %s/TongWeb7/temp", AppCfg.HZB)); + runShell(String.format("rm -rf %s/TongWeb7/temp", AppCfg.HZB), false); log.info("删除 应用 日志文件..."); - runShell(String.format("rm -rf %s/TongWeb7/logs", AppCfg.HZB)); + runShell(String.format("rm -rf %s/TongWeb7/logs", AppCfg.HZB), false); log.info("启动 中间件 服务..."); - runShell("systemctl start " + AppCfg.MW); + runShell("systemctl start " + AppCfg.MW, false); return true; } @@ -185,7 +185,7 @@ public class LinuxTongWebKingBase implements Computer, Database, Middleware { return false; } log.info("停止 中间件 服务..."); - runShell("systemctl stop " + AppCfg.MW); + runShell("systemctl stop " + AppCfg.MW, false); log.info("设置 数据库 内存参数..."); FileUtil.replaceLine(AppCfg.HZB + "/bin/external.vmoptions", @@ -196,35 +196,35 @@ public class LinuxTongWebKingBase implements Computer, Database, Middleware { String.format("-Xmx%dm", size[1])); log.info("启动 中间件 服务..."); - runShell("systemctl start " + AppCfg.MW); + runShell("systemctl start " + AppCfg.MW, false); return true; } @Override public boolean startDbService() { log.info("准备执行>> 启动数据服务命令..."); - runShell("systemctl start " + AppCfg.DB); + runShell("systemctl start " + AppCfg.DB, false); return true; } @Override public boolean stopDbService() { log.info("准备执行>> 停止数据库服务命令..."); - runShell("systemctl stop " + AppCfg.DB); + runShell("systemctl stop " + AppCfg.DB, false); return true; } @Override public boolean startMwService() { log.info("准备执行>> 启动应用服务命令..."); - runShell("systemctl start " + AppCfg.MW); + runShell("systemctl start " + AppCfg.MW, false); return true; } @Override public boolean stopMwService() { log.info("准备执行>> 停止应用服务命令..."); - runShell("systemctl stop " + AppCfg.MW); + runShell("systemctl stop " + AppCfg.MW, false); return true; } diff --git a/src/main/java/com/insigma/service/impl/WindowsTomcatMysql.java b/src/main/java/com/insigma/service/impl/WindowsTomcatMysql.java index a52b9bb..069a132 100644 --- a/src/main/java/com/insigma/service/impl/WindowsTomcatMysql.java +++ b/src/main/java/com/insigma/service/impl/WindowsTomcatMysql.java @@ -1,7 +1,9 @@ package com.insigma.service.impl; import cn.hutool.db.Session; +import com.insigma.command.LocalCommandExecutor; import com.insigma.config.AppCfg; +import com.insigma.entry.ExecuteResult; import com.insigma.entry.IndexObj; import com.insigma.entry.TabColObj; import com.insigma.func.ThrowingConsumer; @@ -9,7 +11,10 @@ import com.insigma.service.Computer; import com.insigma.service.*; import com.insigma.utils.*; import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.util.CollectionUtils; +import org.thymeleaf.util.StringUtils; import java.io.File; import java.sql.SQLException; @@ -28,16 +33,21 @@ import java.util.List; @Service public class WindowsTomcatMysql implements Computer, Database, Middleware { + @Autowired + private LocalCommandExecutor localCommandExecutor; + @Override - public boolean runShell(String shell) { - log.info("准备执行>> shell命令..."); - try { + public boolean runShell(String shell, boolean isWinCommandUtil) { + if(isWinCommandUtil){ new WinCommandUtil(shell).run(); - }catch (Exception e){ - log.error("执行发生异常:{}", e.getMessage()); - return false; + log.info("执行完毕。"); + return true; + }else{ + log.info("准备执行>> shell命令..."); + ExecuteResult executeResult = localCommandExecutor.executeCommand(shell, 6000); + log.info("执行完毕。"); + return executeResult.getExitCode() == 0; } - return true; } @Override @@ -80,6 +90,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { } else { retBool = false; } + log.info("执行完毕。"); return retBool; } @@ -139,6 +150,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { log.error("判断文件:{}...不存在,请检查!", filePath); retBool = false; } + log.info("执行完毕。"); return retBool; } private boolean canNotRun(WinServiceTool.WindowsService ws, @@ -151,6 +163,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { log.error("执行发生异常:{}", e.getMessage()); canRun = false; } + log.debug("执行更新 {} 服务状态:{}", ws.getInfo(), canRun); return !canRun; } @@ -169,6 +182,8 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { sql = String.format("DROP INDEX %s ON %s", idx.getIdx(), idx.getTab()); log.debug(sql); session.execute(sql); + } catch (Exception e) { + log.error("发生错误索引:{}", e.getMessage()); }finally { sql = String.format("ALTER TABLE %s ADD INDEX %s (%s) USING BTREE", idx.getTab(), idx.getIdx(), idx.getCol()); log.debug(sql); @@ -183,6 +198,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { } session.close(); } + log.info("执行完毕。"); return retBool; } @@ -216,6 +232,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { if (canNotRun(ws, WinServiceTool.WindowsService::startService)) { return false; } + log.info("执行完毕。"); return true; } @@ -228,21 +245,25 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { log.info("创建链接..."); final Session session = DbUtil.getSession(DbUtil.url, DbUtil.usr, DbUtil.pwd, DbUtil.drive); try { - log.info("执行 预置 SQL 脚本..."); - for (String sql : sqls) { - log.debug(sql); - session.execute(sql); - } - log.info("执行 清洗数据中特殊字符串 脚本..."); - String sql; - for (String lj : DbUtil.RUBBISH) { - for (TabColObj tab : tabColObjs) { - sql = String.format("update %s set %s=replace(%s, '%s', '') where %s is not null", - tab.getTab(), tab.getCol(), tab.getCol(), lj, tab.getCol()); + if(!CollectionUtils.isEmpty(sqls)){ + log.info("执行 预置 SQL 脚本..."); + for (String sql : sqls) { log.debug(sql); session.execute(sql); } } + if(!CollectionUtils.isEmpty(tabColObjs)){ + log.info("执行 清洗数据中特殊字符串 脚本..."); + String sql; + for (String lj : DbUtil.RUBBISH) { + for (TabColObj tab : tabColObjs) { + sql = String.format("update %s set %s=replace(%s, '%s', '') where %s is not null", + tab.getTab(), tab.getCol(), tab.getCol(), lj, tab.getCol()); + log.debug(sql); + session.execute(sql); + } + } + } retBool = true; } catch (SQLException e) { log.error("执行 清洗数据中特殊字符串 发生异常:{}", e.getMessage()); @@ -253,6 +274,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { log.info("执行 清洗数据中特殊字符串 完成..."); session.close(); } + log.info("执行完毕。"); return retBool; } @@ -275,6 +297,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { String.format("%s\\mysql\\bin\\mysqld --defaults-file=%s\\mysql\\my.ini %s", AppCfg.HZB, AppCfg.HZB, AppCfg.DB))){ return false; } + log.info("执行完毕。"); return true; } @@ -283,13 +306,11 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { log.info("准备执行>> 清楚应用缓存命令..."); WinServiceTool.WindowsService ws = WinServiceTool.getService(AppCfg.MW, AppCfg.CODE); if(ws.getRunningStatus() == WinServiceTool.WindowsService.ServiceState.RUNNING){ - if (canNotRun(ws, WinServiceTool.WindowsService::stopService)) { - return false; - } + stopMwService(); } log.info("退出 浏览器..."); - runShell("taskkill /f /im " + AppCfg.BROWSER); + runShell("taskkill /f /im " + AppCfg.BROWSER, false); log.info("删除 浏览器 历史文件..."); FileUtil.delAllFile(AppCfg.HZB + "/360se6/User Data"); @@ -308,6 +329,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { if (canNotRun(ws, WinServiceTool.WindowsService::startService)) { return false; } + log.info("执行完毕。"); return true; } @@ -327,9 +349,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { log.info("停止 中间件 服务..."); WinServiceTool.WindowsService ws = WinServiceTool.getService(AppCfg.MW, AppCfg.CODE); if(ws.getRunningStatus() == WinServiceTool.WindowsService.ServiceState.RUNNING){ - if (canNotRun(ws, WinServiceTool.WindowsService::stopService)) { - return false; - } + stopMwService(); } if(WinCommandUtil.RegisterUtil.registerJava(AppCfg.HZB, size[0], size[1], size[2], size[3])){ @@ -340,6 +360,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { if (canNotRun(ws, WinServiceTool.WindowsService::startService)) { return false; } + log.info("执行完毕。"); return true; } @@ -380,6 +401,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { AppCfg.HZB)){ return false; } + log.info("执行完毕。"); return true; } @@ -397,6 +419,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { return false; } } + log.info("执行完毕。"); return false; } @@ -409,6 +432,7 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { return false; } } + log.info("执行完毕。"); return false; } @@ -420,27 +444,29 @@ public class WindowsTomcatMysql implements Computer, Database, Middleware { return !canNotRun(ws, WinServiceTool.WindowsService::startService); } if(ws.getRunningStatus() == WinServiceTool.WindowsService.ServiceState.RUNNING){ - return !canNotRun(ws, WinServiceTool.WindowsService::restartService); + stopMwService(); + log.info("已停止应用服务..."); + return startMwService(); } + log.info("执行完毕。"); return false; } @Override public boolean stopMwService() { log.info("准备执行>> 停止应用服务命令..."); - WinServiceTool.WindowsService ws = WinServiceTool.getService(AppCfg.MW, AppCfg.CODE); - if(ws.getRunningStatus() == WinServiceTool.WindowsService.ServiceState.RUNNING){ - if (canNotRun(ws, WinServiceTool.WindowsService::stopService)) { - return false; - } + String port = localCommandExecutor.getPort("netstat -ano", "54022", 6000); + if(StringUtils.isEmpty(port)){ return true; } - return false; + log.info("执行完毕。"); + return runShell("taskkill /F /PID " + port, false); } @Override public void openServer(){ log.info("准备执行>> 打开本地服务命令..."); - runShell("SERVICES.MSC"); + new WinCommandUtil("SERVICES.MSC").run(); + log.info("执行完毕。"); } } diff --git a/src/main/java/com/insigma/ui/Test.java b/src/main/java/com/insigma/ui/Test.java index 0eae614..1941c51 100644 --- a/src/main/java/com/insigma/ui/Test.java +++ b/src/main/java/com/insigma/ui/Test.java @@ -29,14 +29,14 @@ public class Test { if(Objects.isNull(computer) || Objects.isNull(database) || Objects.isNull(middleware)){ return; } - addButton(textPanel, new JButton("√ 执行shell命令"), e -> computer.runShell("SERVICES.MSC")); + addButton(textPanel, new JButton("√ 执行shell命令"), e -> computer.runShell("SERVICES.MSC", true)); addButton(textPanel, new JButton("备份"), e -> computer.runBak(AppCfg.HZB)); // addButton(textPanel, new JButton("还原"), e -> computer.runRestore("")); - addButton(textPanel, new JButton("重建索引"), e -> database.rebuildIndex(IndexObj.getData())); - addButton(textPanel, new JButton("设置数据库大小"), e -> database.setDbSize(512)); - addButton(textPanel, new JButton("清楚垃圾数据"), e -> database.cleanDbCache(TabColObj.getSQL(), TabColObj.getData())); + addButton(textPanel, new JButton("√ 重建索引"), e -> database.rebuildIndex(IndexObj.getData())); + addButton(textPanel, new JButton("√ 清楚垃圾数据"), e -> database.cleanDbCache(TabColObj.getSQL(), TabColObj.getData())); + addButton(textPanel, new JButton("设置数据库大小"), e -> database.setDbSize(64)); addButton(textPanel, new JButton("注册数据库服务"), e -> database.registrationDbService()); - addButton(textPanel, new JButton("清楚应用缓存"), e -> middleware.cleanMwCache()); + addButton(textPanel, new JButton("√ 清楚应用缓存"), e -> middleware.cleanMwCache()); addButton(textPanel, new JButton("设置中间件大小"), e -> middleware.setMwSize(128,256,512,512)); addButton(textPanel, new JButton("注册中间件服务"), e -> middleware.registrationMwService()); addButton(textPanel, new JButton("√ 启动数据库服务"), e -> database.startDbService()); diff --git a/src/main/java/com/insigma/utils/DbUtil.java b/src/main/java/com/insigma/utils/DbUtil.java index bdeeb52..26aae6d 100644 --- a/src/main/java/com/insigma/utils/DbUtil.java +++ b/src/main/java/com/insigma/utils/DbUtil.java @@ -2,6 +2,7 @@ package com.insigma.utils; import cn.hutool.db.Session; import cn.hutool.db.ds.simple.SimpleDataSource; +import lombok.extern.slf4j.Slf4j; import org.springframework.util.StringUtils; import javax.sql.DataSource; @@ -15,6 +16,7 @@ import java.util.Objects; * @author zhangxianwei * @since 15:18 2022/4/18 */ +@Slf4j public class DbUtil { private static DataSource ds; @@ -24,11 +26,8 @@ public class DbUtil { public static String drive; public static Session getSession(String url, String usr, String pwd, String drive) { + log.info("操作参数:{}, {}, {}, {}", url, usr, pwd, drive); if(Objects.isNull(ds)){ - DbUtil.url = url; - DbUtil.usr = url; - DbUtil.pwd = url; - DbUtil.drive = drive; ds = new SimpleDataSource(isDb(url), usr, pwd, drive); } return Session.create(ds); @@ -39,6 +38,7 @@ public class DbUtil { if(StringUtils.startsWithIgnoreCase(url, MYSQL)){ url += "?useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; } + log.debug("操作链接:{}", url); return url; } diff --git a/src/main/resources/templates/.keepgit b/src/main/resources/templates/.keepgit new file mode 100644 index 0000000..e69de29 diff --git a/src/test/java/com/insigma/service/impl/LinuxTongWebKingBaseTest.java b/src/test/java/com/insigma/service/impl/LinuxTongWebKingBaseTest.java index 91c1f9e..bd38348 100644 --- a/src/test/java/com/insigma/service/impl/LinuxTongWebKingBaseTest.java +++ b/src/test/java/com/insigma/service/impl/LinuxTongWebKingBaseTest.java @@ -71,7 +71,7 @@ public class LinuxTongWebKingBaseTest { @Test public void runShell() { - assertTrue(linuxTongWebKingBase.runShell("vim a.txt")); + assertTrue(linuxTongWebKingBase.runShell("vim a.txt", false)); log.info("测试完成!"); } diff --git a/src/test/java/com/insigma/service/impl/WindowsTomcatMysqlTest.java b/src/test/java/com/insigma/service/impl/WindowsTomcatMysqlTest.java index 68b7711..b812bb5 100644 --- a/src/test/java/com/insigma/service/impl/WindowsTomcatMysqlTest.java +++ b/src/test/java/com/insigma/service/impl/WindowsTomcatMysqlTest.java @@ -4,9 +4,16 @@ import com.insigma.config.AppCfg; import com.insigma.entry.IndexObj; import com.insigma.entry.TabColObj; import com.insigma.utils.DbUtil; +import com.insigma.utils.WinServiceTool; import lombok.extern.slf4j.Slf4j; import org.junit.Test; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.nio.charset.Charset; + import static org.junit.jupiter.api.Assertions.assertTrue; @Slf4j @@ -70,10 +77,56 @@ public class WindowsTomcatMysqlTest { @Test public void runShell() { - assertTrue(windowsTomcatMysql.runShell("SERVICES.MSC")); + assertTrue(windowsTomcatMysql.runShell("SERVICES.MSC", true)); log.info("测试完成!"); } + @Test + public void test() { + Runtime runtime = Runtime.getRuntime(); + String result; + try { + Process process = runtime.exec("netstat -ano | findstr 54022"); + int exitVal = process.exitValue(); + System.out.println("process exit value is " + exitVal); + InputStream inputStream = process.getInputStream(); + result = convertInputStream2Str(inputStream, Charset.defaultCharset()); + } catch (IOException e) { + log.error("执行发生异常:{}", e.getMessage()); + return; + } + String[] split = result.split("\n"); + log.info("获取对象信息:{}", split); + } + /** + * 读取输入流中的文本信息 + * + * @param input 文本输入流 + * @param charset 文本编码 + * @return + */ + private static String convertInputStream2Str(InputStream input, Charset charset) { + final char[] buffer = new char[4096]; + final StringBuilder out = new StringBuilder(); + try { + final Reader in = new InputStreamReader(input, charset); + try { + for (; ; ) { + int rsz = in.read(buffer, 0, buffer.length); + if (rsz < 0) { + break; + } + out.append(buffer, 0, rsz); + } + } finally { + in.close(); + } + } catch (Exception ex) { + log.error("执行发生异常:{}", ex.getMessage()); + } + return out.toString(); + } + @Test public void runBak() { assertTrue(windowsTomcatMysql.runBak(AppCfg.HZB)); diff --git a/src/test/java/com/insigma/utils/DbUtilTest.java b/src/test/java/com/insigma/utils/DbUtilTest.java index 5b3b39b..cbe8d37 100644 --- a/src/test/java/com/insigma/utils/DbUtilTest.java +++ b/src/test/java/com/insigma/utils/DbUtilTest.java @@ -1,16 +1,19 @@ package com.insigma.utils; import cn.hutool.db.Session; +import lombok.extern.slf4j.Slf4j; import org.junit.Test; import static org.junit.jupiter.api.Assertions.*; import java.sql.SQLException; +@Slf4j public class DbUtilTest { @Test public void getSessionTest() throws SQLException { Session session = DbUtil.getSession("jdbc:mysql://127.0.0.1:35017/hy_qggwy", "root", "admin", "com.mysql.jdbc.Driver"); - String queryString = session.queryString("select count(1) from a01 limit 1"); + String queryString = session.queryString("select count(1) from a01"); + log.info("对象:{} >> 查询带数据:{}", session, queryString); assertNotEquals("0", queryString); } } \ No newline at end of file