Browse Source

Added Gson as dependency, added JSON file creation for user signup

remotes/origin/feature/client/make-input-field-buttons-interactive
Richard Schmidt 11 months ago
parent
commit
f933542615
  1. 10
      pom.xml
  2. 40
      src/main/java/SignUp.java

10
pom.xml

@ -3,4 +3,14 @@
<groupId>org.progmethoden</groupId>
<artifactId>java-chat</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
</project>

40
src/main/java/SignUp.java

@ -1,3 +1,7 @@
import com.google.gson.Gson;
import java.io.FileWriter;
import java.io.IOException;
public class SignUp {
private String name;
private String password;
@ -25,25 +29,43 @@ public class SignUp {
this.password = password;
}
// Function to create user
// Function to create user with validation
public static SignUp createUser(String name, String password) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException("Username cannot be empty");
throw new IllegalArgumentException("Username cannot be empty");
}
if (password == null || password.isEmpty()) {
throw new IllegalArgumentException("Password cannot be empty");
throw new IllegalArgumentException("Password cannot be empty");
}
if (password.length() < 6) {
throw new IllegalArgumentException("Password must be at least 6 characters long");
throw new IllegalArgumentException("Password must be at least 6 characters long");
} return new SignUp(name, password);
}
// Function to save to JSON file, replace with database call later
public void saveToJsonFile(String filename) {
try (FileWriter fileWriter = new FileWriter(filename)) {
Gson gson = new Gson();
gson.toJson(this, fileWriter);
System.out.println("User information saved to " + filename);
} catch (IOException e) {
System.out.println("Error occurred while saving user information to JSON file: " + e.getMessage());
}
}
public static void main(String[] args) {
// Example
SignUp user = createUser("TestUser", "TestPasswort");
try {
// Example usage
SignUp user = createUser("Test User", "TestPasswort");
// Example of accessing properties
System.out.println("User Name: " + user.getName());
System.out.println("User Password: " + user.getPassword());
// Example of accessing properties
System.out.println("User Name: " + user.getName());
System.out.println("User Password: " + user.getPassword());
// Save user information to a JSON file
user.saveToJsonFile("user.json");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Loading…
Cancel
Save