Skip to content

Commit

Permalink
Merge pull request #77 from ToxicStoxm/dev
Browse files Browse the repository at this point in the history
Hot Fixes + New Settings + Code Refactoring
  • Loading branch information
ToxicStoxm authored Aug 4, 2024
2 parents dbe7509 + b0d29f4 commit a00173a
Show file tree
Hide file tree
Showing 37 changed files with 2,064 additions and 377 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,4 @@ bin/
/ToDo.txt
/.run/
/update-todo.txt
/JavaDoc/
4 changes: 4 additions & 0 deletions src/main/java/com/toxicstoxm/LEDSuite/Constants.java
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,17 @@ public static final class Config {
public static final String PERIODIC_SECTION = TASKS_SECTION + SEPARATOR + "Periodic";
public static final String STATUS_REQUEST_CLOCK = PERIODIC_SECTION + SEPARATOR + "Status-Request-Clock";
public static final String USER_PREFERENCES_SECTION = LOCAL_SETTINGS_SECTION + SEPARATOR + "User-Preferences";
public static final String COLOR_CODING_SECTION = LOGGING_SECTION + SEPARATOR + "Color-Coding";
public static final String COLORS_SECTION = COLOR_CODING_SECTION + SEPARATOR + "Colors";

// settings
public static final String WINDOW_RESIZABLE = WINDOW_SECTION + SEPARATOR + "Window-Resizable";
public static final String WINDOW_DEFAULT_WIDTH = WINDOW_SECTION + SEPARATOR + "Window-Default-Width";
public static final String WINDOW_DEFAULT_HEIGHT = WINDOW_SECTION + SEPARATOR + "Window-Default-Height";

public static final String LOG_LEVEL = LOGGING_SECTION + SEPARATOR + "Log-Level";
public static final String STACK_TRACE_DEPTH = LOGGING_SECTION + SEPARATOR + "Stack-Trace-Depth";
public static final String COLOR_CODING_ENABLED = COLOR_CODING_SECTION + SEPARATOR + "Enabled";
public static final String LOG_FILE_ENABLED = LOGGING_FILE_SECTION + SEPARATOR + "Enabled";
public static final String LOG_FILE_LOG_LEVEL_ALL = LOGGING_FILE_SECTION + SEPARATOR + "Log-Level-All";
public static final String LOG_FILE_MAX_FILES = LOGGING_FILE_SECTION + SEPARATOR + "Max-Files";
Expand Down
236 changes: 157 additions & 79 deletions src/main/java/com/toxicstoxm/LEDSuite/LEDSuite.java

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@
import org.apache.commons.configuration2.io.FileHandler;

import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.*;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
Expand Down Expand Up @@ -118,6 +115,24 @@ private static boolean ping(String ip) {
return false;
}

public interface ValidIPCallback {
void onResult(String result);
}

public static void getValidIP(String ip, boolean ipify, ValidIPCallback callback) {
if (callback == null) return;
new LEDSuiteRunnable() {
@Override
public void run() {
try {
callback.onResult(getValidIP(ip, ipify));
} catch (UnknownHostException e) {
callback.onResult(null);
}
}
}.runTaskAsynchronously();
}

/**
* Validates the provided host address using {@link Validation#isValidIP(String)} and {@link Validation#ping(String)}, and tries to get a
* corresponding hostname to it.
Expand Down Expand Up @@ -235,7 +250,7 @@ public static void sendFileDefaultHost(String fileToSendPath, ProgressTracker pr
* @since 1.0.0
*/
public static void sendFile(String serverIP4, int serverPort, String fileToSendPath, ProgressTracker progressTracker) {
// loading file to memory
// loading the specified file to memory
File fileToSend = new File(fileToSendPath);
try {
// send a file upload request to the server
Expand All @@ -257,7 +272,7 @@ public static void sendFile(String serverIP4, int serverPort, String fileToSendP
);
} catch (YAMLSerializer.TODOException | ConfigurationException | YAMLSerializer.InvalidReplyTypeException |
YAMLSerializer.InvalidPacketTypeException e) {
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
}
}

Expand Down Expand Up @@ -437,7 +452,7 @@ public static boolean sendFile(String serverIPv4, int serverPort, ProgressTracke
} catch (IOException e) {
if (track) progressTracker.setError(true); // inform the progress tracker of the occurred error
LEDSuite.logger.error(id + "Error occurred! Transmission terminated!");
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
return false;
} catch (NetworkException e) {
if (track) progressTracker.setError(true); // inform the progress tracker of the occurred error
Expand Down Expand Up @@ -494,13 +509,14 @@ public static class NetworkHandler {
* @since 1.0.0
*/
protected static Socket server = null;
protected static boolean serverIsRebooting = false;

/**
* Checks if the server is open and connected.
* @return {@code true} If the socket is open and connected to a server
* @since 1.0.0
*/
private static boolean isConnected() {
public static boolean isConnected() {
return server != null && !server.isClosed() && server.isConnected();
}

Expand All @@ -526,6 +542,8 @@ private static boolean isConnected() {
*/
private static LEDSuiteTask masterListener = null;

private static NetworkHandle handle = null;

/**
* Used to monitor communication state between client and server.
* @see SuccessCallback#getResult(boolean)
Expand Down Expand Up @@ -572,28 +590,36 @@ protected static Socket getServer() throws NetworkException {
* @since 1.0.0
*/
public static void init(SuccessCallback callback) throws NetworkException {
if (serverIsRebooting) {
if (callback != null) callback.getResult(false);
return;
}
serverIsRebooting = true;
try {
// if a socket is not initialized at all, create a new socket
// connects it to the new server
if (server == null || server.isClosed()) {
server = new Socket(LEDSuite.server_settings.getIPv4(), LEDSuite.server_settings.getPort());
} else {
server.connect(new InetSocketAddress(LEDSuite.server_settings.getIPv4(), LEDSuite.server_settings.getPort()));
server = new Socket();
server.setReuseAddress(true);
server.connect(new InetSocketAddress(LEDSuite.server_settings.getIPv4(), LEDSuite.server_settings.getPort()), 3000);
}
LEDSuite.logger.verbose("Successfully connected to server!");
} catch (Exception e) {
} catch (IOException e) {
// if connection fails, inform the caller function using the callback
LEDSuite.logger.fatal("Failed to initialize connection to server! Error: " + e.getMessage());
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
serverIsRebooting = false;
if (callback != null) callback.getResult(false);
return;
}

LEDSuite.logger.verbose("Fulfilling initialization request for Network Handler!");

LEDSuite.logger.verbose("Network Handler: starting network handle...");
LEDSuite.eventManager.registerEvents(new NetworkHandle());
LEDSuite.logger.verbose("Network Handler: started network handle!");
if (handle == null) {
LEDSuite.logger.verbose("Network Handler: starting network handle...");
LEDSuite.eventManager.registerEvents(handle = new NetworkHandle());
LEDSuite.logger.verbose("Network Handler: started network handle!");
}


// if manager is already running, cancel it
Expand All @@ -612,8 +638,9 @@ public static void init(SuccessCallback callback) throws NetworkException {
@Override
public void run() {
if (!TimeManager.call("mgr")) return;
// check if keepalive needs to be sent
// check if keepalive needs to be sent
if (TimeManager.call("keepalive")) {
LEDSuite.logger.verbose("Sending keepalive");
try {
// try sending a keepalive message to server
if (!sendKeepalive(
Expand All @@ -624,20 +651,21 @@ public void run() {
.build(),
false
)
) throw new NetworkException("Failed to send Keepalive!");
) throw new NetworkException("Sending keepalive failed!");
} catch (YAMLSerializer.TODOException | ConfigurationException |
YAMLSerializer.InvalidReplyTypeException |
YAMLSerializer.InvalidPacketTypeException |
NetworkException e) {
LEDSuite.logger.fatal("Failed to send keepalive!");
LEDSuite.logger.error(e);
LEDSuite.logger.verbose(e instanceof NetworkException ? e.getMessage() : "Sending keepalive failed! (Not network related)");
}
}

// check if the status needs to be sent / updated
if (TimeManager.call("status")) {
// if the main window is open request status from server
if (LEDSuite.mainWindow != null) LEDSuite.mainWindow.getStatus(null);
}

// if the send-queue isn't empty and the server is connected
if (!networkQueue.isEmpty() && isConnected()) {
Map.Entry<Long, LEDSuiteRunnable> entry = networkQueue.firstEntry();
Expand All @@ -653,6 +681,9 @@ public void run() {
initListener();

LEDSuite.logger.verbose("Network Handler started!");

serverIsRebooting = false;

// informs the function caller of the result
callback.getResult(true);
}
Expand Down Expand Up @@ -694,7 +725,7 @@ public void run() {
UUID networkID0 = UUID.fromString(yamlCfg.getString(Constants.Network.YAML.INTERNAL_NETWORK_ID));
yaml = YAMLSerializer.deserializeYAML(yamlCfg, networkID0);
} catch (IllegalArgumentException e) {
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
LEDSuite.logger.warn(System.currentTimeMillis() + " Received reply with missing or invalid network id! Can't associate it with corresponding listener!");
yaml = YAMLSerializer.deserializeYAML(yamlCfg);

Expand All @@ -720,7 +751,7 @@ public void run() {
}
} catch (Exception e) {
LEDSuite.logger.fatal("Network Handler: master listener: Error: " + e.getMessage());
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
}

}
Expand Down Expand Up @@ -764,6 +795,7 @@ private static void clearQueues() {
* @since 1.0.0
*/
public static void reboot() throws NetworkException {
if (serverIsRebooting) return;
LEDSuite.logger.verbose("Network Handler: Fulfilling reboot request!");
// try to close the current connection
try {
Expand All @@ -777,10 +809,6 @@ public static void reboot() throws NetworkException {
LEDSuite.logger.verbose("Network Handler: Stopping mgr and listener tasks");
cancel();

// clearing network queue and listener collection
LEDSuite.logger.verbose("Network Handler: Clearing queues");
clearQueues();

// try to initialize a new connection and restart the handler with init(SuccessCallback)
// if it fails to throw a new NetworkException to allow for custom error handling
try {
Expand All @@ -791,7 +819,7 @@ public static void reboot() throws NetworkException {
});
} catch (NetworkException e) {
LEDSuite.logger.fatal("Network Handler: reboot failed!");
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
throw new NetworkException("connection failed!");
}
}
Expand All @@ -805,15 +833,6 @@ public static void hostChanged() throws NetworkException {
reboot();
}

/**
* Checks if socket is currently open and connected.
* @return {@code true} If socket is open and connected.
* @since 1.0.0
*/
public static boolean connectedAndRunning() {
return server != null && server.isConnected() && !server.isClosed();
}

/**
* Listener Class. Handles various events like {@link Events.Shutdown}, {@link Events.HostChanged} and {@link Events.SettingsChanged}.
* @since 1.0.0
Expand Down Expand Up @@ -841,7 +860,7 @@ public void onHostChanged(Events.HostChanged e) {
try {
hostChanged();
} catch (NetworkException ex) {
LEDSuite.logger.error(ex);
LEDSuite.logger.displayError(ex);
}
}

Expand Down Expand Up @@ -968,7 +987,7 @@ public static YAMLConfiguration defaultReceive(InputStream is) {
yaml = new YAMLConfiguration();
new FileHandler(yaml).load(new ByteArrayInputStream(CharBuffer.wrap(buffer).toString().getBytes()));
} catch (Exception e) {
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
return null;
}
return yaml;
Expand Down Expand Up @@ -1121,14 +1140,12 @@ public static boolean sendYAML(String host, int port, YAMLConfiguration yaml, Fi
// if that fails, to simply return false completion and cancel an attempt
if (!NetworkHandler.isConnected()) {
try {
NetworkHandler.init(success -> {
if (!success) {
if (callback != null) callback.onFinish(false);
throw new NetworkException("Reconnection attempt to previous server failed!");
} else LEDSuite.logger.verbose("Successfully reconnected to previous server!");
});
NetworkHandler.reboot();
if (callback != null) callback.onFinish(true);
LEDSuite.logger.verbose("Successfully reconnected to previous server!");
} catch (NetworkException e) {
LEDSuite.logger.fatal(e.getMessage());
LEDSuite.logger.error("Reconnection attempt to previous server failed!");
if (callback != null) callback.onFinish(false);
return false;
}
Expand Down Expand Up @@ -1295,12 +1312,12 @@ private static boolean sendYAMLMessage(String serverIP4, int serverPort, YAMLCon
try {
NetworkHandler.reboot();
sendYAMLMessage(serverIP4, serverPort, yaml, callback, replyHandle);
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
} catch (NetworkException ex) {
// if an error occurs, print an error message and give up
if (displayLog) {
LEDSuite.logger.error(id + "Error occurred! Transmission terminated!");
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
}
err = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ public void fireEvent(Object event) {
LEDSuite.logger.warn(id + "Error while trying to fire event: " + event);
LEDSuite.logger.warn(id + "This warning can be ignored!");
LEDSuite.logger.debug(id + "Stack trace: ");
LEDSuite.logger.error(e);
LEDSuite.logger.displayError(e);
// Add the listener to the removal list
toRemove.add(registeredListener);
}
Expand Down Expand Up @@ -137,7 +137,8 @@ private String tryToGetNetworkID(Object event) {
}
} catch (Exception e) {
// Log any exception that occurs during network ID extraction
LEDSuite.logger.error("Error extracting network ID: ", e);
LEDSuite.logger.error("Error extracting network ID: ");
LEDSuite.logger.displayError(e);
}
// Return the network ID if found, else return an empty string
return id.isBlank() ? "" : "[" + id + "] ";
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/com/toxicstoxm/LEDSuite/logging/LogLevel.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.toxicstoxm.LEDSuite.logging;

import org.fusesource.jansi.Ansi;

import java.awt.*;

/**
* Interface representing a logging level.
*
Expand All @@ -20,4 +24,5 @@ public interface LogLevel {
* @since 1.0.0
*/
boolean isEnabled();
Ansi convert(String message);
}
Loading

0 comments on commit a00173a

Please sign in to comment.