java的swing案例
一、需求
1、选择springboot配置文件,修改数据库等连接信息
2、修改完成后,点击重启按钮,重启springboot项目
3、重启放在tomcat的webapp下的vue项目dist
注意:是重启!!!,要先关闭再启动,不能直接启动,会端口冲突
二、效果图
选择文件后显示重启按钮
三、完整代码:
package ToolDemo;
import java.awt.Container;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class PropertiesTool extends Frame implements ActionListener {
/**
* @author Eric
* @Time 2021年6月7日
*
*/
private static final long serialVersionUID = 1L;
private static final String String = null;
public static void main(String[] args) {
new PropertiesTool();
}
JFrame frame = new JFrame("配置管理工具");// 框架布局
JTabbedPane tabPane = new JTabbedPane();// 选项卡布局
Container conKuguan = new Container();//
JLabel label1 = new JLabel("系统目录:");
JTextField text1 = new JTextField();// 文件的路径
JButton buttonChoose1 = new JButton("选择");// 选择
JLabel label2 = new JLabel("配置文件目录:");
JTextField text2 = new JTextField();// 文件的路径
JButton buttonChoose2 = new JButton("选择");// 选择
JLabel label3 = new JLabel("主机:");
JLabel label4 = new JLabel("数据库相关配置");
JLabel label5 = new JLabel("端口号:");
JLabel label6 = new JLabel("用户名:");
JLabel label7 = new JLabel("密码:");
JLabel label8 = new JLabel("库名称:");
// 数据库相关
JTextField text3 = new JTextField();// 主机
JTextField text5 = new JTextField();// 端口号
JTextField text6 = new JTextField();// 用户名
JTextField text7 = new JTextField();// 密码
JTextField text8 = new JTextField();// 库名称
JButton buttonRestart = new JButton();//
JFileChooser jfc = new JFileChooser();// 文件选择器
PropertiesTool() {
jfc.setCurrentDirectory(new File("c://Users//EDZ//Desktop//库管系统//db-manager"));// 文件选择器的初始目录定为c盘
double lx = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
double ly = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
frame.setLocation(new Point((int) (lx / 2) - 400, (int) (ly / 2) - 400));// 设定窗口出现位置
frame.setSize(880, 800);// 设定窗口大小
frame.setContentPane(tabPane);// 设置布局
label1.setBounds(20, 10, 90, 30);
text1.setBounds(115, 10, 520, 30);
conKuguan.add(label1);
conKuguan.add(text1);
buttonChoose1.setBounds(640, 10, 50, 30);
buttonChoose1.addActionListener(this); // 添加事件处理
conKuguan.add(buttonChoose1);
label2.setBounds(20, 45, 90, 30);
text2.setBounds(115, 45, 520, 30);
conKuguan.add(label2);
conKuguan.add(text2);
buttonChoose2.setBounds(640, 45, 50, 30);
buttonChoose2.addActionListener(this); // 添加事件处理
conKuguan.add(buttonChoose2);
label3.setBounds(20, 135, 90, 30);
label4.setBounds(20, 100, 1000, 30);
label5.setBounds(20, 175, 1000, 30);
label6.setBounds(20, 215, 1000, 30);
label7.setBounds(20, 255, 1000, 30);
label8.setBounds(20, 295, 1000, 30);
text3.setBounds(115, 135, 220, 30);
text5.setBounds(115, 175, 220, 30);
text6.setBounds(115, 215, 220, 30);
text7.setBounds(115, 255, 220, 30);
text8.setBounds(115, 295, 220, 30);
conKuguan.add(label3);
conKuguan.add(text3);
conKuguan.add(label5);
conKuguan.add(text5);
conKuguan.add(label6);
conKuguan.add(text6);
conKuguan.add(label7);
conKuguan.add(text7);
conKuguan.add(label8);
conKuguan.add(text8);
conKuguan.add(label4);
buttonRestart.setBounds(410, 570, 60, 30);
// 隐藏重启按钮
buttonRestart.setOpaque(false);// 按钮透明度
buttonRestart.setContentAreaFilled(false);// 按钮背景透明度
buttonRestart.setBorderPainted(false);// 按钮边框隐藏
conKuguan.add(buttonRestart);
buttonRestart.addActionListener(this); // 添加事件处理
frame.setVisible(true);// 窗口可见
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 使能关闭窗口,结束程序
tabPane.add("库管", conKuguan);// 添加布局1
}
/**
* 时间监听的方法
*/
public void actionPerformed(ActionEvent e) {
// 绑定到选择文件,先择文件事件
if (e.getSource().equals(buttonChoose1)) {
jfc.setFileSelectionMode(1);// 设定只能选择到文件
int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
if (state == 1) {
return;// 撤销则返回
} else {
File f = jfc.getSelectedFile();// f为选择到的文件
text1.setText(f.getAbsolutePath());
}
}
if (e.getSource().equals(buttonChoose2)) {
jfc.setFileSelectionMode(0);// 设定只能选择到文件
int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
if (state == 1) {
return;// 撤销则返回
} else {
File f = jfc.getSelectedFile();// f为选择到的文件
text2.setText(f.getAbsolutePath());
// 读取配置文件内容
Map readProperties = ReadProperties(f.getAbsolutePath());
if (readProperties.get("status").equals("error")) {
JOptionPane.showMessageDialog(null, "配置文件读取错误,请检查文件内容", "提示", 2);
System.exit(1);
} else {
try {
String host = (String) readProperties.get("host");
String port = (String) readProperties.get("port");
String username = (String) readProperties.get("username");
String password = (String) readProperties.get("password");
String database = (String) readProperties.get("database");
text3.setText(host);
text5.setText(port);
text6.setText(username);
text7.setText(password);
text8.setText(database);
buttonRestart.setText("重启");
buttonRestart.setOpaque(true);//
buttonRestart.setContentAreaFilled(true); // 显示重启按钮
buttonRestart.setBorderPainted(true);// 按钮边框隐藏
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, "数据库配置项读取错误,请检查配置内容", "提示", 2);
System.exit(1);
}
}
}
}
if (e.getSource().equals(buttonRestart)) {
StringBuffer sb = new StringBuffer("jdbc:postgresql://");
java.lang.String host = text3.getText();
java.lang.String port = text5.getText();
java.lang.String username = text6.getText();
java.lang.String password = text7.getText();
java.lang.String database = text8.getText();
// jdbc:postgresql://localhost:5432/resources
sb.append(host).append(":").append(port).append("/").append(database);
java.lang.String absolutePath = jfc.getSelectedFile().getAbsolutePath();// f为选择到的文件
boolean writeProperties = writeProperties(absolutePath, sb.toString(), username, password);
if (writeProperties) {
boolean startBatShell = startBatShell();
if (startBatShell) {
JOptionPane.showMessageDialog(null, "正在重启中,请确定。。。", "提示", 2);
System.exit(1);
} else {
JOptionPane.showMessageDialog(null, "修改数据库配置成功,但未找到启动服务脚本", "提示", 2);
System.exit(1);
}
} else {
JOptionPane.showMessageDialog(null, "修改数据库配置失败!", "提示", 2);
System.exit(1);
}
}
}
private Map<String, String> ReadProperties(String absolutePath) {
Map<String, String> map = new HashMap<String, String>();
Properties p = new Properties();
try {
InputStream is = new FileInputStream(new File(absolutePath));
p.load(is);
String url = p.getProperty("spring.datasource.url");
java.lang.String[] splitUrl = url.split("//");
java.lang.String[] splitHost = splitUrl[1].split(":");
java.lang.String[] splitPort = splitHost[1].split("/");
String host = splitHost[0];
String port = splitPort[0];
String database = splitPort[1];
String username = p.getProperty("spring.datasource.username");
String password = p.getProperty("spring.datasource.password");
map.put("status", "success");
map.put("host", host);
map.put("port", port);
map.put("username", username);
map.put("password", password);
map.put("database", database);
} catch (Exception e) {
map.put("status", "error");
e.printStackTrace();
}
return map;
}
private boolean writeProperties(java.lang.String absolutePath, java.lang.String url, java.lang.String username,
java.lang.String password) {
FileInputStream iFile = null;
FileOutputStream oFile = null;
try {
iFile = new FileInputStream(absolutePath);
Properties p = new Properties();
p.load(iFile);
p.setProperty("spring.datasource.url", url);
p.setProperty("spring.datasource.username", username);
p.setProperty("spring.datasource.password", password);
oFile = new FileOutputStream(absolutePath);
// 将Properties中的属性列表(键和元素对)写入输出流
// p.store(oFile, "");
Enumeration<?> e = p.propertyNames();
// 这里不使用Properties的store()方法,因为冒号会被转义
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = p.getProperty(key);
String s = key + "=" + value + "\n";
oFile.write(s.getBytes());
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
try {
iFile.close();
oFile.flush();
oFile.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
return true;
}
boolean startBatShell() {
String cmdServe = "cmd /c start " + text1.getText() + "\\server";
String cmdWeb = "cmd /c start " + text1.getText() + "\\web";
try {
Process psServe = Runtime.getRuntime().exec(cmdServe);
Process psWeb = Runtime.getRuntime().exec(cmdWeb);
psServe.waitFor();
psWeb.waitFor();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
四、.bat脚本
1、springboot重启脚本
新建server.bat
,写入以下代码保存
@title biz-server
@REM *************************************************************************
@REM This script is used to start biz-server.
@REM
@REM System will load all jar-packages in 'lib' directory
@REM *************************************************************************
@set JAVA_VM=-XX:PermSize=64M -XX:MaxNewSize=2048m -XX:MaxPermSize=2048m -Djava.awt.headless=true -Xmx2048m -Xms2048m
@set JAVA_OPTIONS=
@set DEPLOY_PATH=%cd%
set port=8084
for /f "tokens=1-5" %%i in ('netstat -ano^|findstr ":%port%"') do (
echo kill the process %%m who use the port
taskkill /pid %%m -t -f
goto start
)
:start
java -jar stock-apply.jar
@pause
特殊说明:脚本的下面这段是查出后台服务端口8084的PID,再杀死进程,需要修改端口号为你自己的后台服务端口
set port=8084
for /f "tokens=1-5" %%i in ('netstat -ano^|findstr ":%port%"') do (
echo kill the process %%m who use the port
taskkill /pid %%m -t -f
goto start
)
:start
2、重启tomcat脚本
思考:tomcat的bin目录下有自带的启动startup.bat
和关闭shutdown.bat
脚本,但怎么才能重启呢?要分别执行这俩bat吗?
尝试:我将shutdown.bat
的shell脚本拷贝到startup.bat
的上面,然后将startup.bat
重命名为web.bat
后保存
结果:重复点击web.bat,是可以先关闭上一个tomcat再启动,成功了!!!
脚本如下:
@echo off
rem Licensed to the Apache Software Foundation (ASF) under one or more
rem contributor license agreements. See the NOTICE file distributed with
rem this work for additional information regarding copyright ownership.
rem The ASF licenses this file to You under the Apache License, Version 2.0
rem (the "License"); you may not use this file except in compliance with
rem the License. You may obtain a copy of the License at
rem
rem http://www.apache.org/licenses/LICENSE-2.0
rem
rem Unless required by applicable law or agreed to in writing, software
rem distributed under the License is distributed on an "AS IS" BASIS,
rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rem See the License for the specific language governing permissions and
rem limitations under the License.
rem ---------------------------------------------------------------------------
rem Stop script for the CATALINA Server
rem ---------------------------------------------------------------------------
setlocal
rem Guess CATALINA_HOME if not defined
set "CURRENT_DIR=%cd%"
if not "%CATALINA_HOME%" == "" goto gotHome
set "CATALINA_HOME=%CURRENT_DIR%"
if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
cd ..
set "CATALINA_HOME=%cd%"
cd "%CURRENT_DIR%"
:gotHome
if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
echo The CATALINA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program
goto end
:okHome
set "EXECUTABLE=%CATALINA_HOME%\bin\catalina.bat"
rem Check that target executable exists
if exist "%EXECUTABLE%" goto okExec
echo Cannot find "%EXECUTABLE%"
echo This file is needed to run this program
goto end
:okExec
rem Get remaining unshifted command line arguments and save them in the
set CMD_LINE_ARGS=
:setArgs
if ""%1""=="""" goto doneSetArgs
set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
shift
goto setArgs
:doneSetArgs
call "%EXECUTABLE%" stop %CMD_LINE_ARGS%
:end
@echo off
rem Licensed to the Apache Software Foundation (ASF) under one or more
rem contributor license agreements. See the NOTICE file distributed with
rem this work for additional information regarding copyright ownership.
rem The ASF licenses this file to You under the Apache License, Version 2.0
rem (the "License"); you may not use this file except in compliance with
rem the License. You may obtain a copy of the License at
rem
rem http://www.apache.org/licenses/LICENSE-2.0
rem
rem Unless required by applicable law or agreed to in writing, software
rem distributed under the License is distributed on an "AS IS" BASIS,
rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rem See the License for the specific language governing permissions and
rem limitations under the License.
rem ---------------------------------------------------------------------------
rem Start script for the CATALINA Server
rem ---------------------------------------------------------------------------
setlocal
rem Guess CATALINA_HOME if not defined
set "CURRENT_DIR=%cd%"
if not "%CATALINA_HOME%" == "" goto gotHome
set "CATALINA_HOME=%CURRENT_DIR%"
if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
cd ..
set "CATALINA_HOME=%cd%"
cd "%CURRENT_DIR%"
:gotHome
if exist "%CATALINA_HOME%\bin\catalina.bat" goto okHome
echo The CATALINA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program
goto end
:okHome
set "EXECUTABLE=%CATALINA_HOME%\bin\catalina.bat"
rem Check that target executable exists
if exist "%EXECUTABLE%" goto okExec
echo Cannot find "%EXECUTABLE%"
echo This file is needed to run this program
goto end
:okExec
rem Get remaining unshifted command line arguments and save them in the
set CMD_LINE_ARGS=
:setArgs
if ""%1""=="""" goto doneSetArgs
set CMD_LINE_ARGS=%CMD_LINE_ARGS% %1
shift
goto setArgs
:doneSetArgs
call "%EXECUTABLE%" start %CMD_LINE_ARGS%
:end
五、测试
- 系统文件如下:
- server文件夹是后台服务代码
- web文件夹是tomcat,里面含有vue打包后的dist
- server脚本,重启后台jar
- web脚本,重启tomcat
- 后台系统配置文件如下:
- 选择系统所放目录,选择后台系统配置文件后会自动读出数据库配置信息,修改后点击重启
- 可以看到已经成功重启了,点击确定,就可以关闭修改工具了
六、完善
以前是再开发工具执行的java程序,现在我将此工具程序打包成.exe,可双击使用,如下图
具体将java程序打包成exe参考:以下博客
将java swing写的用程序打包exe可执行程序-------使用exe4j将java文件打成exe文件运行详细教程,The JVM found at JAVA_HOME is damaged问题解决------生成ico图标网站
注意,启动程序或打包的时候记得带上VM参数-Dfile.encoding=gbk
,否则中文可能会乱码
七、补充一些可能对文件操作的小demo
比如,读取C:\\Software\\mongodb
下面的所有文件名称
File[] list = new File("C:\\Software\\mongodb").listFiles();
for (File file : list) {
String datname = org.apache.commons.io.FilenameUtils.getBaseName(file.getName());
System.out.println(datname);
}
八、案例二
- 效果图
2.完整代码:
package ChangeIpTool;
import java.awt.Color;
import java.awt.Container;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import org.postgresql.util.PSQLException;
import com.mongodb.MongoClient;
public class IpTool extends Frame implements ActionListener {
/**
* @author Eric
* @Time 2021年6月30日
*
*/
private static final long serialVersionUID = 1L;
private static final String String = null;
private MongoClient mongoClient = null;
public static void main(String[] args) {
new IpTool();
}
JFrame frame = new JFrame();// 框架布局
JFrame frameAuto = new JFrame();
JTabbedPane tabPane = new JTabbedPane();// 选项卡布局
Container conKuguan = new Container();//
JLabel label1 = new JLabel("系统目录:");
JTextField text1 = new JTextField(System.getProperty("user.dir"));// 文件的路径
JButton buttonChoose1 = new JButton("选择");// 选择
JLabel labelMapServer = new JLabel("服务引擎:");
JLabel labelGis = new JLabel("空间数据库:");
JLabel labelApp = new JLabel("业务系统IP:");
JLabel dbEnv = new JLabel("一一一一一一一一一一一一一一一一一一一一一一一一一一数据库环境一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一");
JLabel IPEnv = new JLabel("一一一一一一一一一一一一一一一一一一一一一一一一一一服务器配置一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一一");
JLabel dbSystem = new JLabel("系统:");
JLabel dbVersion = new JLabel("当前版本:");
JLabel dbIP = new JLabel("服务器:");
JLabel dbUsr = new JLabel("用户名:");
JLabel dbPwd = new JLabel("密码:");
JLabel dbAction = new JLabel("操作:");
JButton dbUninstall = new JButton("卸载");// 选择
JButton dbInstall = new JButton("安装");// 选择
JButton dbCreate = new JButton("建表");// 选择
JTextField textDbSystem = new JTextField("Postgres");// 系统
JTextField textDbVersion = new JTextField();// 当前版本
JTextField textDbIP = new JTextField(getLocalIp());// 服务器
JTextField textDbUsr = new JTextField("postgres");// 用户名
JTextField textDbPwd = new JTextField("qQq314159@26");// 密码
JLabel textDbPwdError = new JLabel();// 密码不符提醒
// JTextField textMongoSystem = new JTextField("Mongodb");// 系统
// JTextField textMongoVersion = new JTextField();// 当前版本
// JTextField textMongoIP = new JTextField("localhost");// 服务器
// JTextField textMongoUsr = new JTextField();// 用户名
// JTextField textMongoPwd = new JTextField();// 密码
// JButton mongoUninstall = new JButton("卸载");// 选择
// JButton mongoInstall = new JButton("安装");// 选择
// JButton mongoCreate = new JButton("建表");// 选择
// 数据库相关
JTextField textMapServer = new JTextField();// 服务引擎
JTextField textGis = new JTextField();// 空间数据库
JTextField textApp = new JTextField();// 应用IP
JButton buttonRestart = new JButton("重启服务");//
JButton buttonDataReuse = new JButton("数据复用");//
JFileChooser jfc = new JFileChooser();// 文件选择器
IpTool() {
String dbVer = getDbVersion(textDbUsr.getText(), textDbPwd.getText());
if (dbVer.equals("error")) {
textDbPwdError.setText("与指定密码qQq314159@26不符");
textDbPwdError.setForeground(Color.RED);
textDbPwdError.setBounds(100, 210, 200, 30);
conKuguan.add(textDbPwdError);
textDbVersion.setText("未知");
} else {
textDbVersion.setText(dbVer);
}
// String mongoVer = getMongoInfo();
// textMongoVersion.setText(mongoVer);
jfc.setCurrentDirectory(new File(System.getProperty("user.dir")));// 文件选择器的初始目录定为c盘
double lx = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
double ly = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
frame.setLocation(new Point((int) (lx / 2) - 500, (int) (ly / 2) - 400));// 设定窗口出现位置
frame.setResizable(false);
frame.setSize(800, 800);// 设定窗口大小
frame.setTitle("配置管理工具");
frame.setContentPane(tabPane);// 设置布局
label1.setBounds(20, 30, 90, 30);
text1.setBounds(115, 30, 550, 30);
conKuguan.add(label1);
text1.setEditable(false);
conKuguan.add(text1);
buttonChoose1.setBounds(680, 30, 85, 30);
buttonChoose1.addActionListener(this); // 添加事件处理
conKuguan.add(buttonChoose1);
dbEnv.setBounds(0, 80, 1000, 30);
conKuguan.add(dbEnv);
IPEnv.setBounds(0, 300, 1000, 30);
conKuguan.add(IPEnv);
dbSystem.setBounds(40, 130, 80, 30);
conKuguan.add(dbSystem);
textDbSystem.setBounds(20, 180, 80, 30);
textDbSystem.setEditable(false);
conKuguan.add(textDbSystem);
dbVersion.setBounds(140, 130, 180, 30);
conKuguan.add(dbVersion);
textDbVersion.setBounds(100, 180, 180, 30);
textDbVersion.setEditable(false);
conKuguan.add(textDbVersion);
dbAction.setBounds(640, 130, 200, 30);
conKuguan.add(dbAction);
dbUninstall.setBounds(575, 180, 60, 30);
dbUninstall.addActionListener(this); // 添加事件处理
conKuguan.add(dbUninstall);
dbInstall.setBounds(640, 180, 60, 30);
dbInstall.addActionListener(this); // 添加事件处理
conKuguan.add(dbInstall);
dbCreate.setBounds(705, 180, 60, 30);
dbCreate.addActionListener(this); // 添加事件处理
conKuguan.add(dbCreate);
dbIP.setBounds(300, 130, 90, 30);
conKuguan.add(dbIP);
textDbIP.setBounds(280, 180, 90, 30);
textDbIP.setEditable(false);
conKuguan.add(textDbIP);
dbUsr.setBounds(390, 130, 90, 30);
conKuguan.add(dbUsr);
textDbUsr.setBounds(371, 180, 90, 30);
conKuguan.add(textDbUsr);
dbPwd.setBounds(490, 130, 110, 30);
conKuguan.add(dbPwd);
textDbPwd.setBounds(461, 180, 110, 30);
conKuguan.add(textDbPwd);
// textMongoSystem.setBounds(20, 230, 80, 30);
// textMongoSystem.setEditable(false);
// conKuguan.add(textMongoSystem);
// textMongoVersion.setBounds(100, 230, 180, 30);
// textMongoVersion.setEditable(false);
// conKuguan.add(textMongoVersion);
// textMongoIP.setBounds(280, 230, 90, 30);
// textMongoIP.setEditable(false);
// conKuguan.add(textMongoIP);
// textMongoUsr.setBounds(371, 230, 90, 30);
// conKuguan.add(textMongoUsr);
// textMongoPwd.setBounds(461, 230, 110, 30);
// conKuguan.add(textMongoPwd);
// mongoUninstall.setBounds(575, 230, 60, 30);
// mongoUninstall.addActionListener(this); // 添加事件处理
// conKuguan.add(mongoUninstall);
// mongoInstall.setBounds(640, 230, 60, 30);
// mongoInstall.addActionListener(this); // 添加事件处理
// conKuguan.add(mongoInstall);
// mongoCreate.setBounds(705, 230, 60, 30);
// mongoCreate.addActionListener(this); // 添加事件处理
// conKuguan.add(mongoCreate);
labelMapServer.setBounds(20, 345, 90, 30);
labelGis.setBounds(20, 395, 1000, 30);
labelApp.setBounds(20, 445, 1000, 30);
textMapServer.setBounds(115, 345, 650, 30);
textGis.setBounds(115, 395, 650, 30);
textApp.setBounds(115, 445, 650, 30);
String localIp = getLocalIp();
textApp.setText(localIp);
conKuguan.add(labelMapServer);
conKuguan.add(labelGis);
conKuguan.add(labelApp);
conKuguan.add(textMapServer);
conKuguan.add(textGis);
conKuguan.add(textApp);
buttonRestart.setBounds(410, 520, 100, 30);
conKuguan.add(buttonRestart);
buttonRestart.addActionListener(this); // 添加事件处理
buttonDataReuse.setBounds(290, 520, 100, 30);
conKuguan.add(buttonDataReuse);
buttonDataReuse.addActionListener(this); // 添加事件处理
frame.setVisible(true);// 窗口可见
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 使能关闭窗口,结束程序
conKuguan.setBackground(new Color(255, 0, 0));
tabPane.add("IP配置", conKuguan);// 添加布局1
}
private java.lang.String getLocalIp() {
try {
InetAddress ip4 = Inet4Address.getLocalHost();
return ip4.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
return "localhost";
}
}
private String getDbVersion(String usr, String pwd) {
try {
Connection conn = CreatControllerNew.getConn1(usr, pwd, "postgres");
DatabaseMetaData info = conn.getMetaData();
return info.getDatabaseProductVersion();
} catch (PSQLException e1) {
e1.printStackTrace();
return "error";
} catch (Exception e) {
e.printStackTrace();
return "未安装";
}
}
// private java.lang.String getMongoInfo() {
// java.lang.String mongoPort = startBatShell("cmd /c netstat -aon|findstr 27017");
// if (mongoPort.equals("")) {
// return "未安装";
// } else {
// // 连接到 mongodb 服务
// mongoClient = new MongoClient("localhost", 27017);
// MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");
// MongoCollection<Document> collection = mongoDatabase.getCollection("system.version");
// FindIterable<Document> findIterable = collection.find();
// MongoCursor<Document> mongoCursor = findIterable.iterator();
// while (mongoCursor.hasNext()) {
// Document id = mongoCursor.next();
// Object object = id.get("version");
// return object.toString();
// }
// }
// return "未安装";
// }
/**
* 时间监听的方法
*/
public void actionPerformed(ActionEvent e) {
// 绑定到选择文件,先择文件事件
if (e.getSource().equals(buttonChoose1)) {
jfc.setFileSelectionMode(1);// 设定只能选择到文件
int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
if (state == 1) {
return;// 撤销则返回
} else {
File f = jfc.getSelectedFile();// f为选择到的文件
text1.setText(f.getAbsolutePath());
}
}
if (e.getSource().equals(dbInstall)) {
startBatShell("cmd /c start " + text1.getText() + "\\postgresql-12.7-2-windows-x64.exe");
startBatShell("cmd /c start " + text1.getText() + "\\postgis-bundle-pg12x64-setup-3.1.1-2.exe");
}
if (e.getSource().equals(dbUninstall)) {
startBatShell("cmd /c start " + text1.getText() + "\\uninstall-postgresql.exe");
}
// if (e.getSource().equals(mongoInstall) || e.getSource().equals(mongoUninstall)) {
// startBatShell("cmd /c start " + text1.getText() + "\\mongodb-win32-x86_64-2008plus-ssl-4.0.25-signed.msi");
// }
if (e.getSource().equals(dbCreate)) {
java.lang.String usr = textDbUsr.getText();
java.lang.String pwd = textDbPwd.getText();
JOptionPane op = new JOptionPane("本对话框将在10秒后关闭", JOptionPane.INFORMATION_MESSAGE);
final JDialog dialog = op.createDialog("postgres数据还原中...");
new Thread(() -> {
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setAlwaysOnTop(true);
dialog.setModal(false);
dialog.setVisible(true);
}).start();
try {
CreatControllerNew creatControllerNew = new CreatControllerNew();
try {
creatControllerNew.dropdatabase(usr, pwd, text1.getText());
List<File> pg_sql = creatControllerNew.printTableName(usr, pwd, text1.getText());
for (File file : pg_sql) {
String datname = org.apache.commons.io.FilenameUtils.getBaseName(file.getName());
if (datname.equals("runtime")) {
continue;
}
String cmd = "cmd /c start " + text1.getText()
+ "\\postgres\\runtime\\pg_restore.exe --host \"localhost\" --port \"5432\" --username \"postgres\" --role \"postgres\" --dbname "
+ datname + " --verbose " + text1.getText() + "\\postgres\\" + file.getName();
startBatShell(cmd);
}
dialog.setVisible(false);
dialog.dispose();
JOptionPane.showMessageDialog(null, "pg库表还原成功", "提示", 2);
} catch (Exception e2) {
e2.printStackTrace();
dialog.setVisible(false);
dialog.dispose();
JOptionPane.showMessageDialog(null, "pg库表还原失败,用户名或密码错误", "提示", 2);
System.exit(0);
}
} catch (Exception e1) {
dialog.setVisible(false);
dialog.dispose();
JOptionPane.showMessageDialog(null, "pg库表还原失败", "提示", 2);
e1.printStackTrace();
}
}
// 成果复制,执行替换pg库ip的脚本
if (e.getSource().equals(buttonDataReuse)) {
int opt = JOptionPane.showConfirmDialog(conKuguan, "确定替换数据IP?", "确认信息", JOptionPane.YES_NO_OPTION);
if (opt == JOptionPane.YES_OPTION) {
java.lang.String ipMapServer = textMapServer.getText();
java.lang.String ipGis = textGis.getText();
java.lang.String ipApp = textApp.getText();
if (ipMapServer.equals("") || ipGis.equals("") || ipApp.equals("")) {
// startBatShell("cmd /c start " + text1.getText() + "\\run");
JOptionPane.showMessageDialog(null, "必须填写IP", "提示", 2);
return;
}
// 读取需要替换的mapserverIP
java.lang.String mapServerIpChangeTxt = readIpChangeTxt(
text1.getText() + "\\config\\changeMapServerIp.txt");
if ("".equals(mapServerIpChangeTxt) || null == mapServerIpChangeTxt) {
JOptionPane.showMessageDialog(null,
"未读取到原mapserver的IP,请检查:" + text1.getText() + "\\config\\changeMapServerIp.txt", "提示", 2);
return;
}
// 读取需要替换的空间数据库IP
java.lang.String gisChangeTxt = readIpChangeTxt(text1.getText() + "\\config\\changeGisIp.txt");
if ("".equals(gisChangeTxt) || null == gisChangeTxt) {
JOptionPane.showMessageDialog(null,
"未读取到原空间数据库的IP,请检查:" + text1.getText() + "\\config\\changeGisIp.txt", "提示", 2);
return;
}
// 读取需要替换的业务数据库IP
java.lang.String appChangeTxt = readIpChangeTxt(text1.getText() + "\\config\\changeAppIp.txt");
if ("".equals(appChangeTxt) || null == appChangeTxt) {
JOptionPane.showMessageDialog(null,
"未读取到原业务数据库的IP,请检查:" + text1.getText() + "\\config\\changeAppIp.txt", "提示", 2);
return;
}
replaceIP(text1.getText() + "\\nodejstext\\exec.js", ipMapServer, mapServerIpChangeTxt);
replaceIP(text1.getText() + "\\nodejstext\\platformUpdateExec.js", ipApp, appChangeTxt);
replaceIP(text1.getText() + "\\nodejstext\\naturalUpdateExec.js", ipApp, appChangeTxt);
replaceIP(text1.getText() + "\\nodejstext\\exec.js", ipApp, appChangeTxt);
replaceIP(text1.getText() + "\\nodejstext\\platformUpdateExec.js", ipMapServer, mapServerIpChangeTxt);
replaceIP(text1.getText() + "\\nodejstext\\naturalUpdateExec.js", ipMapServer, mapServerIpChangeTxt);
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
startBatShell("cmd /c start " + text1.getText() + "\\nodejstext\\run");
}
}
// 替换并重启
if (e.getSource().equals(buttonRestart)) {
java.lang.String ipMapServer = textMapServer.getText();
java.lang.String ipGis = textGis.getText();
java.lang.String ipApp = textApp.getText();
if (ipMapServer.equals("") || ipGis.equals("") || ipApp.equals("")) {
// startBatShell("cmd /c start " + text1.getText() + "\\run");
JOptionPane.showMessageDialog(null, "必须填写IP", "提示", 2);
return;
} else {
// 读取需要替换的mapserverIP
java.lang.String mapServerIpChangeTxt = readIpChangeTxt(
text1.getText() + "\\config\\changeMapServerIp.txt");
if ("".equals(mapServerIpChangeTxt) || null == mapServerIpChangeTxt) {
JOptionPane.showMessageDialog(null,
"未读取到原mapserver的IP,请检查:" + text1.getText() + "\\config\\changeMapServerIp.txt", "提示", 2);
return;
}
// 读取需要替换的空间数据库IP
java.lang.String gisChangeTxt = readIpChangeTxt(text1.getText() + "\\config\\changeGisIp.txt");
if ("".equals(gisChangeTxt) || null == gisChangeTxt) {
JOptionPane.showMessageDialog(null,
"未读取到原空间数据库的IP,请检查:" + text1.getText() + "\\config\\changeGisIp.txt", "提示", 2);
return;
}
// 读取需要替换的业务数据库IP
java.lang.String appChangeTxt = readIpChangeTxt(text1.getText() + "\\config\\changeAppIp.txt");
if ("".equals(appChangeTxt) || null == appChangeTxt) {
JOptionPane.showMessageDialog(null,
"未读取到原业务数据库的IP,请检查:" + text1.getText() + "\\config\\changeAppIp.txt", "提示", 2);
return;
}
// 修改java接口
File[] serverList = new File(text1.getText() + "\\server\\webapps").listFiles();
if (serverList != null && serverList.length > 0) {
for (File file : serverList) {
String pathStr = "";
if (file.getName().equals("quality")) {
pathStr = text1.getText() + "\\server\\webapps\\" + file.getName()
+ "\\resources\\application.properties";
} else {
pathStr = text1.getText() + "\\server\\webapps\\" + file.getName()
+ "\\WEB-INF\\classes\\application.properties";
}
File filePath = new File(pathStr);
if (filePath.exists()) {
// 修改应用系统IP
replaceIP(pathStr, ipApp, appChangeTxt);
// 修改mapserver的IP
replaceIP(pathStr, ipMapServer, mapServerIpChangeTxt);
}
}
} else {
JOptionPane.showMessageDialog(null, "未找到server文件夹", "提示", 2);
System.exit(1);
}
// 修改目录系统(singleportal)Mongodb
replaceIP(text1.getText() + "\\singleportal\\conf\\cfg\\db.properties", ipMapServer,
mapServerIpChangeTxt);
replaceIP(text1.getText() + "\\singleportal\\conf\\cfg\\db.properties", ipApp, appChangeTxt);
replaceIP(text1.getText() + "\\singleportal\\conf\\cfg\\appSetting.properties", ipMapServer,
mapServerIpChangeTxt);
replaceIP(text1.getText() + "\\singleportal\\conf\\cfg\\appSetting.properties", ipApp, appChangeTxt);
// 修改用户管理和资源共享模块(biz-server)
replaceIP(text1.getText() + "\\web\\resources\\application.properties", ipApp, appChangeTxt);
replaceIP(text1.getText() + "\\web\\resources\\application.properties", ipMapServer,
mapServerIpChangeTxt);
// replaceBizProperties(text1.getText() + "\\web\\resources\\application.properties", ipApp, ipMapServer);
// 修改前端地址
File[] webList = new File(text1.getText() + "\\web\\webapps").listFiles();
if (webList != null && webList.length > 0) {
for (File file : webList) {
if (file.getName().equals("exchange")) {
// 修改应用系统IP
replaceIP(
text1.getText() + "\\web\\webapps\\" + file.getName() + "\\static\\commonConfig.js",
ipApp, appChangeTxt);
replaceIP(text1.getText() + "\\web\\webapps\\" + file.getName() + "\\config\\k-config.yml",
ipApp, appChangeTxt);
}
File filePath = new File(
text1.getText() + "\\web\\webapps\\" + file.getName() + "\\static\\config.js");
if (filePath.exists()) {
// 修改前端项目应用系统IP
replaceIP(text1.getText() + "\\web\\webapps\\" + file.getName() + "\\static\\config.js",
ipApp, appChangeTxt);
// 修改前端项目mapserver的IP
replaceIP(text1.getText() + "\\web\\webapps\\" + file.getName() + "\\static\\config.js",
ipMapServer, mapServerIpChangeTxt);
}
}
} else {
JOptionPane.showMessageDialog(null, "未找到web文件夹", "提示", 2);
System.exit(1);
}
// 修改vectortile
replaceIP(text1.getText()
+ "\\vectortile\\apache-tomcat-8.5.34\\webapps\\cuttile-server\\WEB-INF\\classes\\conf\\database.properties",
ipApp, appChangeTxt);
replaceIP(text1.getText()
+ "\\vectortile\\apache-tomcat-8.5.34\\webapps\\cuttile-server\\WEB-INF\\classes\\conf\\tilemanager.properties",
ipMapServer, mapServerIpChangeTxt);
replaceIP(text1.getText()
+ "\\vectortile\\apache-tomcat-8.5.34\\webapps\\data-server\\WEB-INF\\classes\\dataserverdb.properties",
ipApp, appChangeTxt);
replaceIP(text1.getText()
+ "\\vectortile\\apache-tomcat-8.5.34\\webapps\\vectortile\\WEB-INF\\classes\\vts.properties",
ipApp, appChangeTxt);
replaceIP(text1.getText()
+ "\\vectortile\\apache-tomcat-8.5.34\\webapps\\vectortile\\WEB-INF\\classes\\vts.properties",
ipMapServer, mapServerIpChangeTxt);
// 修改库管服务IP
replaceIP(text1.getText() + "\\datahub\\resources\\application.properties", ipApp, appChangeTxt);
replaceIP(text1.getText() + "\\datahub\\resources\\application.properties", ipMapServer,
mapServerIpChangeTxt);
// 修改服务器监控相关IP
// 1、elasticsearch
replaceIP(text1.getText() + "\\elasticsearch-7.13.0-windows-x86_64\\config\\elasticsearch.yml", ipApp,
appChangeTxt);
// 2、kibana
replaceIP(text1.getText() + "\\kibana-7.13.0-windows-x86_64\\config\\kibana.yml", ipApp, appChangeTxt);
// 3、metricbeat-7.13.0-windows-x86_64
replaceIP(text1.getText() + "\\metricbeat-7.13.0-windows-x86_64\\metricbeat.yml", ipApp, appChangeTxt);
// 修改地名地址IP
// 1、solr
replaceIP(text1.getText() + "\\solr-8.1.1\\server\\solr\\lps\\conf\\data-config.xml", ipApp,
appChangeTxt);
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Boolean createIPChangeTxt1 = createIPChangeTxt(ipApp, text1.getText() + "\\config\\changeAppIp.txt");
Boolean createIPChangeTxt2 = createIPChangeTxt(ipMapServer,
text1.getText() + "\\config\\changeMapServerIp.txt");
if (createIPChangeTxt1 && createIPChangeTxt2) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
startBatShell("cmd /c start " + text1.getText() + "\\run");
// boolean changeDBData = changeDBData(ipGis, textDbPwd.getText());
// Boolean createGisIPChangeTxt = createIPChangeTxt(ipGis,text1.getText() +
// "\\config\\changeGisIp.txt");
JOptionPane.showMessageDialog(null, "正在重启中,请确定。。。", "提示", 2);
} else {
JOptionPane.showMessageDialog(null, "修改服务IP失败", "提示", 2);
}
}
}
}
private void replaceBizProperties(java.lang.String filePath, java.lang.String ipApp, java.lang.String ipMapServer) {
File file = new File(filePath);
Properties properties = new Properties();
try {
properties.load(new FileInputStream(file));
properties.setProperty("proxy.url", "http://" + ipApp + ":8021");
properties.setProperty("spring.datasource.url", "jdbc:postgresql://" + ipApp + ":5432/pie_natural");
properties.setProperty("server.ip", ipApp);
properties.setProperty("piesat.gisserver", "http://" + ipMapServer + ":8065/");
FileOutputStream oFile = new FileOutputStream(filePath, false);// true表示追加打开
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(oFile, "utf-8"));
bw.newLine();
for (Enumeration<?> e = properties.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
String val = properties.getProperty(key);
bw.write(key + "=" + val);
bw.newLine();
}
bw.flush();
oFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean replaceJs(java.lang.String landPath, java.lang.String ipApp) {
java.lang.String str = readJs(landPath);
java.lang.String readIpChangeTxt = readIpChangeTxt(text1.getText() + "\\config\\changeAppIp.txt");
if ("".equals(readIpChangeTxt) || null == readIpChangeTxt) {
str = str.replace("114.116.200.186", ipApp);
} else {
str = str.replace(readIpChangeTxt, ipApp);
}
PrintWriter out;
try {
out = new PrintWriter(landPath);
out.write(str.toCharArray());
out.flush();
out.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
private static String readJs(String path) {
File file = new File(path);
List<String> list = new ArrayList<String>();
try {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf8");
BufferedReader bw = new BufferedReader(isr);
String line = null;
while ((line = bw.readLine()) != null) {
list.add(line);
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
StringBuffer text = new StringBuffer();
for (int i = 0; i < list.size(); i++) {
String[] st = list.get(i).split("\t");
for (int j = 0; j < st.length; j++) {
text.append(st[j]);
}
}
return text.toString();
}
private void deleteMongoDB(String dbName) {
mongoClient.dropDatabase(dbName);
}
private Boolean createIPChangeTxt(String ip, String path) {
File newFile = new File(path);
try {
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(ip.getBytes());
outputStream.flush();
outputStream.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private boolean changeDBData(String ipGis, String dbPwd) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = CreatControllerNew.getConn("postgres", "qQq314159@26", "vectortile");
java.lang.String readMapGisIpChangeTxt = readIpChangeTxt(text1.getText() + "\\config\\changeGisIp.txt");
if ("".equals(readMapGisIpChangeTxt) || null == readMapGisIpChangeTxt) {
String tb_datasource_sql = "UPDATE tb_datasource SET f_connectionparams=replace(f_connectionparams,'114.116.200.186',?) where f_type = 2;UPDATE tb_custom_data SET f_description=f_access::text WHERE f_description IS NOT NULL;UPDATE tb_custom_data SET f_description=replace(f_description,'114.116.200.186',?) WHERE f_description IS NOT NULL;UPDATE tb_custom_data SET f_access=f_description::jsonb WHERE f_description IS NOT NULL;";
stmt = conn.prepareStatement(tb_datasource_sql);
stmt.setString(1, ipGis);
stmt.setString(2, ipGis);
} else {
String tb_datasource_sql = "UPDATE tb_datasource SET f_connectionparams=replace(f_connectionparams,?,?) where f_type = 2;UPDATE tb_custom_data SET f_description=f_access::text WHERE f_description IS NOT NULL;UPDATE tb_custom_data SET f_description=replace(f_description,?,?) WHERE f_description IS NOT NULL;UPDATE tb_custom_data SET f_access=f_description::jsonb WHERE f_description IS NOT NULL;";
stmt = conn.prepareStatement(tb_datasource_sql);
stmt.setString(1, readMapGisIpChangeTxt);
stmt.setString(2, ipGis);
stmt.setString(3, readMapGisIpChangeTxt);
stmt.setString(4, ipGis);
}
stmt.executeUpdate();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
CreatControllerNew.release(conn, stmt, null);
}
}
private String readIpChangeTxt(String path) {
File file = new File(path);
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr);
}
reader.close();
return sbf.toString();
} catch (Exception e) {
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
private Boolean replaceIP(java.lang.String filePath, java.lang.String ip, String readIpChangeTxt) {
try {
String s;
StringBuilder sb = new StringBuilder();
InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "utf-8");// 弃用FileReader而采用InputStreamReader是为了设置编码防止读写文件时产生乱码的问题
BufferedReader br = new BufferedReader(isr);
while ((s = br.readLine()) != null) {
sb.append(s);
sb.append("\r");
}
br.close();
String str = sb.toString();
str = str.replace(readIpChangeTxt, ip);
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath, false), "UTF-8");// false表示不追加文件//
// true表示追加文件
BufferedWriter bw = new BufferedWriter(osw);
bw.write(str);
bw.flush();
bw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
String startBatShell(String cmd) {
try {
Process psServe = Runtime.getRuntime().exec(cmd);
psServe.waitFor();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(psServe.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
九、案例三
- 效果图
- 完整代码:
package ChangeIpTool;
import java.awt.Color;
import java.awt.Container;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
public class MongoDBTools extends Frame implements ActionListener {
/**
* @author Eric
* @Time 2021年6月30日
*
*/
private static final long serialVersionUID = 1L;
private static final String String = null;
private MongoClient mongoClient = null;
public static void main(String[] args) {
new MongoDBTools();
}
JFrame frame = new JFrame();// 框架布局
JFrame frameAuto = new JFrame();
JTabbedPane tabPane = new JTabbedPane();// 选项卡布局
Container conKuguan = new Container();//
JLabel label1 = new JLabel("系统目录:");
JLabel mongoDB = new JLabel("Mongo版本:");
JLabel appIp = new JLabel("应用系统IP:");
JLabel mongoAction = new JLabel("操作:");
JTextField text1 = new JTextField(System.getProperty("user.dir"));// 文件的路径
JButton buttonChoose1 = new JButton("选择");// 选择
JTextField textMongoVersion = new JTextField();// 当前版本
JTextField textAppIp = new JTextField();// 当前版本
JButton mongoUninstall = new JButton("卸载");// 选择
JButton mongoInstall = new JButton("安装");// 选择
JButton mongoCreate = new JButton("建表");// 选择
JButton start = new JButton("启动");// 选择
JFileChooser jfc = new JFileChooser();// 文件选择器
public MongoDBTools() {
// 确认是否要送件
int opt = JOptionPane.showConfirmDialog(conKuguan, "是否打开MongoDB环境面板?", "确认信息", JOptionPane.YES_NO_OPTION);
if (opt == JOptionPane.YES_OPTION) {
String mongoVer = getMongoInfo();
textMongoVersion.setText(mongoVer);
jfc.setCurrentDirectory(new File(System.getProperty("user.dir")));// 文件选择器的初始目录定为c盘
double lx = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
double ly = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
frame.setLocation(new Point((int) (lx / 2) - 200, (int) (ly / 2) - 200));// 设定窗口出现位置
frame.setResizable(false);
frame.setSize(500, 500);// 设定窗口大小
frame.setTitle("配置管理工具");
frame.setContentPane(tabPane);// 设置布局
label1.setBounds(20, 30, 90, 30);
text1.setBounds(100, 30, 280, 30);
conKuguan.add(label1);
mongoDB.setBounds(20, 130, 90, 30);
conKuguan.add(mongoDB);
appIp.setBounds(20, 230, 90, 30);
conKuguan.add(appIp);
textAppIp.setBounds(100, 230, 360, 30);
conKuguan.add(textAppIp);
mongoAction.setBounds(20, 330, 90, 30);
conKuguan.add(mongoAction);
text1.setEditable(false);
conKuguan.add(text1);
buttonChoose1.setBounds(380, 30, 85, 30);
buttonChoose1.addActionListener(this); // 添加事件处理
conKuguan.add(buttonChoose1);
textMongoVersion.setBounds(100, 130, 360, 30);
textMongoVersion.setEditable(false);
conKuguan.add(textMongoVersion);
mongoUninstall.setBounds(100, 330, 80, 30);
mongoUninstall.addActionListener(this); // 添加事件处理
conKuguan.add(mongoUninstall);
mongoInstall.setBounds(192, 330, 80, 30);
mongoInstall.addActionListener(this); // 添加事件处理
conKuguan.add(mongoInstall);
mongoCreate.setBounds(284, 330, 80, 30);
mongoCreate.addActionListener(this); // 添加事件处理
conKuguan.add(mongoCreate);
start.setBounds(376, 330, 80, 30);
start.addActionListener(this); // 添加事件处理
conKuguan.add(start);
frame.setVisible(true);// 窗口可见
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 使能关闭窗口,结束程序
conKuguan.setBackground(new Color(255, 0, 0));
tabPane.add("MongoDB安装", conKuguan);// 添加布局1
} else {
System.exit(0);
}
}
private java.lang.String getMongoInfo() {
java.lang.String mongoPort = startBatShell("cmd /c netstat -aon|findstr 27017");
if (mongoPort.equals("")) {
return "未安装";
} else {
// 连接到 mongodb 服务
mongoClient = new MongoClient("localhost", 27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase("admin");
MongoCollection<Document> collection = mongoDatabase.getCollection("system.version");
FindIterable<Document> findIterable = collection.find();
MongoCursor<Document> mongoCursor = findIterable.iterator();
while (mongoCursor.hasNext()) {
Document id = mongoCursor.next();
Object object = id.get("version");
return object.toString();
}
}
return "未安装";
}
/**
* 时间监听的方法
*/
public void actionPerformed(ActionEvent e) {
// 绑定到选择文件,先择文件事件
if (e.getSource().equals(buttonChoose1)) {
jfc.setFileSelectionMode(1);// 设定只能选择到文件
int state = jfc.showOpenDialog(null);// 此句是打开文件选择器界面的触发语句
if (state == 1) {
return;// 撤销则返回
} else {
File f = jfc.getSelectedFile();// f为选择到的文件
text1.setText(f.getAbsolutePath());
}
}
if (e.getSource().equals(mongoInstall) || e.getSource().equals(mongoUninstall)) {
startBatShell("cmd /c start " + text1.getText() + "\\mongodb-win32-x86_64-2008plus-ssl-4.0.25-signed.msi");
}
if (e.getSource().equals(start)) {
if (textAppIp.getText() == null || textAppIp.getText().equals("")) {
startBatShell("cmd /c start " + text1.getText() + "\\run.bat");
return;
}
java.lang.String readIpChangeTxt = readIpChangeTxt(text1.getText() + "\\config\\changeAppIp.txt");
// 修改mapserver
replaceIP(text1.getText() + "\\mapserver\\config.json", textAppIp.getText(), readIpChangeTxt);
// // 修改vectortile
// replaceIP(text1.getText()
// + "\\vectortile\\apache-tomcat-8.5.34\\webapps\\cuttile-server\\WEB-INF\\classes\\conf\\database.properties",
// textAppIp.getText(), readIpChangeTxt);
// replaceIP(text1.getText()
// + "\\vectortile\\apache-tomcat-8.5.34\\webapps\\data-server\\WEB-INF\\classes\\dataserverdb.properties",
// textAppIp.getText(), readIpChangeTxt);
// replaceIP(text1.getText()
// + "\\vectortile\\apache-tomcat-8.5.34\\webapps\\data-server\\WEB-INF\\classes\\zkSetting.properties",
// textAppIp.getText(), readIpChangeTxt);
// replaceIP(text1.getText()
// + "\\vectortile\\apache-tomcat-8.5.34\\webapps\\vectortile\\WEB-INF\\classes\\vts.properties",
// textAppIp.getText(), readIpChangeTxt);
Boolean createIPChangeTxt = createIPChangeTxt(textAppIp.getText(),
text1.getText() + "\\config\\changeAppIp.txt");
if (createIPChangeTxt) {
startBatShell("cmd /c start " + text1.getText() + "\\run.bat");
}
}
if (e.getSource().equals(mongoCreate)) {
File mongorestore = new File(text1.getText() + "\\mongodb\\mongorestore.exe");
if (!mongorestore.exists()) {
JOptionPane.showMessageDialog(null, "未找到mongorestore还原工具");
} else {
JOptionPane op = new JOptionPane("请耐心等待", JOptionPane.INFORMATION_MESSAGE);
final JDialog dialog = op.createDialog("MongoDB数据还原中");
try {
File[] list = new File(text1.getText() + "\\mongodb").listFiles();
if (list != null && list.length > 1) {
new Thread(() -> {
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setAlwaysOnTop(true);
dialog.setModal(false);
dialog.setVisible(true);
}).start();
// 删除原有的
for (File file : list) {
String datname = org.apache.commons.io.FilenameUtils.getBaseName(file.getName());
if (datname.equals("mongorestore")) {
continue;
}
deleteMongoDB(datname);
}
for (File file : list) {
String datname = org.apache.commons.io.FilenameUtils.getBaseName(file.getName());
dialog.setTitle(datname + "还原中,请稍后");
if (datname.equals("mongorestore")) {
continue;
}
if (datname.equals("GTDB")) {
continue;
}
startRestore(
"cmd /c " + text1.getText() + "\\mongodb\\mongorestore.exe -h 127.0.0.1:27017 -d "
+ datname + " --dir " + text1.getText() + "\\mongodb\\" + datname);
dialog.setTitle(datname + "还原成功!");
Thread.sleep(2000);
}
File fileGTDB = new File(text1.getText() + "\\mongodb\\GTDB");
if (fileGTDB.exists()) {
dialog.setTitle("GTDB还原中,请稍后");
startRestore("cmd /c " + text1.getText()
+ "\\mongodb\\mongorestore.exe -h 127.0.0.1:27017 -d GTDB --dir " + text1.getText()
+ "\\mongodb\\GTDB");
Thread.sleep(180000);
dialog.setTitle("GTDB还原成功!");
}
dialog.setVisible(false);
dialog.dispose();
JOptionPane.showMessageDialog(null, "mongodb数据还原成功");
} else {
JOptionPane.showMessageDialog(null, "未找到Mongo数据文件");
}
} catch (Exception e2) {
e2.printStackTrace();
dialog.setVisible(false);
dialog.dispose();
JOptionPane.showMessageDialog(null, "Mongo库表还原失败", "提示", 2);
}
}
}
}
private void deleteMongoDB(String dbName) {
mongoClient.dropDatabase(dbName);
}
String startBatShell(String cmd) {
try {
Process psServe = Runtime.getRuntime().exec(cmd);
psServe.waitFor();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(psServe.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
void startRestore(String cmd) {
new Thread(() -> {
try {
Process psServe = Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Boolean replaceIP(java.lang.String filePath, java.lang.String ip, java.lang.String readIpChangeTxt) {
try {
String s;
StringBuilder sb = new StringBuilder();
InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "utf-8");// 弃用FileReader而采用InputStreamReader是为了设置编码防止读写文件时产生乱码的问题
BufferedReader br = new BufferedReader(isr);
while ((s = br.readLine()) != null) {
sb.append(s);
sb.append("\r");
}
br.close();
String str = sb.toString();
str = str.replace(readIpChangeTxt, ip);
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath, false), "utf-8");// false表示不追加文件//
// true表示追加文件
BufferedWriter bw = new BufferedWriter(osw);
bw.write(str);
bw.flush();
bw.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
private String readIpChangeTxt(String path) {
File file = new File(path);
BufferedReader reader = null;
StringBuffer sbf = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempStr;
while ((tempStr = reader.readLine()) != null) {
sbf.append(tempStr);
}
reader.close();
return sbf.toString();
} catch (Exception e) {
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
private Boolean createIPChangeTxt(String ip, String path) {
File newFile = new File(path);
try {
FileOutputStream outputStream = new FileOutputStream(newFile);
outputStream.write(ip.getBytes());
outputStream.flush();
outputStream.close();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
}