+
+
+
+ """);
+ }
+ }
+
+ public void updateUserDataById(Socket clientSocket, BufferedReader in, String requestLine)
+ throws IOException {
+ try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
+
+ String requestBody = HttpUtils.getRequestBody(in);
+ int userId = UserUtils.getUserId(requestLine);
+
+ String newName = HttpUtils.extractQueryParams(requestBody).get("new-name");
+ String newJob = HttpUtils.extractQueryParams(requestBody).get("new-job");
+
+ if (!newName.equals("") && newName != null) {
+ data.getUserDataByIndex(userId - 1).setName(newName);
+ }
+
+ if (!newJob.equals("") && newJob != null) {
+ data.getUserDataByIndex(userId - 1).setJob(newJob);
+ }
+
+ // HTTP response header
+ out.println("HTTP/1.1 200 OK");
+ out.println("Content-Type: application/json");
+ out.println();
+
+ // HTTP response body
+ out.println(
+ """
+ {
+ "status": "success",
+ "message": "Data updated successfully"
+ }
+ """);
+ }
+ }
+
+ public void deleteUserDataById(Socket clientSocket, String requestLine) throws IOException {
+ System.out.println("delete bang!");
+ try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
+
+ int userId = UserUtils.getUserId(requestLine);
+
+ data.removeData(userId - 1);
+
+ // HTTP response header
+ out.println("HTTP/1.1 200 OK");
+ out.println("Content-Type: application/json");
+ out.println();
+
+ // HTTP response body
+ out.println(
+ """
+ {
+ "status": "success",
+ "message": "Data deleted successfully"
+ }
+ """);
+ }
+ }
+}
diff --git a/src/main/java/com/server/model/User.java b/src/main/java/com/server/model/User.java
new file mode 100644
index 0000000..017aa0c
--- /dev/null
+++ b/src/main/java/com/server/model/User.java
@@ -0,0 +1,26 @@
+package com.server.model;
+
+public class User {
+ private String name, job;
+
+ public User(String name, String job) {
+ this.name = name;
+ this.job = job;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getJob() {
+ return job;
+ }
+
+ public void setJob(String job) {
+ this.job = job;
+ }
+}
diff --git a/src/main/java/com/server/model/Users.java b/src/main/java/com/server/model/Users.java
new file mode 100644
index 0000000..799e2a5
--- /dev/null
+++ b/src/main/java/com/server/model/Users.java
@@ -0,0 +1,73 @@
+package com.server.model;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+public class Users {
+ private ArrayList data;
+
+ public Users() {
+ data = new ArrayList<>();
+
+ data.add(new User("Alex", "Data Analyst"));
+ data.add(new User("Budi", "Frontend Web Developer"));
+ data.add(new User("Cahya", "Computer Vision Engineer"));
+ data.add(new User("Dono", "Data Analyst"));
+ data.add(new User("Cakra", "Frontend Web Developer"));
+ data.add(new User("Zara", "Frontend Web Developer"));
+ data.add(new User("Jojo", "Machine Learning Engineer"));
+ data.add(new User("Pepe", "Data Analyst"));
+ }
+
+ public ArrayList getAllData() {
+ return data;
+ }
+
+ public int getArrayLength() {
+ return data.size();
+ }
+
+ public User getUserDataByIndex(int index) {
+ return data.get(index);
+ }
+
+ public ArrayList getUserDataByQuery(Map queryParams) {
+ String nameWanted = queryParams.get("name");
+ String jobWanted = queryParams.get("job");
+
+ ArrayList result = new ArrayList<>();
+
+ if (!nameWanted.equals("") && !jobWanted.equals("")) {
+ for (User datum : data) {
+ if (datum.getName().equalsIgnoreCase(nameWanted)
+ && datum.getJob().equalsIgnoreCase(jobWanted)) {
+ result.add(datum);
+ }
+ }
+ } else if (!nameWanted.equals("")) {
+ for (User datum : data) {
+ if (datum.getName().equalsIgnoreCase(nameWanted)) {
+ result.add(datum);
+ }
+ }
+ } else if (!jobWanted.equals("")) {
+ for (User datum : data) {
+ if (datum.getJob().equalsIgnoreCase(jobWanted)) {
+ result.add(datum);
+ }
+ }
+ } else {
+ result = getAllData();
+ }
+
+ return result;
+ }
+
+ public void addNewData(User newData) {
+ data.add(newData);
+ }
+
+ public void removeData(int index) {
+ data.remove(index);
+ }
+}
diff --git a/src/main/java/com/server/utils/HttpUtils.java b/src/main/java/com/server/utils/HttpUtils.java
new file mode 100644
index 0000000..dcc118d
--- /dev/null
+++ b/src/main/java/com/server/utils/HttpUtils.java
@@ -0,0 +1,102 @@
+package com.server.utils;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.net.Socket;
+import java.util.HashMap;
+import java.util.Map;
+
+public class HttpUtils {
+
+ /**
+ * Sends a 404 Not Found response to the client.
+ *
+ * @param clientSocket the socket connection to the client
+ * @throws IOException if an I/O error occurs while sending the response
+ */
+ public static void handle404ErrorResponse(Socket clientSocket) throws IOException {
+ try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
+ out.println("HTTP/1.1 404 Not Found");
+ out.println("Content-Type: text/html");
+ out.println();
+ out.println("
404 Not Found!
");
+ }
+ }
+
+ /**
+ * Sends a 500 Internal Server Error response to the client.
+ *
+ * @param clientSocket the socket connection to the client
+ * @param e the exception that occurred, which will be included in the response message
+ */
+ public static void handleServerErrorResponse(Socket clientSocket, Exception e) {
+ try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
+ out.println("HTTP/1.1 500 Internal Server Error");
+ out.println("Content-Type: text/html");
+ out.println();
+ out.println("Error occured: " + e.getMessage());
+ } catch (IOException ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ /**
+ * Retrieves the entire HTTP request body from the given BufferedReader.
+ *
+ * @param in the BufferedReader from which the HTTP request body is read
+ * @return a String containing the entire request body
+ */
+ public static String getRequestBody(BufferedReader in) throws IOException {
+ String requestBody = null;
+ int contentLength = getContentLength(in);
+
+ // Read the body content if not empty
+ if (contentLength > 0) {
+ char[] body = new char[contentLength];
+ try {
+ in.read(body, 0, contentLength);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ requestBody = new String(body);
+ }
+
+ return requestBody;
+ }
+
+ private static int getContentLength(BufferedReader in) throws IOException {
+ String inputLine;
+ int contentLength = 0;
+ while ((inputLine = in.readLine()) != null && !inputLine.isEmpty()) {
+ if (inputLine.startsWith("Content-Length:")) {
+ contentLength = Integer.parseInt(inputLine.split(":")[1].trim());
+ }
+ }
+
+ return contentLength;
+ }
+
+ /**
+ * Extracts raw query parameters from a URL string and returns them as a map.
+ *
+ * @param queryParam the URL query parameter string (e.g., "key1=value1&key2=value2")
+ * @return a Map containing the extracted query parameters, where each key is a parameter name and
+ * the corresponding value is the parameter value
+ */
+ public static Map extractQueryParams(String queryParam) {
+ Map result = new HashMap<>();
+ String[] pairs = queryParam.split("&");
+
+ for (String pair : pairs) {
+ String[] keyValue = pair.split("=");
+ if (keyValue.length == 2) {
+ result.put(keyValue[0], keyValue[1]);
+ } else if (keyValue.length == 1) {
+ result.put(keyValue[0], "");
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/src/main/java/com/server/utils/UserUtils.java b/src/main/java/com/server/utils/UserUtils.java
new file mode 100644
index 0000000..eda46ef
--- /dev/null
+++ b/src/main/java/com/server/utils/UserUtils.java
@@ -0,0 +1,23 @@
+package com.server.utils;
+
+public class UserUtils {
+
+ /**
+ * Retrieves the user ID from the specified URL request line.
+ *
+ * @param requestLine the HTTP request line containing the URL with the user ID parameter
+ * @return the user ID extracted from the request line
+ */
+ public static int getUserId(String requestLine) {
+ String[] arrayRequestLine = requestLine.split(" ");
+ int userId = -1;
+
+ try {
+ userId = Integer.parseInt(arrayRequestLine[1].substring("/users/".length()));
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ return userId;
+ }
+}
diff --git a/src/model/User.java b/src/model/User.java
deleted file mode 100644
index 548c4fa..0000000
--- a/src/model/User.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package model;
-
-public class User {
- private String name, job;
-
- public User(String name, String job) {
- this.name = name;
- this.job = job;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getJob() {
- return job;
- }
-
- public void setJob(String job) {
- this.job = job;
- }
-}
diff --git a/src/model/Users.java b/src/model/Users.java
deleted file mode 100644
index 086ec63..0000000
--- a/src/model/Users.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package model;
-
-import java.util.ArrayList;
-import java.util.Map;
-
-public class Users {
- private ArrayList data;
-
- public Users() {
- data = new ArrayList<>();
-
- data.add(new User("Alex", "Data Analyst"));
- data.add(new User("Budi", "Frontend Web Developer"));
- data.add(new User("Cahya", "Computer Vision Engineer"));
- data.add(new User("Dono", "Data Analyst"));
- data.add(new User("Cakra", "Frontend Web Developer"));
- data.add(new User("Zara", "Frontend Web Developer"));
- data.add(new User("Jojo", "Machine Learning Engineer"));
- data.add(new User("Pepe", "Data Analyst"));
- }
-
- public ArrayList getAllData() {
- return data;
- }
-
- public int getArrayLength() {
- return data.size();
- }
-
- public User getUserDataByIndex(int index) {
- return data.get(index);
- }
-
- public ArrayList getUserDataByQuery(Map queryParams) {
- String nameWanted = queryParams.get("name");
- String jobWanted = queryParams.get("job");
-
- ArrayList result = new ArrayList<>();
-
- if (!nameWanted.equals("") && !jobWanted.equals("")) {
- for (User datum : data) {
- if (datum.getName().equalsIgnoreCase(nameWanted) &&
- datum.getJob().equalsIgnoreCase(jobWanted)) {
- result.add(datum);
- }
- }
- } else if (!nameWanted.equals("")) {
- for (User datum : data) {
- if (datum.getName().equalsIgnoreCase(nameWanted)) {
- result.add(datum);
- }
- }
- } else if (!jobWanted.equals("")) {
- for (User datum : data) {
- if (datum.getJob().equalsIgnoreCase(jobWanted)) {
- result.add(datum);
- }
- }
- } else {
- result = getAllData();
- }
-
- return result;
- }
-
- public void addNewData(User newData) {
- data.add(newData);
- }
-
- public void removeData(int index) {
- data.remove(index);
- }
-}
\ No newline at end of file
diff --git a/src/test/java/com/server/model/UsersTest.java b/src/test/java/com/server/model/UsersTest.java
new file mode 100644
index 0000000..0e12e84
--- /dev/null
+++ b/src/test/java/com/server/model/UsersTest.java
@@ -0,0 +1,33 @@
+package com.server.model;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+import org.junit.jupiter.api.Test;
+
+public class UsersTest {
+
+ @Test
+ public void testAddNewData() {
+ Users users = new Users();
+ int initialSize = users.getArrayLength();
+
+ User newUser = new User("Test User", "Tester");
+ users.addNewData(newUser);
+
+ assertEquals(initialSize + 1, users.getArrayLength(), "Users array size should increase by 1");
+ assertEquals(
+ "Test User", users.getUserDataByIndex(initialSize).getName(), "New user name should match");
+ assertEquals(
+ "Tester", users.getUserDataByIndex(initialSize).getJob(), "New user job should match");
+ }
+
+ @Test
+ public void testRemoveData() {
+ Users users = new Users();
+ int initialSize = users.getArrayLength();
+
+ users.removeData(0); // Remove the first user
+
+ assertEquals(initialSize - 1, users.getArrayLength(), "Users array size should decrease by 1");
+ }
+}
diff --git a/src/utils/HttpUtils.java b/src/utils/HttpUtils.java
deleted file mode 100644
index 4382d47..0000000
--- a/src/utils/HttpUtils.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package utils;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.net.Socket;
-import java.util.HashMap;
-import java.util.Map;
-
-public class HttpUtils {
-
- /**
- * Sends a 404 Not Found response to the client.
- *
- * @param clientSocket the socket connection to the client
- * @throws IOException if an I/O error occurs while sending the response
- */
- public static void handle404ErrorResponse(Socket clientSocket) throws IOException {
- try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
- out.println("HTTP/1.1 404 Not Found");
- out.println("Content-Type: text/html");
- out.println();
- out.println("
404 Not Found!
");
- }
- }
-
- /**
- * Sends a 500 Internal Server Error response to the client.
- *
- * @param clientSocket the socket connection to the client
- * @param e the exception that occurred, which will be included in the response message
- */
- public static void handleServerErrorResponse(Socket clientSocket, Exception e) {
- try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
- out.println("HTTP/1.1 500 Internal Server Error");
- out.println("Content-Type: text/html");
- out.println();
- out.println("Error occured: " + e.getMessage());
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
-
- /**
- * Retrieves the entire HTTP request body from the given BufferedReader.
- *
- * @param in the BufferedReader from which the HTTP request body is read
- * @return a String containing the entire request body
- */
- public static String getRequestBody(BufferedReader in) throws IOException {
- String requestBody = null;
- int contentLength = getContentLength(in);
-
- // Read the body content if not empty
- if (contentLength > 0) {
- char[] body = new char[contentLength];
- try {
- in.read(body, 0, contentLength);
- } catch (IOException e) {
- e.printStackTrace();
- }
- requestBody = new String(body);
- }
-
- return requestBody;
- }
-
- private static int getContentLength(BufferedReader in) throws IOException {
- String inputLine;
- int contentLength = 0;
- while ((inputLine = in.readLine()) != null && !inputLine.isEmpty()) {
- if (inputLine.startsWith("Content-Length:")) {
- contentLength = Integer.parseInt(inputLine.split(":")[1].trim());
- }
- }
-
- return contentLength;
- }
-
- /**
- * Extracts raw query parameters from a URL string and returns them as a map.
- *
- * @param queryParam the URL query parameter string (e.g., "key1=value1&key2=value2")
- * @return a Map containing the extracted query parameters, where each key is a parameter name
- * and the corresponding value is the parameter value
- */
- public static Map extractQueryParams(String queryParam) {
- Map result = new HashMap<>();
- String[] pairs = queryParam.split("&");
-
- for (String pair : pairs) {
- String[] keyValue = pair.split("=");
- if (keyValue.length == 2) {
- result.put(keyValue[0], keyValue[1]);
- } else if (keyValue.length == 1) {
- result.put(keyValue[0], "");
- }
- }
-
- return result;
- }
-
-}
diff --git a/src/utils/UserUtils.java b/src/utils/UserUtils.java
deleted file mode 100644
index 999617d..0000000
--- a/src/utils/UserUtils.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package utils;
-
-public class UserUtils {
-
- /**
- * Retrieves the user ID from the specified URL request line.
- *
- * @param requestLine the HTTP request line containing the URL with the user ID parameter
- * @return the user ID extracted from the request line
- */
- public static int getUserId(String requestLine) {
- String[] arrayRequestLine = requestLine.split(" ");
- int userId = -1;
-
- try {
- userId = Integer.parseInt(arrayRequestLine[1].substring("/users/".length()));
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- return userId;
- }
-}
From bdd84468bf7f9c9a7243c3f411d23bc09d1a3ba8 Mon Sep 17 00:00:00 2001
From: Farrel Augusta Dinata
Date: Wed, 23 Sep 2026 08:35:12 +0700
Subject: [PATCH 2/4] refactor: setup to Maven REST API with CI/CD and tooling
---
README.md | 96 +++---
pom.xml | 7 +
.../com/server/controller/RootController.java | 67 ++--
.../server/controller/UsersController.java | 286 +++---------------
src/main/java/com/server/utils/HttpUtils.java | 12 +-
5 files changed, 132 insertions(+), 336 deletions(-)
diff --git a/README.md b/README.md
index f0c5cab..ca51584 100644
--- a/README.md
+++ b/README.md
@@ -1,23 +1,22 @@
-# Basic Java Web Server Project
+# Basic Java Web Server REST API
-This is a basic web server project built with **native Java**, utilizing only the Java standard library without any external frameworks. It demonstrates fundamental concepts such as routing, handling different HTTP methods, and processing URL parameters and query strings. The goal of this project is to serve as a reference for anyone interested in understanding how a web service can be implemented using just Java.
+This is a basic web server project originally built with native Java, now refactored into a **professional RESTful JSON API**. It demonstrates fundamental backend concepts such as handling HTTP methods, thread pools for concurrency, routing, and processing JSON payloads. The goal of this project is to serve as an educational reference for building a modern web service in Java from scratch.
## Features
-- **Basic Routing**: Set up routes for different endpoints.
-- **Route with Parameters**: Handle dynamic routes with URL parameters.
-- **Query Parameters**: Extract and process query strings from the URL.
-- **HTTP Methods**: Support for common HTTP methods: `GET`, `POST`, `PATCH`, `DELETE`.
+- **REST API (JSON)**: Fully responds and consumes `application/json` using Google's Gson library.
+- **Concurrency**: Built-in `ThreadPoolExecutor` for handling multiple HTTP requests simultaneously.
+- **Maven Architecture**: Standardized project structure and dependency management.
+- **Dev Tooling**: Code automatically formatted via **Spotless** (Google Java Format) and linted via **Checkstyle**.
+- **CI/CD Ready**: Includes GitHub Actions for PR checks (Format/Lint/Test) and multi-stage manual deployment pipelines using SCP/SSH.
## Getting Started
### Prerequisites
-Ensure you have **Java Development Kit (JDK)** installed on your machine.
-
-- [Download JDK](https://www.oracle.com/java/technologies/downloads/) (or the version you prefer)
+Ensure you have **Java Development Kit (JDK) 17+** and **Apache Maven** installed on your machine.
### Installation
@@ -32,64 +31,63 @@ Ensure you have **Java Development Kit (JDK)** installed on your machine.
### Running the Server
-1. Compile Java program first:
- ```bash
- javac -d bin src/Main.java src/controller/*.java src/model/*.java src/utils/*.java
- ```
-2. Run compiled program
- ```bash
- java -cp bin Main
- ```
-
-The server will be running at http://localhost:8000
+Using Maven, you can compile and start the server immediately:
+```bash
+mvn clean compile exec:java -Dexec.mainClass="com.server.Main"
+```
+The server will be running at `http://localhost:8000`
+### Building the Executable JAR
+If you want to build a deployment-ready Fat JAR:
+```bash
+mvn clean package -DskipTests
+java -jar target/basic-web-server-1.0-SNAPSHOT.jar
+```
-## Endpoints
-Here are the key endpoints that you can interact with:
+## Tooling & Testing
-```
-GET / : Returns a simple welcome message and provide simple form to handle request input
-GET /users : Fetch all users
-GET /users/:id : Fetch a data by their ID
-POST /users : Add a new user
-PATCH /users/:id : Update user information
-DELETE /users/:id : Delete a user by their ID
-GET /search?name=&job= : Retrieves data based on user input from a search form, filtering results by name and job
+Run the automated tests:
+```bash
+mvn test
```
-## Query Parameters
-Example: /search?name=John&job=data+analyst
-Query parameters can be extracted and used in request processing.
+Format the codebase and check for linting errors:
+```bash
+mvn spotless:apply checkstyle:check
+```
-## HTTP Methods
-The service supports the following HTTP methods:
+## Endpoints
+Here are the key REST endpoints that you can interact with (use Postman or `curl`):
```
-GET: Retrieve data.
-POST: Submit new data.
-PATCH: Update partial existing data.
-DELETE: Remove data.
+GET / : Returns a JSON health check and API status
+GET /users : Fetch all users as a JSON array
+GET /users/:id : Fetch a specific user by their ID
+POST /users : Add a new user (Accepts JSON body: {"name": "...", "job": "..."})
+PATCH /users/:id : Update user information (Accepts JSON body: {"name": "..."})
+DELETE /users/:id : Delete a user by their ID
+GET /search?name=&job= : Filters users and returns a JSON array
```
## Code Structure
-The project is simple and has the following structure:
+The project uses the standard Maven structure:
```bash
/root
-├───bin # compiled Java file
-│ ├─── /controller
-│ ├─── /model
-│ └─── /utils
-├───lib
+├───.github/workflows # CI/CD Pipelines
+├───pom.xml # Build config and dependencies
└───src
- ├─── /controller # A handler for any request
- ├─── /model # A temporary data user blueprint
- ├─── /utils # Some helper function
- └─── Main.java # Main server logic
+ ├───main/java/com/server
+ │ ├─── /controller # HTTP route handlers
+ │ ├─── /model # Data structures and tracking
+ │ ├─── /utils # Parsers and HTTP helpers
+ │ └─── Main.java # Server initialization and Thread Pool
+ └───test/java/com/server
+ └─── /model # JUnit 5 test cases
```
## License
This project is licensed under the MIT License.
## Acknowledgments
-This project is intended to help others learn the basics of building a web service with Java native ☕.
\ No newline at end of file
+This project is intended to help others learn the basics of building a robust REST API with Java ☕.
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 5a5482d..a48dc8f 100644
--- a/pom.xml
+++ b/pom.xml
@@ -21,6 +21,13 @@
5.10.0test
+
+
+
+ com.google.code.gson
+ gson
+ 2.10.1
+
diff --git a/src/main/java/com/server/controller/RootController.java b/src/main/java/com/server/controller/RootController.java
index 7e39322..adcb3a0 100644
--- a/src/main/java/com/server/controller/RootController.java
+++ b/src/main/java/com/server/controller/RootController.java
@@ -1,69 +1,48 @@
package com.server.controller;
+import com.google.gson.Gson;
import com.server.model.Users;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
+import java.util.HashMap;
+import java.util.Map;
+/** Controller for handling requests to the root endpoint. */
public class RootController {
private Users data;
+ private Gson gson = new Gson();
+ /**
+ * Constructs the root controller.
+ *
+ * @param data The user data model.
+ */
public RootController(Users data) {
this.data = data;
}
+ /**
+ * Handles GET requests to the root endpoint.
+ *
+ * @param clientSocket The client socket.
+ * @throws IOException If an I/O error occurs.
+ */
public void handleGetRequest(Socket clientSocket) throws IOException {
try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
+ Map responseBody = new HashMap<>();
+ responseBody.put("status", "UP");
+ responseBody.put("message", "Welcome to Basic Web Server API");
+ responseBody.put("totalUsers", data.getArrayLength());
+
// HTTP response header
out.println("HTTP/1.1 200 OK");
- out.println("Content-Type: text/html");
+ out.println("Content-Type: application/json");
out.println();
// HTTP response body
- out.println(
- """
-
-
-
- Root Page
-
-
-
-
Welcome! You successfully get response from server
-
Current user: """
- + data.getArrayLength()
- + """
-
-
-
-
-
-
Send user data to server!
-
-
-
-
-
Search user data!
-
-
*) Empty search box will get all user data
-
-
-
-
- """);
+ out.println(gson.toJson(responseBody));
}
}
}
diff --git a/src/main/java/com/server/controller/UsersController.java b/src/main/java/com/server/controller/UsersController.java
index 67a61b9..39e0b1f 100644
--- a/src/main/java/com/server/controller/UsersController.java
+++ b/src/main/java/com/server/controller/UsersController.java
@@ -1,5 +1,7 @@
package com.server.controller;
+import com.google.gson.Gson;
+import com.google.gson.JsonObject;
import com.server.model.User;
import com.server.model.Users;
import com.server.utils.HttpUtils;
@@ -13,8 +15,10 @@
import java.util.ArrayList;
import java.util.Map;
+/** Controller for user endpoints, refactored to REST API (JSON). */
public class UsersController {
private Users data;
+ private Gson gson = new Gson();
public UsersController(Users data) {
this.data = data;
@@ -22,182 +26,25 @@ public UsersController(Users data) {
public void getAllUsers(Socket clientSocket) throws IOException {
try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
-
ArrayList dataResult = data.getAllData();
- String result = "";
- for (User datum : dataResult) {
- result +=
- """
-