Skip to content

Commit

Permalink
全面引入日志系统
Browse files Browse the repository at this point in the history
重构架构
添加自动重连
  • Loading branch information
RedDragon0293 committed Jun 5, 2024
1 parent 3bba5f5 commit c547cc5
Show file tree
Hide file tree
Showing 10 changed files with 97 additions and 51 deletions.
6 changes: 6 additions & 0 deletions .idea/encodings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 7 additions & 30 deletions src/main/java/cn/reddragon/eportal/EPortal.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import cn.reddragon.eportal.account.AccountManager;
import cn.reddragon.eportal.config.ConfigManager;
import cn.reddragon.eportal.config.configs.AutoReconnectConfig;
import cn.reddragon.eportal.controllers.MainController;
import cn.reddragon.eportal.utils.Authenticator;
import cn.reddragon.eportal.utils.LoginType;
Expand All @@ -13,53 +14,37 @@
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.util.Objects;

public class EPortal extends Application {
public static MainController controller;
public static Logger logger = LogManager.getLogger("EPortal");
public static final Thread askThread = new Thread(() -> {
while (true) {
try {
//System.out.println("Heartbeat.");
Authenticator.updateStatus();
if (!Authenticator.online && AutoReconnectConfig.getAutoReconnect() && !Authenticator.error)
controller.onLoginButtonClick();
Platform.runLater(controller::updateUI);
if (Authenticator.error)
Thread.sleep(1000L);
else
Thread.sleep(5000L);
} catch (Exception e) {
//throw new RuntimeException(e);
e.printStackTrace();
logger.error("监听线程出错!", e);
}
}
});

public static void main(String[] args) {
askThread.setDaemon(true);
Authenticator.checkOnline();
try {
if (Authenticator.online) {
System.out.println("Already connected!");
Authenticator.updateUserIndex();
//System.exit(0);
} else {
System.out.println("Ready");
}
//System.out.println(result);
} catch (NullPointerException e) {
e.printStackTrace();
System.exit(0);
}
launch();
ConfigManager.saveConfigs();
}

@SuppressWarnings("unchecked")
@Override
public void start(Stage stage) throws IOException {
Thread.currentThread().setName("EPortal Main");
FXMLLoader fxmlLoader = new FXMLLoader(EPortal.class.getResource("hello-view.fxml"));
Parent root = fxmlLoader.load();
controller = fxmlLoader.getController();
Expand All @@ -79,19 +64,11 @@ public void start(Stage stage) throws IOException {
ConfigManager.loadConfigs();
TextField name = (TextField) root.lookup("#userNameField");
TextField pass = (TextField) root.lookup("#passwordField");
//name.setText(config[0]);
//pass.setText(config[1]);
if (!AccountManager.accounts.isEmpty()) {
name.setText(AccountManager.accounts.get(0).getName());
pass.setText(AccountManager.accounts.get(0).getPassword());
}
//box.setValue(box.getItems().get(Byte.parseByte(config[2])));
//updateUI();
askThread.start();
Authenticator.checkOnline();
if (!Authenticator.online) {
controller.onLoginButtonClick();
}
stage.show();
}
}
17 changes: 16 additions & 1 deletion src/main/java/cn/reddragon/eportal/Main.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
package cn.reddragon.eportal;

import cn.reddragon.eportal.config.ConfigManager;
import cn.reddragon.eportal.utils.Authenticator;

public class Main {
public static void main(String[] args) {
EPortal.main(args);
Thread.currentThread().setName("EPortal Main");
EPortal.askThread.setDaemon(true);
Authenticator.checkOnline();
try {
if (Authenticator.online) {
Authenticator.updateUserIndex();
}
} catch (NullPointerException e) {
EPortal.logger.error("启动时出错!", e);
System.exit(0);
}
EPortal.launch();
ConfigManager.saveConfigs();
}
}
13 changes: 11 additions & 2 deletions src/main/java/cn/reddragon/eportal/config/ConfigManager.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cn.reddragon.eportal.config;

import cn.reddragon.eportal.config.configs.AccountConfig;
import cn.reddragon.eportal.config.configs.AutoReconnectConfig;
import cn.reddragon.eportal.config.configs.NetTypeConfig;
import com.google.gson.*;
import org.apache.logging.log4j.LogManager;
Expand All @@ -15,6 +16,7 @@ public class ConfigManager {
private static final File configFile = new File("EPortal.json");
private static final ArrayList<AbstractConfig> configs = new ArrayList<>();
private static final Logger logger = LogManager.getLogger("ConfigManager");
private static final int configVersion = 1;

static {
if (!configFile.exists()) {
Expand All @@ -28,6 +30,7 @@ public class ConfigManager {
}
configs.add(new AccountConfig());
configs.add(new NetTypeConfig());
configs.add(new AutoReconnectConfig());
}

public static void loadConfigs() {
Expand All @@ -36,14 +39,19 @@ public static void loadConfigs() {
if (!element.isJsonNull()) {
JsonObject object = element.getAsJsonObject();
for (Entry<String, JsonElement> next : object.entrySet()) {
if (next.getKey().equals("ConfigVersion")) {
// TODO
}
for (AbstractConfig config : configs) {
if (config.name.equals(next.getKey())) {
config.fromJson(next.getValue());
logger.info("成功加载配置文件 {}", config.name);
logger.info("成功加载配置文件 {}.", config.name);
break;
}
}
}
} else {
logger.warn("配置文件损坏!");
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
Expand All @@ -52,9 +60,10 @@ public static void loadConfigs() {

public static void saveConfigs() {
JsonObject root = new JsonObject();
root.addProperty("ConfigVersion", configVersion);
for (AbstractConfig config : configs) {
root.add(config.name, config.toJson());
logger.info("成功保存配置文件 {}", config.name);
logger.info("成功保存配置文件 {}.", config.name);
}
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(configFile));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package cn.reddragon.eportal.config.configs;

import cn.reddragon.eportal.EPortal;
import cn.reddragon.eportal.config.AbstractConfig;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import javafx.scene.control.CheckMenuItem;

public class AutoReconnectConfig extends AbstractConfig {
public AutoReconnectConfig() {
super("AutoReconnect");
}

public static boolean getAutoReconnect() {
return ((CheckMenuItem) EPortal.controller.menuBar.getMenus().get(0).getItems().get(0)).isSelected();
}

@Override
public JsonElement toJson() {
return new JsonPrimitive(getAutoReconnect());
}

@Override
public void fromJson(JsonElement element) {
((CheckMenuItem) EPortal.controller.menuBar.getMenus().get(0).getItems().get(0)).setSelected(element.getAsBoolean());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ public JsonElement toJson() {

@Override
public void fromJson(JsonElement element) {
selector.setValue(selector.getItems().get(element.getAsInt()));
if (element.getAsInt() != -1)
selector.setValue(selector.getItems().get(element.getAsInt()));
else
selector.setValue("");
}
}
20 changes: 12 additions & 8 deletions src/main/java/cn/reddragon/eportal/controllers/MainController.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
package cn.reddragon.eportal.controllers;

import cn.reddragon.eportal.EPortal;
import cn.reddragon.eportal.account.AccountManager;
import cn.reddragon.eportal.utils.*;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.*;

import java.io.IOException;
import java.io.InputStreamReader;
Expand All @@ -36,6 +34,8 @@ public class MainController {
private TextField userNameField;
@FXML
private TextField passwordField;
@FXML
public MenuBar menuBar;

public void updateUI() {
StringBuilder sb = new StringBuilder();
Expand Down Expand Up @@ -90,6 +90,7 @@ public void onLoginButtonClick() {
new Thread(() -> {
HttpURLConnection connection = null;
try {
EPortal.logger.info("尝试发出登出命令.");
connection = Authenticator.logout();
if (connection == null) {
Platform.runLater(() -> {
Expand All @@ -99,12 +100,13 @@ public void onLoginButtonClick() {
return;
}
JsonObject resultMessage = JsonParser.parseString(IOUtils.readText(connection.getInputStream())).getAsJsonObject();
System.out.println(resultMessage.toString());
//System.out.println(resultMessage.toString());
EPortal.logger.info("服务器返回的是: {}", resultMessage);
Platform.runLater(() -> resultText.setText(resultMessage.get("result").getAsString() + ":" + resultMessage.get("message").getAsString()));
Authenticator.updateStatus();
Platform.runLater(this::updateUI);
} catch (Exception e) {
e.printStackTrace();
EPortal.logger.error("登出线程出错!", e);
Platform.runLater(() -> resultText.setText(e.getMessage()));
} finally {
if (connection != null) {
Expand Down Expand Up @@ -134,6 +136,7 @@ public void onLoginButtonClick() {
String serviceString = Arrays.stream(LoginType.values()).filter(it -> Objects.equals(it.displayName, mode)).findFirst().map(it -> URIEncoder.encodeURI(URIEncoder.encodeURI(it.authName))).orElse("");
new Thread(() -> {
try {
EPortal.logger.info("尝试发出登录命令.");
//获取queryString
HttpURLConnection connection = HttpUtils.make("http://123.123.123.123", "GET");
connection.setInstanceFollowRedirects(false);
Expand Down Expand Up @@ -164,7 +167,8 @@ public void onLoginButtonClick() {
}
//获取结果
JsonObject resultMessage = JsonParser.parseString(IOUtils.readText(loginConnection.getInputStream())).getAsJsonObject();
System.out.println(resultMessage.toString());
//System.out.println(resultMessage.toString());
EPortal.logger.info("服务器返回的是: {}", resultMessage);
String result = resultMessage.get("result").getAsString();
Platform.runLater(() -> resultText.setText(resultMessage.get("result").getAsString() + ":" + resultMessage.get("message").getAsString()));
if (result.equals("success")) {
Expand All @@ -174,7 +178,7 @@ public void onLoginButtonClick() {
AccountManager.addAccount(username, password);
}
} catch (IOException e) {
e.printStackTrace();
EPortal.logger.error("登录线程出错!", e);
Platform.runLater(() -> resultText.setText(e.getMessage()));
}
Authenticator.updateStatus();
Expand Down
17 changes: 10 additions & 7 deletions src/main/java/cn/reddragon/eportal/utils/Authenticator.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javafx.application.Platform;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
Expand All @@ -18,6 +20,7 @@
public class Authenticator {
public static final String ePortalUrl = "http://10.96.0.155/eportal";
public static final String ePortalInterFaceUrl = ePortalUrl + "/InterFace.do?method=";
private static final Logger logger = LogManager.getLogger("Authenticator");
public static String userIndex = null;
public static boolean online = false;
public static LoginType type = null;
Expand All @@ -34,7 +37,7 @@ public static HttpURLConnection login(String username, String password, String s
connection.connect();
return connection;
} catch (IOException e) {
e.printStackTrace();
logger.error("登录时出错!", e);
return null;
}
}
Expand All @@ -51,7 +54,7 @@ public static void updateUserIndex() {
String redirectLocation = result.get("Location").get(0);
userIndex = redirectLocation.substring(redirectLocation.indexOf('=') + 1);
} catch (IOException e) {
e.printStackTrace();
logger.error("更新 UserIndex 时出错!", e);
userIndex = null;
}
}
Expand All @@ -67,7 +70,7 @@ public static HttpURLConnection getUserInfo() {
connection.connect();
return connection;
} catch (IOException e) {
e.printStackTrace();
logger.error("更新用户数据时出错!", e);
return null;
}
}
Expand Down Expand Up @@ -120,21 +123,21 @@ public static void checkOnline() {
error = false;
}
} catch (SocketTimeoutException e) {
System.err.println(e.getMessage());
logger.error("无法连接到认证服务器! {}", e.getMessage());
if (EPortal.controller != null) {
Platform.runLater(() -> EPortal.controller.resultText.setText("错误: 无法连接到认证服务器!"));
error = true;
}
online = false;
} catch (SocketException e) {
System.err.println(e.getMessage());
logger.error("客户端网络错误! {}", e.getMessage());
if (EPortal.controller != null) {
Platform.runLater(() -> EPortal.controller.resultText.setText("错误: 无网络连接!"));
error = true;
}
online = false;
} catch (IOException | NullPointerException e) {
e.printStackTrace();
logger.error("更新在线状态时出错!", e);
online = false;
}
}
Expand Down Expand Up @@ -164,7 +167,7 @@ public static void updateSession() {
}
}
} catch (Exception e) {
e.printStackTrace();
logger.error("更新 Session 时出错!", e);
}
}).start();
}
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/cn/reddragon/eportal/utils/IOUtils.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package cn.reddragon.eportal.utils;

import cn.reddragon.eportal.EPortal;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -20,7 +22,7 @@ public static String readText(InputStream stream) {
}
return sb.toString();*/
} catch (IOException e) {
e.printStackTrace();
EPortal.logger.error("读入数据时出错!", e);
return "";
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/cn/reddragon/eportal/hello-view.fxml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<VBox xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/21"
fx:controller="cn.reddragon.eportal.controllers.MainController">
<children>
<MenuBar maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308">
<MenuBar fx:id="menuBar" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308">
<menus>
<Menu mnemonicParsing="false" text="设置">
<items>
Expand Down

0 comments on commit c547cc5

Please sign in to comment.