72 lines
2.1 KiB
Java
72 lines
2.1 KiB
Java
package fr.univ.lyon1.common;
|
|
|
|
import org.jetbrains.annotations.NotNull;
|
|
|
|
import java.io.File;
|
|
import java.io.FileReader;
|
|
import java.io.FileWriter;
|
|
import java.io.IOException;
|
|
import java.util.Properties;
|
|
|
|
/**
|
|
* The client server configuration
|
|
* ToDo should be in gui and not in common ?
|
|
*/
|
|
public record ServerConfiguration(@NotNull String address, int port) {
|
|
@NotNull
|
|
private static final File file = new File("connection.properties");
|
|
|
|
/**
|
|
* Create a configuration
|
|
* @param address the server address
|
|
* @param port the server port
|
|
*/
|
|
public ServerConfiguration(@NotNull String address, int port) {
|
|
this.address = address;
|
|
this.port = port;
|
|
}
|
|
|
|
/**
|
|
* Load configuration from file
|
|
* @return the configuration
|
|
* @throws IOException if the file doesn't exist
|
|
*/
|
|
public static ServerConfiguration load() throws IOException {
|
|
// Check if file non exists, return error to launch server configuration
|
|
if (!file.exists()) {
|
|
System.out.println("File not exists");
|
|
throw new IOException("File not exists");
|
|
}
|
|
|
|
@NotNull final Properties properties = new Properties();
|
|
properties.load(new FileReader(file));
|
|
return new ServerConfiguration(properties.getProperty("address"), Integer.parseInt(properties.getProperty("port")));
|
|
}
|
|
|
|
/**
|
|
* Save configuration to file
|
|
* @throws IOException if fail to write the file
|
|
*/
|
|
public void save() throws IOException {
|
|
@NotNull final Properties properties = new Properties();
|
|
properties.setProperty("address", this.address);
|
|
properties.setProperty("port", String.valueOf(this.port));
|
|
properties.store(new FileWriter(file), "Information needed to connect to the server");
|
|
}
|
|
|
|
/**
|
|
* Get the server address
|
|
* @return the server address
|
|
*/
|
|
public @NotNull String getAddress() {
|
|
return address;
|
|
}
|
|
|
|
/**
|
|
* Get the server port
|
|
* @return the server port
|
|
*/
|
|
public int getPort() {
|
|
return port;
|
|
}
|
|
}
|