Browse Source

Merge branch 'main' into feature/client/exchange-messages-between-client-server

remotes/origin/feature/client/exchange-messages-between-client-server
Alena Bandarovich 11 months ago
parent
commit
0677c393b8
  1. 10
      pom.xml
  2. 41
      src/main/java/ChatServer.java
  3. 124
      src/main/java/CreateUser.java
  4. 103
      src/main/java/SignUpGUI.java
  5. 14
      user.json

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>

41
src/main/java/ChatServer.java

@ -2,32 +2,59 @@
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class ChatServer {
private ServerSocket serverSocket;
private List<ClientHandler> clients; // Liste, um alle verbundenen Clients zu verwalten
public ChatServer(int port) {
clients = new CopyOnWriteArrayList<>(); // Verwende CopyOnWriteArrayList für die Thread-Sicherheit
try {
serverSocket = new ServerSocket(port);
System.out.println("Started ChatServer on port " + port);
Socket connectionToClient = serverSocket.accept();
System.out.println("Accepted new Client");
while (true) {
System.out.println("waiting for new Client...");
Socket connectionToClient = serverSocket.accept(); // Auf Verbindungen von Clients warten
ClientHandler client = new ClientHandler(this, connectionToClient);
clients.add(client); // Neuen Client zur Liste hinzufügen
System.out.println("Accepted new Client");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void broadcastMessage(String s) {
// Methode, um eine Nachricht an alle verbundenen Clients zu senden
public void broadcastMessage(String message) {
System.out.println(message);
if (message != null) {
for (ClientHandler client : clients) {
client.sendMessage(message); // Nachricht an jeden Client senden
}
}
}
public static void main(String[] args) {
new ChatServer(3141);
new ChatServer(3141); // ChatServer auf Port 3141 starten (eventuell den Port flexibler noch wählen? falls belegt)
}
// Methode, um einen Client aus der Liste der verbundenen Clients zu entfernen
public void removeClient(ClientHandler client) {
clients.remove(client);
}
}

124
src/main/java/CreateUser.java

@ -0,0 +1,124 @@
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.io.FileWriter;
import java.io.IOException;
import java.util.UUID;
class CreateUser {
private String id;
private String userName;
private String password;
private String birthday;
// Constructor
public CreateUser(String id, String name, String password, String birthday) {
this.id = id;
this.userName = name;
this.password = password;
this.birthday = birthday;
}
// Getters and Setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
// Function to create user with validation
public static CreateUser createUser(String id, String userName, String password, String birthday) {
if (userName == null || userName.isEmpty()) {
throw new IllegalArgumentException("Username cannot be empty");
}
if (password == null || password.isEmpty()) {
throw new IllegalArgumentException("Password cannot be empty");
}
if (password.length() < 6) {
throw new IllegalArgumentException("Password must be at least 6 characters long");
} return new CreateUser(id, userName, password, birthday);
}
// Function to save to JSON file, replace with database call later
public void saveToJsonFile(String filename) {
List<CreateUser> userList = readUserListFromJsonFile(filename);
userList.add(this);
try (FileWriter fileWriter = new FileWriter(filename)) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
gson.toJson(userList, fileWriter);
System.out.println("User information appended to " + filename);
} catch (IOException e) {
System.out.println("Error occurred while saving user information to JSON file: " + e.getMessage());
}
}
// Function to read user information from a JSON file
public static List<CreateUser> readUserListFromJsonFile(String filename) {
List<CreateUser> userList = new ArrayList<>();
try (Reader reader = new FileReader(filename)) {
Type userListType = new TypeToken<List<CreateUser>>() {}.getType();
Gson gson = new Gson();
userList = gson.fromJson(reader, userListType);
} catch (FileNotFoundException e) {
// File does not exist yet, so return an empty list
} catch (IOException e) {
System.out.println("Error occurred while reading user information from JSON file: " + e.getMessage());
}
return userList;
}
public static void main(String[] args) {
try {
// Example usage
UUID randomUUID = UUID.randomUUID();
CreateUser user = createUser(randomUUID.toString(), "Another Test User", "TestPasswort123", "01.01.2000");
// Example of accessing properties
System.out.println("UserID: " + user.getId());
System.out.println("User Name: " + user.getUserName());
System.out.println("User Password: " + user.getPassword());
System.out.println("User Birthday: " + user.getBirthday());
// Save user information to a JSON file
user.saveToJsonFile("user.json");
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

103
src/main/java/SignUpGUI.java

@ -0,0 +1,103 @@
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.UUID;
public class SignUpGUI extends JFrame implements ActionListener {
private JTextField usernameField, passwordField, confirmPasswordField, birthdayField;
private JButton signUpButton;
public SignUpGUI() {
setTitle("Sign Up");
setSize(300, 250);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(null);
JLabel usernameLabel = new JLabel("Username:");
usernameLabel.setBounds(20, 20, 80, 25);
add(usernameLabel);
usernameField = new JTextField();
usernameField.setBounds(100, 20, 160, 25);
add(usernameField);
JLabel passwordLabel = new JLabel("Password:");
passwordLabel.setBounds(20, 50, 80, 25);
add(passwordLabel);
passwordField = new JPasswordField();
passwordField.setBounds(100, 50, 160, 25);
add(passwordField);
JLabel confirmPasswordLabel = new JLabel("Confirm Password:");
confirmPasswordLabel.setBounds(20, 80, 120, 25);
add(confirmPasswordLabel);
confirmPasswordField = new JPasswordField();
confirmPasswordField.setBounds(140, 80, 120, 25);
add(confirmPasswordField);
JLabel birthdayLabel = new JLabel("Birthday:");
birthdayLabel.setBounds(20, 110, 80, 25);
add(birthdayLabel);
birthdayField = new JTextField();
birthdayField.setBounds(100, 110, 160, 25);
add(birthdayField);
signUpButton = new JButton("Sign Up");
signUpButton.setBounds(100, 150, 100, 25);
signUpButton.addActionListener(this);
add(signUpButton);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == signUpButton) {
String username = usernameField.getText();
String password = passwordField.getText();
String confirmPassword = confirmPasswordField.getText();
String birthday = birthdayField.getText();
if (!password.equals(confirmPassword)) {
JOptionPane.showMessageDialog(this, "Passwords do not match!", "Sign Up Error", JOptionPane.ERROR_MESSAGE);
return;
}
if (!isUsernameAvailable("user.json", username)) {
JOptionPane.showMessageDialog(this, "Username already exists!", "Sign Up Error", JOptionPane.ERROR_MESSAGE);
return;
}
try {
UUID randomUUID = UUID.randomUUID();
CreateUser user = CreateUser.createUser(randomUUID.toString(), username, password, birthday);
user.saveToJsonFile("user.json");
JOptionPane.showMessageDialog(this, "User signed up successfully!");
dispose();
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage(), "Sign Up Error", JOptionPane.ERROR_MESSAGE);
}
}
}
// Function to check if the input username doesn't already exist in the JSON file
private boolean isUsernameAvailable(String filename, String username) {
List<CreateUser> userList = CreateUser.readUserListFromJsonFile(filename);
if (userList != null) {
for (CreateUser user : userList) {
if (user.getUserName().equals(username)) {
return false; // Username already exists
}
}
}
return true; // Username is available
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SignUpGUI signUpGUI = new SignUpGUI();
signUpGUI.setVisible(true);
});
}
}

14
user.json

@ -0,0 +1,14 @@
[
{
"id": "961ca202-ecbd-4dfc-ac0b-28f367618aa1",
"userName": "asd",
"password": "123456",
"birthday": "1"
},
{
"id": "d563a466-753b-4a5e-8b6c-e7e4756c7397",
"userName": "asd1",
"password": "123456",
"birthday": "1"
}
]
Loading…
Cancel
Save