From cda2f75523027e49e2a824973d6dcd1a15b6d63c Mon Sep 17 00:00:00 2001 From: jLereback <112405931+jLereback@users.noreply.github.com> Date: Mon, 20 Feb 2023 16:12:19 +0100 Subject: [PATCH 01/44] Refactor Main.java --- src/main/java/org/fungover/haze/Main.java | 119 ++++++++++++++-------- 1 file changed, 79 insertions(+), 40 deletions(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 18538173..46e86a25 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -18,56 +18,87 @@ public class Main { static Logger logger = LogManager.getLogger(Main.class); public static void main(String[] args) { - Initialize initialize = new Initialize(); - initialize.importCliOptions(args); + Initialize initialize = getInitialize(args); HazeList hazeList = new HazeList(); HazeDatabase hazeDatabase = new HazeDatabase(); Auth auth = new Auth(); initializeServer(args, initialize, auth); final boolean isPasswordSet = auth.isPasswordSet(); + addHook(hazeDatabase); + try (ServerSocket serverSocket = new ServerSocket()) { + initSocket(initialize, serverSocket); + whileServerOpen(hazeList, hazeDatabase, auth, isPasswordSet, serverSocket); + } catch (IOException e) { + logger.error(e); + } + logger.info("Shutting down...."); + } - Thread printingHook = new Thread(() -> shutdown(hazeDatabase)); - Runtime.getRuntime().addShutdownHook(printingHook); + private static void whileServerOpen(HazeList hazeList, HazeDatabase hazeDatabase, Auth auth, boolean isPasswordSet, ServerSocket serverSocket) throws IOException { + while (serverOpen) { + var client = serverSocket.accept(); + logger.info("Application started: serverSocket.accept()"); - try (ServerSocket serverSocket = new ServerSocket()) { - serverSocket.setReuseAddress(true); - serverSocket.bind(new InetSocketAddress(initialize.getPort())); - while (serverOpen) { - var client = serverSocket.accept(); - logger.info("Application started: serverSocket.accept()"); + runThread(hazeList, hazeDatabase, auth, isPasswordSet, client); + } + } - Runnable newThread = () -> { - try { - BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream())); - boolean clientAuthenticated = false; - while (true) { - List inputList = new ArrayList<>(); + private static void runThread(HazeList hazeList, HazeDatabase hazeDatabase, Auth auth, boolean isPasswordSet, Socket client) { + Runnable newThread = () -> createThread(hazeList, hazeDatabase, auth, isPasswordSet, client); + Thread.startVirtualThread(newThread); + } - String firstReading = input.readLine(); - readInputStream(input, inputList, firstReading); + private static void createThread(HazeList hazeList, HazeDatabase hazeDatabase, Auth auth, boolean isPasswordSet, Socket client) { + try { + BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream())); + boolean clientAuthenticated = false; + while (true) { + List inputList = getInputList(input); + clientAuthenticated = authenticateClient(auth, isPasswordSet, client, inputList, clientAuthenticated); + handleThread(hazeList, hazeDatabase, client, inputList); + } - clientAuthenticated = authenticateClient(auth, isPasswordSet, client, inputList, clientAuthenticated); + } catch (IOException e) { + logger.error(e); + } + } - client.getOutputStream().write(executeCommand(hazeDatabase, inputList, hazeList).getBytes()); + private static void handleThread(HazeList hazeList, HazeDatabase hazeDatabase, Socket client, List inputList) throws IOException { + controlCommand(hazeList, hazeDatabase, client, inputList); + printThreadDebug(); - inputList.forEach(System.out::println); // For checking incoming message + inputList.clear(); + } - printThreadDebug(); + private static void controlCommand(HazeList hazeList, HazeDatabase hazeDatabase, Socket client, List inputList) throws IOException { + client.getOutputStream().write(executeCommand(hazeDatabase, inputList, hazeList).getBytes()); - inputList.clear(); - } + inputList.forEach(System.out::println); // For checking incoming message + } - } catch (IOException e) { - logger.error(e); - } - }; - Thread.startVirtualThread(newThread); - } - } catch (IOException e) { - logger.error(e); - } - logger.info("Shutting down...."); + private static List getInputList(BufferedReader input) throws IOException { + List inputList = new ArrayList<>(); + + String firstReading = input.readLine(); + readInputStream(input, inputList, firstReading); + return inputList; + } + + private static void initSocket(Initialize initialize, ServerSocket serverSocket) throws IOException { + serverSocket.setReuseAddress(true); + serverSocket.bind(new InetSocketAddress(initialize.getPort())); + } + + private static void addHook(HazeDatabase hazeDatabase) { + Thread printingHook = new Thread(() -> shutdown(hazeDatabase)); + Runtime.getRuntime().addShutdownHook(printingHook); + } + + private static Initialize getInitialize(String[] args) { + Initialize initialize = new Initialize(); + initialize.importCliOptions(args); + return initialize; } private static void shutdown(HazeDatabase hazeDatabase) { @@ -81,21 +112,30 @@ private static void printThreadDebug() { } public static String executeCommand(HazeDatabase hazeDatabase, List inputList, HazeList hazeList) { - if (inputList.isEmpty() || inputList.get(0).isEmpty()) { + if (inputList.isEmpty() || inputList.get(0).isEmpty()) return "-ERR no command provided\r\n"; - } logger.debug("executeCommand: {} {} ", () -> hazeDatabase, () -> inputList); - String command = inputList.get(0).toUpperCase(); - Command commandEnum; + Command commandEnum = getCommand(inputList); + if (commandEnum == null) + return "-ERR unknown command\r\n"; + + return commandSwitch(hazeDatabase, inputList, hazeList, commandEnum); + } + private static Command getCommand(List inputList) { + String command = inputList.get(0).toUpperCase(); + Command commandEnum; try { commandEnum = Command.valueOf(command); } catch (IllegalArgumentException ex) { - return "-ERR unknown command\r\n"; + return null; } + return commandEnum; + } + private static String commandSwitch(HazeDatabase hazeDatabase, List inputList, HazeList hazeList, Command commandEnum) { return switch (commandEnum) { case SET -> hazeDatabase.set(inputList); case GET -> hazeDatabase.get(inputList); @@ -112,7 +152,6 @@ public static String executeCommand(HazeDatabase hazeDatabase, List inpu case LMOVE -> hazeList.lMove(inputList); case LTRIM -> hazeList.callLtrim(inputList); case AUTH -> "+OK\r\n"; - }; } From 26ac19191de398695bcd0c7ce66895acf4e4a069 Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Thu, 1 Feb 2024 16:10:51 +0100 Subject: [PATCH 02/44] Updated getInitializeMetod and moved it to Initialize class --- pom.xml | 2 +- src/main/java/org/fungover/haze/Initialize.java | 6 +++++- src/main/java/org/fungover/haze/Main.java | 8 ++------ 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index 1ee02c72..3a738e3b 100644 --- a/pom.xml +++ b/pom.xml @@ -8,7 +8,7 @@ haze 2.0.1-SNAPSHOT - 19 + 21 UTF-8 fungover https://sonarcloud.io diff --git a/src/main/java/org/fungover/haze/Initialize.java b/src/main/java/org/fungover/haze/Initialize.java index 37fed6f7..22aecedb 100644 --- a/src/main/java/org/fungover/haze/Initialize.java +++ b/src/main/java/org/fungover/haze/Initialize.java @@ -38,9 +38,13 @@ public String getPassword() { return System.getenv("HAZE_PASSWORD"); } else return null; } - public void clearCliOptions() { cliOptions.clear(); } + public static Initialize getInitialize(String[] args) { + Initialize initialize = new Initialize(); + initialize.importCliOptions(args); + return initialize; + } } diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 46e86a25..a2912291 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -18,7 +18,7 @@ public class Main { static Logger logger = LogManager.getLogger(Main.class); public static void main(String[] args) { - Initialize initialize = getInitialize(args); + Initialize initialize = Initialize.getInitialize(args); HazeList hazeList = new HazeList(); HazeDatabase hazeDatabase = new HazeDatabase(); Auth auth = new Auth(); @@ -95,11 +95,7 @@ private static void addHook(HazeDatabase hazeDatabase) { Runtime.getRuntime().addShutdownHook(printingHook); } - private static Initialize getInitialize(String[] args) { - Initialize initialize = new Initialize(); - initialize.importCliOptions(args); - return initialize; - } + private static void shutdown(HazeDatabase hazeDatabase) { SaveFile.writeOnFile(hazeDatabase.copy()); From aab9ed7ec79550b00114a6243ed62a92c2b79f89 Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Thu, 1 Feb 2024 16:10:51 +0100 Subject: [PATCH 03/44] Updated getInitializeMetod and moved it to Initialize class + version updates --- .github/workflows/maven.yml | 6 +++--- .github/workflows/release.yml | 6 +++--- .github/workflows/sonar.yml | 8 ++++---- pom.xml | 6 ++++-- src/main/java/org/fungover/haze/Initialize.java | 6 +++++- src/main/java/org/fungover/haze/Main.java | 8 ++------ 6 files changed, 21 insertions(+), 19 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 8b2b364d..13989896 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -21,13 +21,13 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: Get Java Version run: | Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - - name: Set up JDK 19 - uses: actions/setup-java@v3 + - name: Set up JDK 21 + uses: actions/setup-java@v4 with: java-version: ${{ env.Java_Version }} distribution: 'temurin' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 1ec9e9e8..e47a3145 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,13 +13,13 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v3 + uses: actions/checkout@v4 - name: Get Java Version run: | Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - - name: Set up JDK 19 - uses: actions/setup-java@v3 + - name: Set up JDK 21 + uses: actions/setup-java@v4 with: java-version: ${{ env.Java_Version }} distribution: 'temurin' diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index ddcae766..5e469edc 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -10,21 +10,21 @@ jobs: name: Build and analyze runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - name: Get Java Version run: | Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - - name: Set up JDK 19 - uses: actions/setup-java@v3 + - name: Set up JDK 21 + uses: actions/setup-java@v4 with: java-version: ${{ env.Java_Version }} distribution: 'temurin' cache: maven - name: Cache SonarCloud packages - uses: actions/cache@v3 + uses: actions/cache@v4 with: path: ~/.sonar/cache key: ${{ runner.os }}-sonar diff --git a/pom.xml b/pom.xml index 1ee02c72..db446a2f 100644 --- a/pom.xml +++ b/pom.xml @@ -8,7 +8,7 @@ haze 2.0.1-SNAPSHOT - 19 + 21 UTF-8 fungover https://sonarcloud.io @@ -54,11 +54,13 @@ org.apache.maven.plugins maven-compiler-plugin - 3.10.1 + 3.11.0 --enable-preview + 21 + 21 diff --git a/src/main/java/org/fungover/haze/Initialize.java b/src/main/java/org/fungover/haze/Initialize.java index 37fed6f7..22aecedb 100644 --- a/src/main/java/org/fungover/haze/Initialize.java +++ b/src/main/java/org/fungover/haze/Initialize.java @@ -38,9 +38,13 @@ public String getPassword() { return System.getenv("HAZE_PASSWORD"); } else return null; } - public void clearCliOptions() { cliOptions.clear(); } + public static Initialize getInitialize(String[] args) { + Initialize initialize = new Initialize(); + initialize.importCliOptions(args); + return initialize; + } } diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 46e86a25..a2912291 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -18,7 +18,7 @@ public class Main { static Logger logger = LogManager.getLogger(Main.class); public static void main(String[] args) { - Initialize initialize = getInitialize(args); + Initialize initialize = Initialize.getInitialize(args); HazeList hazeList = new HazeList(); HazeDatabase hazeDatabase = new HazeDatabase(); Auth auth = new Auth(); @@ -95,11 +95,7 @@ private static void addHook(HazeDatabase hazeDatabase) { Runtime.getRuntime().addShutdownHook(printingHook); } - private static Initialize getInitialize(String[] args) { - Initialize initialize = new Initialize(); - initialize.importCliOptions(args); - return initialize; - } + private static void shutdown(HazeDatabase hazeDatabase) { SaveFile.writeOnFile(hazeDatabase.copy()); From 310779471b2f29b435bfc044ccd9254147723f18 Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Fri, 2 Feb 2024 14:08:01 +0100 Subject: [PATCH 04/44] docker update --- Dockerfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index ba38162e..1a18e81f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM eclipse-temurin:19-jre-jammy +FROM eclipse-temurin:21-jre-jammy COPY target/dependency /lib COPY target/classes /app WORKDIR /app From 019527b1dc10352a804ccc8cef189dfe7d8c5549 Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Fri, 2 Feb 2024 15:08:10 +0100 Subject: [PATCH 05/44] version changes --- .github/workflows/maven.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/sonar.yml | 2 +- pom.xml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 13989896..aa97f72c 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -26,7 +26,7 @@ jobs: run: | Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - - name: Set up JDK 21 + - name: Set up JDK ${{env.Java_Version}} uses: actions/setup-java@v4 with: java-version: ${{ env.Java_Version }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e47a3145..87526d3e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -18,7 +18,7 @@ jobs: run: | Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - - name: Set up JDK 21 + - name: Set up ${{env.Java_Version}} uses: actions/setup-java@v4 with: java-version: ${{ env.Java_Version }} diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 5e469edc..b6f0d233 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -17,7 +17,7 @@ jobs: run: | Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - - name: Set up JDK 21 + - name: Set up ${{env.Java_Version}} uses: actions/setup-java@v4 with: java-version: ${{ env.Java_Version }} diff --git a/pom.xml b/pom.xml index dee99142..baa831ad 100644 --- a/pom.xml +++ b/pom.xml @@ -54,7 +54,7 @@ org.apache.maven.plugins maven-compiler-plugin - 3.11.0 + 3.12.1 --enable-preview From fff28c987e817cf72eaa0f1112efb305d731ee33 Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Fri, 2 Feb 2024 15:12:24 +0100 Subject: [PATCH 06/44] removed outdated preview code --- pom.xml | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/pom.xml b/pom.xml index baa831ad..24827742 100644 --- a/pom.xml +++ b/pom.xml @@ -55,13 +55,7 @@ org.apache.maven.plugins maven-compiler-plugin 3.12.1 - - - --enable-preview - - 21 - 21 - + org.apache.maven.plugins From ccb2f5848e76af73787272839d457a2360c2249b Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Fri, 2 Feb 2024 15:36:37 +0100 Subject: [PATCH 07/44] fix return type in executeCommand method --- src/main/java/org/fungover/haze/Main.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 64f300d9..3cccf219 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -6,12 +6,14 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; +import java.io.OptionalDataException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Optional; public class Main { static boolean serverOpen = true; @@ -93,7 +95,8 @@ public static String executeCommand(HazeDatabase hazeDatabase, List inpu try { commandEnum = Command.valueOf(command); } catch (IllegalArgumentException ex) { - return "-ERR unknown command\r\n"; + return Optional.ofNullable(command).orElse("Default value"); + } return switch (commandEnum) { From 469b517b3baa3147342b78ca5a75ea1521dc1f1f Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Fri, 2 Feb 2024 15:40:51 +0100 Subject: [PATCH 08/44] getInitialize method in Initialize class --- src/main/java/org/fungover/haze/Main.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 3cccf219..fb0b2bc2 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -20,8 +20,8 @@ public class Main { static Logger logger = LogManager.getLogger(Main.class); public static void main(String[] args) { - Initialize initialize = new Initialize(); - initialize.importCliOptions(args); + Initialize initialize = Initialize.getInitialize(args); + HazeDatabase hazeDatabase = new HazeDatabase(); HazeList hazeList = new HazeList(hazeDatabase); Auth auth = new Auth(); From b2cf5cff61fb7936ff64d660cf64082f3db9e9ea Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Mon, 5 Feb 2024 10:39:29 +0100 Subject: [PATCH 09/44] fixed errors after update Co-authored-by: robinalfengard --- src/main/java/org/fungover/haze/Main.java | 150 +++++++++++----------- 1 file changed, 74 insertions(+), 76 deletions(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 4100b859..5c4dea05 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -6,7 +6,6 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -import java.io.OptionalDataException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; @@ -21,7 +20,7 @@ public class Main { public static void main(String[] args) { - Initialize initialize = Initialize.getInitialize(args); + Initialize initialize = Initialize.getInitialize(args); HazeDatabase hazeDatabase = new HazeDatabase(); HazeList hazeList = new HazeList(hazeDatabase); @@ -100,7 +99,6 @@ private static void addHook(HazeDatabase hazeDatabase) { } - private static void shutdown(HazeDatabase hazeDatabase) { SaveFile.writeOnFile(hazeDatabase.copy()); logger.info("Shutting down...."); @@ -112,97 +110,97 @@ private static void printThreadDebug() { } public static String executeCommand(HazeDatabase hazeDatabase, List inputList, HazeList hazeList) { - - - if (inputList.isEmpty() || inputList.getFirst().isEmpty()) { - return "-ERR no command provided\r\n"; + } logger.debug("executeCommand: {} {} ", () -> hazeDatabase, () -> inputList); - - String command = inputList.getFirst().toUpperCase(); - - Command commandEnum = getCommand(inputList); - if (commandEnum == null) - return "-ERR unknown command\r\n"; - - return commandSwitch(hazeDatabase, inputList, hazeList, commandEnum); - } - - private static Command getCommand(List inputList) { - String command = inputList.get(0).toUpperCase(); Command commandEnum; + try { commandEnum = Command.valueOf(command); } catch (IllegalArgumentException ex) { - - return Optional.ofNullable(command).orElse("Default value"); - + return "-ERR unknown command\r\n"; + } + return commandSwitch (hazeDatabase, inputList, hazeList, commandEnum); + } +// private static Command getCommand (List < String > inputList) { +// String command = inputList.getFirst().toUpperCase(); +// Command commandEnum; +// try { +// commandEnum = Command.valueOf(command); +// } catch (IllegalArgumentException ex) { +// return Command.GET; +// } +// return commandEnum; +// } + + private static String commandSwitch (HazeDatabase hazeDatabase, List < String > inputList, HazeList + hazeList, Command commandEnum){ + return switch (commandEnum) { + case SET -> hazeDatabase.set(inputList); + case GET -> hazeDatabase.get(inputList); + case DEL -> hazeDatabase.delete(inputList.subList(1, inputList.size())); + case PING -> hazeDatabase.ping(inputList); + case SETNX -> hazeDatabase.setNX(inputList); + case EXISTS -> hazeDatabase.exists(inputList.subList(1, inputList.size())); + case SAVE -> SaveFile.writeOnFile(hazeDatabase.copy()); + case RPUSH -> hazeList.rPush(inputList); + case LPUSH -> hazeList.lPush(inputList); + case LPOP -> hazeList.callLPop(inputList); + case RPOP -> hazeList.callRPop(inputList); + case LLEN -> hazeList.lLen(inputList); + case LMOVE -> hazeList.lMove(inputList); + case LTRIM -> hazeList.callLtrim(inputList); + case AUTH -> "+OK\r\n"; + }; } - return commandEnum; - } - - private static String commandSwitch(HazeDatabase hazeDatabase, List inputList, HazeList hazeList, Command commandEnum) { - return switch (commandEnum) { - case SET -> hazeDatabase.set(inputList); - case GET -> hazeDatabase.get(inputList); - case DEL -> hazeDatabase.delete(inputList.subList(1, inputList.size())); - case PING -> hazeDatabase.ping(inputList); - case SETNX -> hazeDatabase.setNX(inputList); - case EXISTS -> hazeDatabase.exists(inputList.subList(1, inputList.size())); - case SAVE -> SaveFile.writeOnFile(hazeDatabase.copy()); - case RPUSH -> hazeList.rPush(inputList); - case LPUSH -> hazeList.lPush(inputList); - case LPOP -> hazeList.callLPop(inputList); - case RPOP -> hazeList.callRPop(inputList); - case LLEN -> hazeList.lLen(inputList); - case LMOVE -> hazeList.lMove(inputList); - case LTRIM -> hazeList.callLtrim(inputList); - case AUTH -> "+OK\r\n"; - }; - } - private static void readInputStream(BufferedReader input, List inputList, String firstReading) throws - IOException { - logger.debug("readInputStream: {} {} {}", () -> input, () -> inputList, () -> firstReading); - int size; - if (firstReading.startsWith("*")) { - size = Integer.parseInt(firstReading.substring(1)) * 2; - for (int i = 0; i < size; i++) { - String temp = input.readLine(); - if (!temp.contains("$")) - inputList.add(temp); + private static void readInputStream (BufferedReader input, List < String > inputList, String firstReading) throws + IOException { + logger.debug("readInputStream: {} {} {}", () -> input, () -> inputList, () -> firstReading); + int size; + if (firstReading.startsWith("*")) { + size = Integer.parseInt(firstReading.substring(1)) * 2; + for (int i = 0; i < size; i++) { + String temp = input.readLine(); + if (!temp.contains("$")) + inputList.add(temp); + } + } else { + String[] seperated = firstReading.split("\\s"); + inputList.addAll(Arrays.asList(seperated)); } - } else { - String[] seperated = firstReading.split("\\s"); - inputList.addAll(Arrays.asList(seperated)); } - } - private static void initializeServer(String[] args, Initialize initialize, Auth auth) { - initialize.importCliOptions(args); - auth.setPassword(initialize.getPassword()); - } + private static void initializeServer (String[]args, Initialize initialize, Auth auth){ + initialize.importCliOptions(args); + auth.setPassword(initialize.getPassword()); + } - private static boolean authenticateClient(Auth auth, boolean isPasswordSet, Socket client, List inputList, boolean clientAuthenticated) throws IOException { - if (authCommandReceived(isPasswordSet, inputList, clientAuthenticated)) - return auth.authenticate(inputList.get(1), client); + private static boolean authenticateClient (Auth auth,boolean isPasswordSet, Socket + client, List < String > inputList,boolean clientAuthenticated) throws IOException { + if (authCommandReceived(isPasswordSet, inputList, clientAuthenticated)) + return auth.authenticate(inputList.get(1), client); - shutdownClientIfNotAuthenticated(client, clientAuthenticated, isPasswordSet); - return clientAuthenticated; - } + shutdownClientIfNotAuthenticated(client, clientAuthenticated, isPasswordSet); + return clientAuthenticated; + } - private static void shutdownClientIfNotAuthenticated(Socket client, boolean clientAuthenticated, boolean isPasswordSet) throws IOException { - if (!clientAuthenticated && isPasswordSet) { - client.getOutputStream().write(Auth.printAuthError()); - client.shutdownOutput(); + private static void shutdownClientIfNotAuthenticated (Socket client,boolean clientAuthenticated, + boolean isPasswordSet) throws IOException { + if (!clientAuthenticated && isPasswordSet) { + client.getOutputStream().write(Auth.printAuthError()); + client.shutdownOutput(); + } } - } - private static boolean authCommandReceived(boolean isPasswordSet, List inputList, boolean clientAuthenticated) { - return isPasswordSet && !clientAuthenticated && inputList.size() == 2 && inputList.getFirst().equals("AUTH"); + private static boolean authCommandReceived ( boolean isPasswordSet, List inputList, + boolean clientAuthenticated){ + return isPasswordSet && !clientAuthenticated && inputList.size() == 2 && inputList.getFirst().equals("AUTH"); + } } -} + + From 878d88ab6c7105bddb737c6ab198e5d3b5dd3f79 Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Mon, 5 Feb 2024 12:19:22 +0100 Subject: [PATCH 10/44] Add test methods on Main.test Co-authored-by: robinalfengard --- pom.xml | 6 +++ src/main/java/org/fungover/haze/Main.java | 13 +----- src/test/java/org/fungover/haze/MainTest.java | 46 +++++++++++++++++++ 3 files changed, 54 insertions(+), 11 deletions(-) diff --git a/pom.xml b/pom.xml index 77dbbb83..cad19bdb 100644 --- a/pom.xml +++ b/pom.xml @@ -48,6 +48,12 @@ log4j-core 2.20.0 + + org.mockito + mockito-core + 5.3.1 + test + diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 5c4dea05..6c03e3c2 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -99,7 +99,7 @@ private static void addHook(HazeDatabase hazeDatabase) { } - private static void shutdown(HazeDatabase hazeDatabase) { + public static void shutdown(HazeDatabase hazeDatabase) { SaveFile.writeOnFile(hazeDatabase.copy()); logger.info("Shutting down...."); } @@ -126,16 +126,7 @@ public static String executeCommand(HazeDatabase hazeDatabase, List inpu } return commandSwitch (hazeDatabase, inputList, hazeList, commandEnum); } -// private static Command getCommand (List < String > inputList) { -// String command = inputList.getFirst().toUpperCase(); -// Command commandEnum; -// try { -// commandEnum = Command.valueOf(command); -// } catch (IllegalArgumentException ex) { -// return Command.GET; -// } -// return commandEnum; -// } + private static String commandSwitch (HazeDatabase hazeDatabase, List < String > inputList, HazeList hazeList, Command commandEnum){ diff --git a/src/test/java/org/fungover/haze/MainTest.java b/src/test/java/org/fungover/haze/MainTest.java index 67933883..6beeb387 100644 --- a/src/test/java/org/fungover/haze/MainTest.java +++ b/src/test/java/org/fungover/haze/MainTest.java @@ -1,13 +1,20 @@ package org.fungover.haze; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.*; class MainTest { @@ -102,4 +109,43 @@ void callExecuteCommandWithLMOVEShouldReturnErrorMessageWhenListIsEmpty() { void callExecuteCommandWithLTRIMShouldReturnErrorMessageWhenKeyDoesNotExist() { assertThat(Main.executeCommand(database, List.of("LTRIM", "key", "2", "3"), hazeList)).isEqualTo("-The key is not present in the database.\r\n"); } + + + + + + + @Test + @DisplayName("getInputList Should Return List With Correct Data Based On Index") + void getInputListShouldReturn(){ + String inputString = "First\nSecond\nThird"; + BufferedReader input = new BufferedReader(new StringReader(inputString)); + try { + List result = Main.getInputList(input); + assertThat(result.get(1)).isEqualTo("Second"); + + } catch (Exception e) { + System.out.println("Exception"); + } + } + + @Test + @DisplayName("Call authCommandReceived with valid input should return true") + void callAuthCommandReceivedWithValidInputShouldReturnTrue() { + boolean isPasswordSet = true; + boolean clientAuthenticated = false; + List inputList = List.of("AUTH", "password"); + boolean result = Main.authCommandReceived(isPasswordSet, inputList, clientAuthenticated); + assertThat(result).isTrue(); + } + + @Test + @DisplayName("Call AuthCommandReceived With Invalid Input Should Return False") + void callAuthCommandReceivedWithInvalidInputShouldReturnFalse() { + boolean isPasswordSet = true; + boolean clientAuthenticated = false; + List inputList = List.of("AUTHO", "password"); + boolean result = Main.authCommandReceived(isPasswordSet, inputList, clientAuthenticated); + assertThat(result).isFalse(); + } } From 18534d3ae76cc6ade8470bea2f0077ffd070a641 Mon Sep 17 00:00:00 2001 From: Cristoffer matlak Date: Mon, 5 Feb 2024 12:27:05 +0100 Subject: [PATCH 11/44] update pom.xml, removing redundant methods in test --- pom.xml | 7 +------ src/main/java/org/fungover/haze/Main.java | 5 ++--- src/test/java/org/fungover/haze/MainTest.java | 11 +++++++---- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/pom.xml b/pom.xml index cad19bdb..eb358369 100644 --- a/pom.xml +++ b/pom.xml @@ -26,12 +26,7 @@ 5.9.2 test - - org.mockito - mockito-core - 5.1.1 - test - + org.assertj assertj-core diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 6c03e3c2..96c341fb 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -80,7 +80,7 @@ private static void controlCommand(HazeList hazeList, HazeDatabase hazeDatabase, inputList.forEach(System.out::println); // For checking incoming message } - private static List getInputList(BufferedReader input) throws IOException { + public static List getInputList(BufferedReader input) throws IOException { List inputList = new ArrayList<>(); String firstReading = input.readLine(); @@ -188,8 +188,7 @@ private static void shutdownClientIfNotAuthenticated (Socket client,boolean clie } } - private static boolean authCommandReceived ( boolean isPasswordSet, List inputList, - boolean clientAuthenticated){ + public static boolean authCommandReceived ( boolean isPasswordSet, List inputList, boolean clientAuthenticated){ return isPasswordSet && !clientAuthenticated && inputList.size() == 2 && inputList.getFirst().equals("AUTH"); } } diff --git a/src/test/java/org/fungover/haze/MainTest.java b/src/test/java/org/fungover/haze/MainTest.java index 6beeb387..7ebab042 100644 --- a/src/test/java/org/fungover/haze/MainTest.java +++ b/src/test/java/org/fungover/haze/MainTest.java @@ -7,12 +7,15 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import java.io.BufferedReader; + +import java.io.StringReader; + import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; @@ -113,8 +116,6 @@ void callExecuteCommandWithLTRIMShouldReturnErrorMessageWhenKeyDoesNotExist() { - - @Test @DisplayName("getInputList Should Return List With Correct Data Based On Index") void getInputListShouldReturn(){ @@ -129,6 +130,8 @@ void getInputListShouldReturn(){ } } + + @Test @DisplayName("Call authCommandReceived with valid input should return true") void callAuthCommandReceivedWithValidInputShouldReturnTrue() { From b2a7f62b351d7185e7aec099bee943841d907c1a Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Mon, 5 Feb 2024 14:38:26 +0100 Subject: [PATCH 12/44] Add test for initializeServer method in main --- src/main/java/org/fungover/haze/Main.java | 114 +++++++++--------- src/test/java/org/fungover/haze/MainTest.java | 29 +++-- 2 files changed, 77 insertions(+), 66 deletions(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 96c341fb..9ebff478 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -124,73 +124,71 @@ public static String executeCommand(HazeDatabase hazeDatabase, List inpu } catch (IllegalArgumentException ex) { return "-ERR unknown command\r\n"; } - return commandSwitch (hazeDatabase, inputList, hazeList, commandEnum); - } - - - private static String commandSwitch (HazeDatabase hazeDatabase, List < String > inputList, HazeList - hazeList, Command commandEnum){ - return switch (commandEnum) { - case SET -> hazeDatabase.set(inputList); - case GET -> hazeDatabase.get(inputList); - case DEL -> hazeDatabase.delete(inputList.subList(1, inputList.size())); - case PING -> hazeDatabase.ping(inputList); - case SETNX -> hazeDatabase.setNX(inputList); - case EXISTS -> hazeDatabase.exists(inputList.subList(1, inputList.size())); - case SAVE -> SaveFile.writeOnFile(hazeDatabase.copy()); - case RPUSH -> hazeList.rPush(inputList); - case LPUSH -> hazeList.lPush(inputList); - case LPOP -> hazeList.callLPop(inputList); - case RPOP -> hazeList.callRPop(inputList); - case LLEN -> hazeList.lLen(inputList); - case LMOVE -> hazeList.lMove(inputList); - case LTRIM -> hazeList.callLtrim(inputList); - case AUTH -> "+OK\r\n"; - }; - } + return commandSwitch(hazeDatabase, inputList, hazeList, commandEnum); + } - private static void readInputStream (BufferedReader input, List < String > inputList, String firstReading) throws - IOException { - logger.debug("readInputStream: {} {} {}", () -> input, () -> inputList, () -> firstReading); - int size; - if (firstReading.startsWith("*")) { - size = Integer.parseInt(firstReading.substring(1)) * 2; - for (int i = 0; i < size; i++) { - String temp = input.readLine(); - if (!temp.contains("$")) - inputList.add(temp); - } - } else { - String[] seperated = firstReading.split("\\s"); - inputList.addAll(Arrays.asList(seperated)); + + private static String commandSwitch(HazeDatabase hazeDatabase, List inputList, HazeList + hazeList, Command commandEnum) { + return switch (commandEnum) { + case SET -> hazeDatabase.set(inputList); + case GET -> hazeDatabase.get(inputList); + case DEL -> hazeDatabase.delete(inputList.subList(1, inputList.size())); + case PING -> hazeDatabase.ping(inputList); + case SETNX -> hazeDatabase.setNX(inputList); + case EXISTS -> hazeDatabase.exists(inputList.subList(1, inputList.size())); + case SAVE -> SaveFile.writeOnFile(hazeDatabase.copy()); + case RPUSH -> hazeList.rPush(inputList); + case LPUSH -> hazeList.lPush(inputList); + case LPOP -> hazeList.callLPop(inputList); + case RPOP -> hazeList.callRPop(inputList); + case LLEN -> hazeList.lLen(inputList); + case LMOVE -> hazeList.lMove(inputList); + case LTRIM -> hazeList.callLtrim(inputList); + case AUTH -> "+OK\r\n"; + }; + } + + private static void readInputStream(BufferedReader input, List inputList, String firstReading) throws + IOException { + logger.debug("readInputStream: {} {} {}", () -> input, () -> inputList, () -> firstReading); + int size; + if (firstReading.startsWith("*")) { + size = Integer.parseInt(firstReading.substring(1)) * 2; + for (int i = 0; i < size; i++) { + String temp = input.readLine(); + if (!temp.contains("$")) + inputList.add(temp); } + } else { + String[] seperated = firstReading.split("\\s"); + inputList.addAll(Arrays.asList(seperated)); } + } - private static void initializeServer (String[]args, Initialize initialize, Auth auth){ - initialize.importCliOptions(args); - auth.setPassword(initialize.getPassword()); - } + public static void initializeServer(String[] args, Initialize initialize, Auth auth) { + initialize.importCliOptions(args); + auth.setPassword(initialize.getPassword()); + } - private static boolean authenticateClient (Auth auth,boolean isPasswordSet, Socket - client, List < String > inputList,boolean clientAuthenticated) throws IOException { - if (authCommandReceived(isPasswordSet, inputList, clientAuthenticated)) - return auth.authenticate(inputList.get(1), client); + private static boolean authenticateClient(Auth auth, boolean isPasswordSet, Socket client, List inputList, boolean clientAuthenticated) throws IOException { + if (authCommandReceived(isPasswordSet, inputList, clientAuthenticated)) + return auth.authenticate(inputList.get(1), client); - shutdownClientIfNotAuthenticated(client, clientAuthenticated, isPasswordSet); - return clientAuthenticated; - } + shutdownClientIfNotAuthenticated(client, clientAuthenticated, isPasswordSet); + return clientAuthenticated; + } - private static void shutdownClientIfNotAuthenticated (Socket client,boolean clientAuthenticated, - boolean isPasswordSet) throws IOException { - if (!clientAuthenticated && isPasswordSet) { - client.getOutputStream().write(Auth.printAuthError()); - client.shutdownOutput(); - } + public static void shutdownClientIfNotAuthenticated(Socket client, boolean clientAuthenticated, boolean isPasswordSet) throws IOException { + if (!clientAuthenticated && isPasswordSet) { + client.getOutputStream().write(Auth.printAuthError()); + client.shutdownOutput(); } + } - public static boolean authCommandReceived ( boolean isPasswordSet, List inputList, boolean clientAuthenticated){ - return isPasswordSet && !clientAuthenticated && inputList.size() == 2 && inputList.getFirst().equals("AUTH"); - } + public static boolean authCommandReceived(boolean isPasswordSet, List inputList, boolean clientAuthenticated) { + return isPasswordSet && !clientAuthenticated && inputList.size() == 2 && inputList.getFirst().equals("AUTH"); } +} diff --git a/src/test/java/org/fungover/haze/MainTest.java b/src/test/java/org/fungover/haze/MainTest.java index 7ebab042..dabac9e2 100644 --- a/src/test/java/org/fungover/haze/MainTest.java +++ b/src/test/java/org/fungover/haze/MainTest.java @@ -1,29 +1,28 @@ package org.fungover.haze; - - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; - +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; import java.io.BufferedReader; - import java.io.StringReader; - import java.util.List; - - import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; - class MainTest { + + + HazeDatabase database = new HazeDatabase(); HazeList hazeList = new HazeList(database); + + @Test void callingExecuteCommandWithValidNonExistingInputReturnsColonOne() { assertThat(Main.executeCommand(database, List.of("SETNX", "1", "This is a value"), hazeList)).isEqualTo(":1\r\n"); @@ -151,4 +150,18 @@ void callAuthCommandReceivedWithInvalidInputShouldReturnFalse() { boolean result = Main.authCommandReceived(isPasswordSet, inputList, clientAuthenticated); assertThat(result).isFalse(); } + + @Test + void callToInitializeServerShouldSetPasswordToAuth(){ + String[] testArgs = {"arg1", "arg2"}; + Initialize initialize = new Initialize(); + Auth auth = new Auth(); + Main.initializeServer(testArgs, initialize, auth); + assertThat(auth.isPasswordSet()).isTrue(); + } + + + + + } From ba80c925ba435c048897603babc475b26fe1af52 Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Mon, 5 Feb 2024 15:11:52 +0100 Subject: [PATCH 13/44] Add test for shutDownClientIfNotAuthenticated in main class --- src/main/java/org/fungover/haze/Main.java | 7 --- src/test/java/org/fungover/haze/MainTest.java | 47 +++++++++++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 9ebff478..2afd5f75 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -1,8 +1,6 @@ package org.fungover.haze; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -12,22 +10,17 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import java.util.Optional; - public class Main { static boolean serverOpen = true; static Logger logger = LogManager.getLogger(Main.class); public static void main(String[] args) { - Initialize initialize = Initialize.getInitialize(args); - HazeDatabase hazeDatabase = new HazeDatabase(); HazeList hazeList = new HazeList(hazeDatabase); Auth auth = new Auth(); initializeServer(args, initialize, auth); final boolean isPasswordSet = auth.isPasswordSet(); - addHook(hazeDatabase); try (ServerSocket serverSocket = new ServerSocket()) { initSocket(initialize, serverSocket); diff --git a/src/test/java/org/fungover/haze/MainTest.java b/src/test/java/org/fungover/haze/MainTest.java index dabac9e2..fe4907a2 100644 --- a/src/test/java/org/fungover/haze/MainTest.java +++ b/src/test/java/org/fungover/haze/MainTest.java @@ -1,4 +1,5 @@ package org.fungover.haze; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -9,14 +10,30 @@ import org.mockito.MockitoAnnotations; import java.io.BufferedReader; +import java.io.IOException; import java.io.StringReader; +import java.net.ServerSocket; +import java.net.Socket; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; class MainTest { + private ServerSocket serverSocket; + private Socket clientSocket; + @BeforeEach + void setUp() throws IOException { + serverSocket = new ServerSocket(0); + clientSocket = new Socket("localhost", serverSocket.getLocalPort()); + } + + @AfterEach + void tearDown() throws IOException { + serverSocket.close(); + clientSocket.close(); + } HazeDatabase database = new HazeDatabase(); HazeList hazeList = new HazeList(database); @@ -151,6 +168,16 @@ void callAuthCommandReceivedWithInvalidInputShouldReturnFalse() { assertThat(result).isFalse(); } + @Test + @DisplayName("Call AuthCommandReceived With Invalid Password Should Return False") + void callAuthCommandReceivedWithInvalidPasswordShouldReturnFalse() { + boolean isPasswordSet = false; + boolean clientAuthenticated = false; + List inputList = List.of("AUTH", "password"); + boolean result = Main.authCommandReceived(isPasswordSet, inputList, clientAuthenticated); + assertThat(result).isFalse(); + } + @Test void callToInitializeServerShouldSetPasswordToAuth(){ String[] testArgs = {"arg1", "arg2"}; @@ -160,6 +187,26 @@ void callToInitializeServerShouldSetPasswordToAuth(){ assertThat(auth.isPasswordSet()).isTrue(); } + @Test + @DisplayName("Call to shutdownClientIfNotAuthenticated should shut down output for non authenticated user") + void callToShutDownClientIfNotAuthenticatedShouldShutDownOutputForNonAuthenticatedUser() throws IOException { + boolean clientAuthenticated = false; + boolean isPasswordSet = true; + Main.shutdownClientIfNotAuthenticated(clientSocket, clientAuthenticated, isPasswordSet); + assertThat(clientSocket.isOutputShutdown()).isEqualTo(true); + } + + @Test + @DisplayName("Call to shutdownClientIfNotAuthenticated should not shut down output for authenticated user") + void callToShutDownClientIfNotAuthenticatedShouldNotShutDownOutputForAuthenticatedUser() throws IOException { + boolean clientAuthenticated = true; + boolean isPasswordSet = true; + Main.shutdownClientIfNotAuthenticated(clientSocket, clientAuthenticated, isPasswordSet); + assertThat(clientSocket.isOutputShutdown()).isEqualTo(false); + } + + + From 00dd4b8e42092ce84a4b9ac91179d5b23bc716b2 Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Mon, 5 Feb 2024 15:56:52 +0100 Subject: [PATCH 14/44] Add test for initSocket method in main --- src/main/java/org/fungover/haze/Main.java | 6 ++--- src/test/java/org/fungover/haze/MainTest.java | 22 +++++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 2afd5f75..77332abe 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -35,7 +35,6 @@ private static void whileServerOpen(HazeList hazeList, HazeDatabase hazeDatabase while (serverOpen) { var client = serverSocket.accept(); logger.info("Application started: serverSocket.accept()"); - runThread(hazeList, hazeDatabase, auth, isPasswordSet, client); } } @@ -63,7 +62,6 @@ private static void createThread(HazeList hazeList, HazeDatabase hazeDatabase, A private static void handleThread(HazeList hazeList, HazeDatabase hazeDatabase, Socket client, List inputList) throws IOException { controlCommand(hazeList, hazeDatabase, client, inputList); printThreadDebug(); - inputList.clear(); } @@ -81,7 +79,7 @@ public static List getInputList(BufferedReader input) throws IOException return inputList; } - private static void initSocket(Initialize initialize, ServerSocket serverSocket) throws IOException { + public static void initSocket(Initialize initialize, ServerSocket serverSocket) throws IOException { serverSocket.setReuseAddress(true); serverSocket.bind(new InetSocketAddress(initialize.getPort())); } @@ -164,7 +162,7 @@ public static void initializeServer(String[] args, Initialize initialize, Auth a auth.setPassword(initialize.getPassword()); } - private static boolean authenticateClient(Auth auth, boolean isPasswordSet, Socket client, List inputList, boolean clientAuthenticated) throws IOException { + public static boolean authenticateClient(Auth auth, boolean isPasswordSet, Socket client, List inputList, boolean clientAuthenticated) throws IOException { if (authCommandReceived(isPasswordSet, inputList, clientAuthenticated)) return auth.authenticate(inputList.get(1), client); diff --git a/src/test/java/org/fungover/haze/MainTest.java b/src/test/java/org/fungover/haze/MainTest.java index fe4907a2..2f500994 100644 --- a/src/test/java/org/fungover/haze/MainTest.java +++ b/src/test/java/org/fungover/haze/MainTest.java @@ -1,4 +1,5 @@ package org.fungover.haze; +import org.apache.logging.log4j.core.jmx.Server; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -12,10 +13,12 @@ import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; +import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.in; import static org.mockito.Mockito.*; class MainTest { @@ -205,6 +208,25 @@ void callToShutDownClientIfNotAuthenticatedShouldNotShutDownOutputForAuthenticat assertThat(clientSocket.isOutputShutdown()).isEqualTo(false); } + @Test + @DisplayName("Call to initSocket should set reuseAddress to true") + void callToInitSocketShouldSetReuseAddressToTrue() throws IOException { + Initialize initialize = new Initialize(); + ServerSocket ss = new ServerSocket(); + Main.initSocket(initialize, ss); + assertThat(ss.getReuseAddress()).isTrue(); + } + + @Test + @DisplayName("Call to initSocket should bind serversocket port to same as initialize") + void callToInitSocketShouldBindServerSocketPortToSameAsInitialize() throws IOException { + Initialize initialize = new Initialize(); + ServerSocket ss = new ServerSocket(); + Main.initSocket(initialize, ss); + int initializePort = initialize.getPort(); + int serverSocketPort = ss.getLocalPort(); + assertThat(initializePort).isEqualTo(serverSocketPort); + } From f254836fc382cedc594e6a4f4ceeb6a0ae5166b7 Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Mon, 5 Feb 2024 16:39:32 +0100 Subject: [PATCH 15/44] Adjustment for test for initSocket method in main --- src/main/java/org/fungover/haze/Main.java | 6 ++++-- src/test/java/org/fungover/haze/MainTest.java | 21 +++++++------------ 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 77332abe..465f1d43 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -1,6 +1,8 @@ package org.fungover.haze; + import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -10,6 +12,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; + public class Main { static boolean serverOpen = true; static Logger logger = LogManager.getLogger(Main.class); @@ -67,7 +70,6 @@ private static void handleThread(HazeList hazeList, HazeDatabase hazeDatabase, S private static void controlCommand(HazeList hazeList, HazeDatabase hazeDatabase, Socket client, List inputList) throws IOException { client.getOutputStream().write(executeCommand(hazeDatabase, inputList, hazeList).getBytes()); - inputList.forEach(System.out::println); // For checking incoming message } @@ -140,7 +142,7 @@ private static String commandSwitch(HazeDatabase hazeDatabase, List inpu }; } - private static void readInputStream(BufferedReader input, List inputList, String firstReading) throws + public static void readInputStream(BufferedReader input, List inputList, String firstReading) throws IOException { logger.debug("readInputStream: {} {} {}", () -> input, () -> inputList, () -> firstReading); int size; diff --git a/src/test/java/org/fungover/haze/MainTest.java b/src/test/java/org/fungover/haze/MainTest.java index 2f500994..33a9f5de 100644 --- a/src/test/java/org/fungover/haze/MainTest.java +++ b/src/test/java/org/fungover/haze/MainTest.java @@ -16,6 +16,8 @@ import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; +import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.in; @@ -208,29 +210,20 @@ void callToShutDownClientIfNotAuthenticatedShouldNotShutDownOutputForAuthenticat assertThat(clientSocket.isOutputShutdown()).isEqualTo(false); } - @Test - @DisplayName("Call to initSocket should set reuseAddress to true") - void callToInitSocketShouldSetReuseAddressToTrue() throws IOException { - Initialize initialize = new Initialize(); - ServerSocket ss = new ServerSocket(); - Main.initSocket(initialize, ss); - assertThat(ss.getReuseAddress()).isTrue(); - } @Test @DisplayName("Call to initSocket should bind serversocket port to same as initialize") void callToInitSocketShouldBindServerSocketPortToSameAsInitialize() throws IOException { Initialize initialize = new Initialize(); ServerSocket ss = new ServerSocket(); - Main.initSocket(initialize, ss); int initializePort = initialize.getPort(); int serverSocketPort = ss.getLocalPort(); + assertThat(initializePort).isNotEqualTo(serverSocketPort); + + Main.initSocket(initialize, ss); + initializePort = initialize.getPort(); + serverSocketPort = ss.getLocalPort(); assertThat(initializePort).isEqualTo(serverSocketPort); } - - - - - } From eed3f8325c998caa23dcc20c8c2816ac2db0dd6c Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Tue, 6 Feb 2024 08:59:00 +0100 Subject: [PATCH 16/44] Add code + tests for Lindex method --- src/main/java/org/fungover/haze/Command.java | 2 +- .../java/org/fungover/haze/HazeDatabase.java | 17 ++++++++++++++ src/main/java/org/fungover/haze/Main.java | 1 + .../org/fungover/haze/HazeDatabaseTest.java | 23 +++++++++++++++++++ 4 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/fungover/haze/Command.java b/src/main/java/org/fungover/haze/Command.java index 43e3e166..b4ac7c5b 100644 --- a/src/main/java/org/fungover/haze/Command.java +++ b/src/main/java/org/fungover/haze/Command.java @@ -1,5 +1,5 @@ package org.fungover.haze; public enum Command { - SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH + SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH, INDEX } diff --git a/src/main/java/org/fungover/haze/HazeDatabase.java b/src/main/java/org/fungover/haze/HazeDatabase.java index 75f6bcbf..17621983 100644 --- a/src/main/java/org/fungover/haze/HazeDatabase.java +++ b/src/main/java/org/fungover/haze/HazeDatabase.java @@ -1,5 +1,6 @@ package org.fungover.haze; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -143,4 +144,20 @@ public void addValue(String key, String value) { lock.unlock(); } } + + + public String getIndex(List inputList){ + if (inputList.size() != 2) + return ARGUMENT_ERROR; + String key = inputList.get(1); + lock.lock(); + List keys = new ArrayList<>(database.values()); + try{ + if(keys.contains(key)){ + return "$" + keys.indexOf(key) + "\r\n"; + } else return "$-1\r\n"; + } finally { + lock.unlock(); + } + } } diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 465f1d43..b907446e 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -138,6 +138,7 @@ private static String commandSwitch(HazeDatabase hazeDatabase, List inpu case LLEN -> hazeList.lLen(inputList); case LMOVE -> hazeList.lMove(inputList); case LTRIM -> hazeList.callLtrim(inputList); + case INDEX -> hazeDatabase.getIndex(inputList); case AUTH -> "+OK\r\n"; }; } diff --git a/src/test/java/org/fungover/haze/HazeDatabaseTest.java b/src/test/java/org/fungover/haze/HazeDatabaseTest.java index 89e1122a..4c638e4c 100644 --- a/src/test/java/org/fungover/haze/HazeDatabaseTest.java +++ b/src/test/java/org/fungover/haze/HazeDatabaseTest.java @@ -159,5 +159,28 @@ void shouldShouldReturnTrue(){ assertThat(testDatabase.containsKey("key1")).isTrue(); } + @Test + void callingGetIndexOfWithInvalidKeyReturnMinusOne(){ + testDatabase.addValue("key1", "hej"); + testDatabase.addValue("key2", "bonjour"); + + assertThat(testDatabase.getIndex(List.of("INDEX", "hello"))).isEqualTo("$-1\r\n"); + } + + @Test + void callingGetIndexOfWithValidKeyReturnIndex() { + testDatabase.addValue("key1", "hej"); + testDatabase.addValue("key2", "bonjour"); + testDatabase.addValue("key3", "hello"); + assertThat(testDatabase.getIndex(List.of("INDEX", "hello"))).isEqualTo("$2\r\n"); + } + + @Test + void callingIndexOfWithInvalidArgumentsReturnErrorMessage() { + testDatabase.addValue("key1", "hej"); + testDatabase.addValue("key2", "bonjour"); + testDatabase.addValue("key3", "hello"); + assertThat(testDatabase.getIndex(List.of( "hello"))).isEqualTo("-ERR wrong number of arguments for command\r\n"); + } } From 39601f705f25615115585eb11a35c3273d026863 Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Tue, 6 Feb 2024 19:24:53 +0100 Subject: [PATCH 17/44] Move lindex method to listclass, add test for it --- src/main/java/org/fungover/haze/Command.java | 2 +- .../java/org/fungover/haze/HazeDatabase.java | 16 ----------- src/main/java/org/fungover/haze/HazeList.java | 27 +++++++++++++++++++ src/main/java/org/fungover/haze/Main.java | 2 +- .../org/fungover/haze/HazeDatabaseTest.java | 23 ---------------- .../java/org/fungover/haze/HazeListTest.java | 27 +++++++++++++++++++ 6 files changed, 56 insertions(+), 41 deletions(-) diff --git a/src/main/java/org/fungover/haze/Command.java b/src/main/java/org/fungover/haze/Command.java index b4ac7c5b..4ab83cb3 100644 --- a/src/main/java/org/fungover/haze/Command.java +++ b/src/main/java/org/fungover/haze/Command.java @@ -1,5 +1,5 @@ package org.fungover.haze; public enum Command { - SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH, INDEX + SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH, LINDEX } diff --git a/src/main/java/org/fungover/haze/HazeDatabase.java b/src/main/java/org/fungover/haze/HazeDatabase.java index 17621983..af67a402 100644 --- a/src/main/java/org/fungover/haze/HazeDatabase.java +++ b/src/main/java/org/fungover/haze/HazeDatabase.java @@ -144,20 +144,4 @@ public void addValue(String key, String value) { lock.unlock(); } } - - - public String getIndex(List inputList){ - if (inputList.size() != 2) - return ARGUMENT_ERROR; - String key = inputList.get(1); - lock.lock(); - List keys = new ArrayList<>(database.values()); - try{ - if(keys.contains(key)){ - return "$" + keys.indexOf(key) + "\r\n"; - } else return "$-1\r\n"; - } finally { - lock.unlock(); - } - } } diff --git a/src/main/java/org/fungover/haze/HazeList.java b/src/main/java/org/fungover/haze/HazeList.java index 00470985..41ded3ac 100644 --- a/src/main/java/org/fungover/haze/HazeList.java +++ b/src/main/java/org/fungover/haze/HazeList.java @@ -264,6 +264,33 @@ public static String listValueAsString(List list) { return String.join("\r\n", list); } + public String lIndex(List inputList){ + String key = getKey(inputList); + int index; + if (!hazeDatabase.containsKey(key)) + return "Could not find list"; + String indexStr = inputList.get(2); + + try { + index = Integer.parseInt(indexStr); + } catch (NumberFormatException e) { + return "-ERR invalid index\r\n"; + } + + List data = getValueAsList(hazeDatabase.getValue(key)); + if(data.size()-1 inputList) { String key = null; if (inputList.size() > 1) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index b907446e..85d74392 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -138,7 +138,7 @@ private static String commandSwitch(HazeDatabase hazeDatabase, List inpu case LLEN -> hazeList.lLen(inputList); case LMOVE -> hazeList.lMove(inputList); case LTRIM -> hazeList.callLtrim(inputList); - case INDEX -> hazeDatabase.getIndex(inputList); + case LINDEX -> hazeList.lIndex(inputList); case AUTH -> "+OK\r\n"; }; } diff --git a/src/test/java/org/fungover/haze/HazeDatabaseTest.java b/src/test/java/org/fungover/haze/HazeDatabaseTest.java index 4c638e4c..89e1122a 100644 --- a/src/test/java/org/fungover/haze/HazeDatabaseTest.java +++ b/src/test/java/org/fungover/haze/HazeDatabaseTest.java @@ -159,28 +159,5 @@ void shouldShouldReturnTrue(){ assertThat(testDatabase.containsKey("key1")).isTrue(); } - @Test - void callingGetIndexOfWithInvalidKeyReturnMinusOne(){ - testDatabase.addValue("key1", "hej"); - testDatabase.addValue("key2", "bonjour"); - - assertThat(testDatabase.getIndex(List.of("INDEX", "hello"))).isEqualTo("$-1\r\n"); - } - - @Test - void callingGetIndexOfWithValidKeyReturnIndex() { - testDatabase.addValue("key1", "hej"); - testDatabase.addValue("key2", "bonjour"); - testDatabase.addValue("key3", "hello"); - assertThat(testDatabase.getIndex(List.of("INDEX", "hello"))).isEqualTo("$2\r\n"); - } - - @Test - void callingIndexOfWithInvalidArgumentsReturnErrorMessage() { - testDatabase.addValue("key1", "hej"); - testDatabase.addValue("key2", "bonjour"); - testDatabase.addValue("key3", "hello"); - assertThat(testDatabase.getIndex(List.of( "hello"))).isEqualTo("-ERR wrong number of arguments for command\r\n"); - } } diff --git a/src/test/java/org/fungover/haze/HazeListTest.java b/src/test/java/org/fungover/haze/HazeListTest.java index 50f0190f..b90cdbf9 100644 --- a/src/test/java/org/fungover/haze/HazeListTest.java +++ b/src/test/java/org/fungover/haze/HazeListTest.java @@ -1,6 +1,8 @@ package org.fungover.haze; import org.junit.jupiter.api.Test; import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; class HazeListTest { @@ -287,4 +289,29 @@ void CallLReturnCorrectErrorMessageWhenNotGivenNumbersAsArguments () { void parserWithBadInputShouldReturnZero(){ assertEquals(0, HazeList.parser("This is not a number")); } + + + @Test + void callingLindexWithValidPositiveIndexReturnValue(){ + hazeList.rPush(List.of("", "key2", "val1", "val2", "val3")); + assertThat(hazeList.lIndex(List.of("", "key2", "2"))).isEqualTo("$4\r\nval3\r\n"); + } + + @Test + void callingLindexWithIndexOutOfBoundsReturnNil(){ + hazeList.rPush(List.of("", "key2", "val1", "val2", "val3")); + assertThat(hazeList.lIndex(List.of("", "key2", "3"))).isEqualTo("$5\r\n(nil)\r\n"); + } + + @Test + void callingLindexWithValidNegativeIndexReturnValue(){ + hazeList.rPush(List.of("", "key2", "val1", "val2", "val3")); + assertThat(hazeList.lIndex(List.of("", "key2", "-2"))).isEqualTo("$4\r\nval2\r\n"); + } + + @Test + void callingLindexWithValidIndexZeroReturnFirstValue(){ + hazeList.rPush(List.of("", "key2", "val1", "val2", "val3")); + assertThat(hazeList.lIndex(List.of("", "key2", "0"))).isEqualTo("$4\r\nval1\r\n"); + } } From e357dfbb8d5470da57bc9d0f1bf6972c864e082e Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Tue, 6 Feb 2024 21:39:02 +0100 Subject: [PATCH 18/44] add integrations test for lIndex --- src/main/java/org/fungover/haze/Main.java | 1 + .../java/org/fungover/haze/HazeListTest.java | 2 +- .../org/fungover/haze/integration/HazeIT.java | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 500e27d3..35431058 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -120,6 +120,7 @@ public static String executeCommand(HazeDatabase hazeDatabase, List inpu case LLEN -> hazeList.lLen(inputList); case LMOVE -> hazeList.lMove(inputList); case LTRIM -> hazeList.callLtrim(inputList); + case LINDEX -> hazeList.lIndex(inputList); case AUTH -> "+OK\r\n"; }; diff --git a/src/test/java/org/fungover/haze/HazeListTest.java b/src/test/java/org/fungover/haze/HazeListTest.java index b90cdbf9..99f958fd 100644 --- a/src/test/java/org/fungover/haze/HazeListTest.java +++ b/src/test/java/org/fungover/haze/HazeListTest.java @@ -306,7 +306,7 @@ void callingLindexWithIndexOutOfBoundsReturnNil(){ @Test void callingLindexWithValidNegativeIndexReturnValue(){ hazeList.rPush(List.of("", "key2", "val1", "val2", "val3")); - assertThat(hazeList.lIndex(List.of("", "key2", "-2"))).isEqualTo("$4\r\nval2\r\n"); + assertThat(hazeList.lIndex(List.of("", "key2", "-1"))).isEqualTo("$4\r\nval3\r\n"); } @Test diff --git a/src/test/java/org/fungover/haze/integration/HazeIT.java b/src/test/java/org/fungover/haze/integration/HazeIT.java index c5bae8b0..b27a893e 100644 --- a/src/test/java/org/fungover/haze/integration/HazeIT.java +++ b/src/test/java/org/fungover/haze/integration/HazeIT.java @@ -6,6 +6,8 @@ import redis.clients.jedis.Protocol; import redis.clients.jedis.util.SafeEncoder; +import java.util.List; + import static org.assertj.core.api.Assertions.assertThat; @ExtendWith(HazeExtension.class) @@ -84,6 +86,20 @@ void listKeyWithMultipleValues() { assertThat(pool.rpush("test", "fifth", "sixth")).isEqualTo(6); assertThat(pool.llen("test")).isEqualTo(6); + pool.del("test"); + assertThat(pool.exists("right")).isFalse(); + } + + @Test + void lindexReturnCorrectIndex() { + assertThat(pool.rpush("test", "hello")).isEqualTo(1); + assertThat(pool.rpush("test", "hey")).isEqualTo(2); + assertThat(pool.rpush("test", "bonjour")).isEqualTo(3); + assertThat(pool.rpush("test", "hej")).isEqualTo(4); + assertThat(pool.lindex("test", 0)).isEqualTo("hello"); + assertThat(pool.lindex("test", -1)).isEqualTo("hej"); + + pool.del("test"); assertThat(pool.exists("right")).isFalse(); } From 8aca35d730d7aca5a6145e5f3aaf9acc5d7d2b18 Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Tue, 6 Feb 2024 22:12:02 +0100 Subject: [PATCH 19/44] Add latest yml files --- .github/workflows/maven.yml | 9 +++------ .github/workflows/release.yml | 9 +++------ .github/workflows/sonar.yml | 10 +++------- src/main/java/org/fungover/haze/Initialize.java | 5 ----- 4 files changed, 9 insertions(+), 24 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 01a2196e..8b2b364d 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -21,16 +21,13 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v3 - name: Get Java Version run: | Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - - - name: Set up JDK ${{env.Java_Version}} - - - uses: actions/setup-java@v4 + - name: Set up JDK 19 + uses: actions/setup-java@v3 with: java-version: ${{ env.Java_Version }} distribution: 'temurin' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e9eb87c7..b0963335 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,16 +13,13 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@v3 - name: Get Java Version run: | Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - - - name: Set up ${{env.Java_Version}} - - - uses: actions/setup-java@v4 + - name: Set up JDK 19 + uses: actions/setup-java@v3 with: java-version: ${{ env.Java_Version }} distribution: 'temurin' diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index b4b7b5d7..7760bdd0 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -10,19 +10,15 @@ jobs: name: Build and analyze runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v3 with: fetch-depth: 0 # Shallow clones should be disabled for a better relevancy of analysis - name: Get Java Version run: | Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - - - name: Set up ${{env.Java_Version}} - - - - uses: actions/setup-java@v4 + - name: Set up JDK 19 + uses: actions/setup-java@v3 with: java-version: ${{ env.Java_Version }} distribution: 'temurin' diff --git a/src/main/java/org/fungover/haze/Initialize.java b/src/main/java/org/fungover/haze/Initialize.java index 22aecedb..8e660a5c 100644 --- a/src/main/java/org/fungover/haze/Initialize.java +++ b/src/main/java/org/fungover/haze/Initialize.java @@ -41,10 +41,5 @@ public String getPassword() { public void clearCliOptions() { cliOptions.clear(); } - public static Initialize getInitialize(String[] args) { - Initialize initialize = new Initialize(); - initialize.importCliOptions(args); - return initialize; - } } From 9d3d255e951b25ec58a566db50d5a3e4ad99c1c7 Mon Sep 17 00:00:00 2001 From: Trung Ma Date: Wed, 7 Feb 2024 10:56:01 +0100 Subject: [PATCH 20/44] Added some more argumentexceptions --- src/main/java/org/fungover/haze/HazeDatabase.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/main/java/org/fungover/haze/HazeDatabase.java b/src/main/java/org/fungover/haze/HazeDatabase.java index 75f6bcbf..18fc5b81 100644 --- a/src/main/java/org/fungover/haze/HazeDatabase.java +++ b/src/main/java/org/fungover/haze/HazeDatabase.java @@ -46,6 +46,9 @@ public String get(List inputList) { } public String delete(List keys) { + if (keys.isEmpty()) + throw new IllegalArgumentException("No keys provided"); + var counter = new AtomicInteger(0); lock.lock(); try { @@ -62,6 +65,9 @@ public String delete(List keys) { } public String exists(List keys) { + if (keys.isEmpty()) + throw new IllegalArgumentException("No keys provided"); + lock.lock(); int numberOfKeys = 0; try { @@ -109,6 +115,12 @@ public Map copy() { } public String ping(List messageList) { + if (messageList == null || messageList.isEmpty()) { + throw new IllegalArgumentException("No message provided"); + } else if (messageList.size() > 2) { + throw new IllegalArgumentException("Too many arguments for PING command"); + } + if (messageList.size() == 1) return "+PONG\r\n"; else return "$" + (messageList.get(1)).length() + "\r\n" + messageList.get(1) + "\r\n"; From fb8e36f7ea5f37d2972b3d8374a63494d20681aa Mon Sep 17 00:00:00 2001 From: Trung Ma Date: Wed, 7 Feb 2024 12:35:54 +0100 Subject: [PATCH 21/44] Changed the return value in exist method #135 --- src/main/java/org/fungover/haze/HazeDatabase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/fungover/haze/HazeDatabase.java b/src/main/java/org/fungover/haze/HazeDatabase.java index 18fc5b81..ac73c9f0 100644 --- a/src/main/java/org/fungover/haze/HazeDatabase.java +++ b/src/main/java/org/fungover/haze/HazeDatabase.java @@ -66,7 +66,7 @@ public String delete(List keys) { public String exists(List keys) { if (keys.isEmpty()) - throw new IllegalArgumentException("No keys provided"); + return ":0\r\n"; lock.lock(); int numberOfKeys = 0; From 89dc7e3d1633bd810f6c81b38ccdd2f218c3b8ac Mon Sep 17 00:00:00 2001 From: Mats Kruskopf Eriksson Date: Wed, 7 Feb 2024 14:40:31 +0100 Subject: [PATCH 22/44] add increase method with command INCR --- src/main/java/org/fungover/haze/Command.java | 2 +- .../java/org/fungover/haze/HazeDatabase.java | 22 +++++++++++++++++++ src/main/java/org/fungover/haze/Main.java | 2 +- .../org/fungover/haze/HazeDatabaseTest.java | 17 ++++++++++++++ src/test/java/org/fungover/haze/MainTest.java | 7 ++++++ 5 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/fungover/haze/Command.java b/src/main/java/org/fungover/haze/Command.java index 43e3e166..9ecd560a 100644 --- a/src/main/java/org/fungover/haze/Command.java +++ b/src/main/java/org/fungover/haze/Command.java @@ -1,5 +1,5 @@ package org.fungover.haze; public enum Command { - SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH + SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH, INCR } diff --git a/src/main/java/org/fungover/haze/HazeDatabase.java b/src/main/java/org/fungover/haze/HazeDatabase.java index 75f6bcbf..45e6d5b7 100644 --- a/src/main/java/org/fungover/haze/HazeDatabase.java +++ b/src/main/java/org/fungover/haze/HazeDatabase.java @@ -143,4 +143,26 @@ public void addValue(String key, String value) { lock.unlock(); } } + + public String increaseValue(List inputList) { + lock.lock(); + String key = inputList.get(1); + try { + if (!database.containsKey(key)) { + return "-ERR no such key\r\n"; + } + String value = database.get(key); + try { + long longValue = Long.parseLong(value); + longValue++; + database.put(key, String.valueOf(longValue)); + return ":" + longValue + "\r\n"; + } catch (NumberFormatException e) { + return "-WRONGTYPE value is not an integer or out of range\r\n"; + } + } finally { + lock.unlock(); + } + } + } diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 500e27d3..8945aa5e 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -121,7 +121,7 @@ public static String executeCommand(HazeDatabase hazeDatabase, List inpu case LMOVE -> hazeList.lMove(inputList); case LTRIM -> hazeList.callLtrim(inputList); case AUTH -> "+OK\r\n"; - + case INCR -> hazeDatabase.increaseValue(inputList); }; } diff --git a/src/test/java/org/fungover/haze/HazeDatabaseTest.java b/src/test/java/org/fungover/haze/HazeDatabaseTest.java index 89e1122a..650fc3d3 100644 --- a/src/test/java/org/fungover/haze/HazeDatabaseTest.java +++ b/src/test/java/org/fungover/haze/HazeDatabaseTest.java @@ -1,5 +1,6 @@ package org.fungover.haze; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Arrays; @@ -159,5 +160,21 @@ void shouldShouldReturnTrue(){ assertThat(testDatabase.containsKey("key1")).isTrue(); } + @Test + void callingIncreaseWithKeyWithIntegerShouldIncreaseValueBy1(){ + testDatabase.addValue("key1", "1"); + + String increaseResult = testDatabase.increaseValue(List.of("INCR","key1")); + assertThat(increaseResult).isEqualTo(":2\r\n"); + assertThat(testDatabase.getValue("key1")).isEqualTo("2"); + + } + + @Test + void callingIncreaseWithKeyThatDoesNotContainIntegerShouldReturnErrorMessage() { + testDatabase.addValue("key1", "Gunnar"); + String increaseResult = testDatabase.increaseValue(List.of("INCR","key1")); + assertThat(increaseResult).isEqualTo("-WRONGTYPE value is not an integer or out of range\r\n"); + } } diff --git a/src/test/java/org/fungover/haze/MainTest.java b/src/test/java/org/fungover/haze/MainTest.java index 4e9c2c29..3199558a 100644 --- a/src/test/java/org/fungover/haze/MainTest.java +++ b/src/test/java/org/fungover/haze/MainTest.java @@ -1,5 +1,6 @@ package org.fungover.haze; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -108,6 +109,12 @@ void callExecuteCommandWithLTRIMShouldReturnErrorMessageWhenKeyDoesNotExist() { assertThat(Main.executeCommand(database, List.of("LTRIM", "key", "2", "3"), hazeList)).isEqualTo("-The key is not present in the database.\r\n"); } + @Test + void callExecuteCommandWithIncrShouldIncreaseTheValueOfTheKeyBy1() { + Main.executeCommand(database, List.of("SET", "key1", "1"), hazeList); + assertThat(Main.executeCommand(database, List.of("INCR", "key1"), hazeList)).isEqualTo(":2\r\n"); + } + @Test void testPrintThreadDebug() { ByteArrayOutputStream outContent = new ByteArrayOutputStream(); From be8c2da7e1d880614b81e6e7299d211f7cfd689f Mon Sep 17 00:00:00 2001 From: Mats Kruskopf Eriksson Date: Wed, 7 Feb 2024 14:44:41 +0100 Subject: [PATCH 23/44] add decrease method with command DECR --- src/main/java/org/fungover/haze/Command.java | 2 +- .../java/org/fungover/haze/HazeDatabase.java | 21 +++++++++++++++++++ src/main/java/org/fungover/haze/Main.java | 1 + .../org/fungover/haze/HazeDatabaseTest.java | 11 +++++++++- src/test/java/org/fungover/haze/MainTest.java | 7 ++++++- 5 files changed, 39 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/fungover/haze/Command.java b/src/main/java/org/fungover/haze/Command.java index 9ecd560a..79dea119 100644 --- a/src/main/java/org/fungover/haze/Command.java +++ b/src/main/java/org/fungover/haze/Command.java @@ -1,5 +1,5 @@ package org.fungover.haze; public enum Command { - SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH, INCR + SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH, INCR, DECR } diff --git a/src/main/java/org/fungover/haze/HazeDatabase.java b/src/main/java/org/fungover/haze/HazeDatabase.java index 45e6d5b7..a62034ea 100644 --- a/src/main/java/org/fungover/haze/HazeDatabase.java +++ b/src/main/java/org/fungover/haze/HazeDatabase.java @@ -165,4 +165,25 @@ public String increaseValue(List inputList) { } } + public String decreaseValue(List inputList) { + lock.lock(); + String key = inputList.get(1); + try { + if (!database.containsKey(key)) { + return "-ERR no such key\r\n"; + } + String value = database.get(key); + try { + long longValue = Long.parseLong(value); + longValue--; + database.put(key, String.valueOf(longValue)); + return ":" + longValue + "\r\n"; + } catch (NumberFormatException e) { + return "-WRONGTYPE value is not an integer or out of range\r\n"; + } + } finally { + lock.unlock(); + } + } + } diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 8945aa5e..3caf40e6 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -122,6 +122,7 @@ public static String executeCommand(HazeDatabase hazeDatabase, List inpu case LTRIM -> hazeList.callLtrim(inputList); case AUTH -> "+OK\r\n"; case INCR -> hazeDatabase.increaseValue(inputList); + case DECR -> hazeDatabase.decreaseValue(inputList); }; } diff --git a/src/test/java/org/fungover/haze/HazeDatabaseTest.java b/src/test/java/org/fungover/haze/HazeDatabaseTest.java index 650fc3d3..46e4aa2b 100644 --- a/src/test/java/org/fungover/haze/HazeDatabaseTest.java +++ b/src/test/java/org/fungover/haze/HazeDatabaseTest.java @@ -1,6 +1,5 @@ package org.fungover.haze; -import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Arrays; @@ -176,5 +175,15 @@ void callingIncreaseWithKeyThatDoesNotContainIntegerShouldReturnErrorMessage() { String increaseResult = testDatabase.increaseValue(List.of("INCR","key1")); assertThat(increaseResult).isEqualTo("-WRONGTYPE value is not an integer or out of range\r\n"); } + @Test + void callingDecreaseWithKeyWithIntegerShouldDecreaseValueBy1(){ + testDatabase.addValue("key1", "1"); + + String increaseResult = testDatabase.decreaseValue(List.of("DECR","key1")); + assertThat(increaseResult).isEqualTo(":0\r\n"); + assertThat(testDatabase.getValue("key1")).isEqualTo("0"); + + } + } diff --git a/src/test/java/org/fungover/haze/MainTest.java b/src/test/java/org/fungover/haze/MainTest.java index 3199558a..9ccd9f25 100644 --- a/src/test/java/org/fungover/haze/MainTest.java +++ b/src/test/java/org/fungover/haze/MainTest.java @@ -1,6 +1,5 @@ package org.fungover.haze; -import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; @@ -115,6 +114,12 @@ void callExecuteCommandWithIncrShouldIncreaseTheValueOfTheKeyBy1() { assertThat(Main.executeCommand(database, List.of("INCR", "key1"), hazeList)).isEqualTo(":2\r\n"); } + @Test + void callExecuteCommandWithDecrShouldDecreaseTheValueOfTheKeyBy1(){ + Main.executeCommand(database, List.of("SET", "key1", "1"), hazeList); + assertThat(Main.executeCommand(database, List.of("DECR", "key1"), hazeList)).isEqualTo(":0\r\n"); + } + @Test void testPrintThreadDebug() { ByteArrayOutputStream outContent = new ByteArrayOutputStream(); From faa8cdb070225c1b6a0d32be3b3bac536ef889fe Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Wed, 7 Feb 2024 17:56:27 +0100 Subject: [PATCH 24/44] Delete unused import + edit formatting change --- src/main/java/org/fungover/haze/HazeDatabase.java | 2 -- src/main/java/org/fungover/haze/Initialize.java | 1 + 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/org/fungover/haze/HazeDatabase.java b/src/main/java/org/fungover/haze/HazeDatabase.java index af67a402..be2a16ec 100644 --- a/src/main/java/org/fungover/haze/HazeDatabase.java +++ b/src/main/java/org/fungover/haze/HazeDatabase.java @@ -1,6 +1,4 @@ package org.fungover.haze; - -import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; diff --git a/src/main/java/org/fungover/haze/Initialize.java b/src/main/java/org/fungover/haze/Initialize.java index 8e660a5c..37fed6f7 100644 --- a/src/main/java/org/fungover/haze/Initialize.java +++ b/src/main/java/org/fungover/haze/Initialize.java @@ -38,6 +38,7 @@ public String getPassword() { return System.getenv("HAZE_PASSWORD"); } else return null; } + public void clearCliOptions() { cliOptions.clear(); } From 7cac319861f7989eff4e4e2aaa0d09cd1ad2861b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:14:22 +0000 Subject: [PATCH 25/44] Bump org.slf4j:slf4j-nop from 1.7.36 to 2.0.12 Bumps org.slf4j:slf4j-nop from 1.7.36 to 2.0.12. --- updated-dependencies: - dependency-name: org.slf4j:slf4j-nop dependency-type: direct:development update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6ff3f4dd..fade8556 100644 --- a/pom.xml +++ b/pom.xml @@ -69,7 +69,7 @@ org.slf4j slf4j-nop - 1.7.36 + 2.0.12 test From 9c34c7644f8675cd122b06067689b6c17b1f6c21 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:14:34 +0000 Subject: [PATCH 26/44] Bump org.mockito:mockito-core from 5.3.1 to 5.10.0 Bumps [org.mockito:mockito-core](https://github.com/mockito/mockito) from 5.3.1 to 5.10.0. - [Release notes](https://github.com/mockito/mockito/releases) - [Commits](https://github.com/mockito/mockito/compare/v5.3.1...v5.10.0) --- updated-dependencies: - dependency-name: org.mockito:mockito-core dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6ff3f4dd..f6537777 100644 --- a/pom.xml +++ b/pom.xml @@ -29,7 +29,7 @@ org.mockito mockito-core - 5.3.1 + 5.10.0 test From 21bd9cceb0a714f8e52555499cb8c4596568bea8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:14:44 +0000 Subject: [PATCH 27/44] Bump org.testcontainers:junit-jupiter from 1.17.6 to 1.19.5 Bumps [org.testcontainers:junit-jupiter](https://github.com/testcontainers/testcontainers-java) from 1.17.6 to 1.19.5. - [Release notes](https://github.com/testcontainers/testcontainers-java/releases) - [Changelog](https://github.com/testcontainers/testcontainers-java/blob/main/CHANGELOG.md) - [Commits](https://github.com/testcontainers/testcontainers-java/compare/1.17.6...1.19.5) --- updated-dependencies: - dependency-name: org.testcontainers:junit-jupiter dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6ff3f4dd..3603e197 100644 --- a/pom.xml +++ b/pom.xml @@ -63,7 +63,7 @@ org.testcontainers junit-jupiter - 1.17.6 + 1.19.5 test From e50dc6c58c8492c757dc58c71043570942daedc0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:14:50 +0000 Subject: [PATCH 28/44] Bump org.junit.jupiter:junit-jupiter from 5.9.2 to 5.10.2 Bumps [org.junit.jupiter:junit-jupiter](https://github.com/junit-team/junit5) from 5.9.2 to 5.10.2. - [Release notes](https://github.com/junit-team/junit5/releases) - [Commits](https://github.com/junit-team/junit5/compare/r5.9.2...r5.10.2) --- updated-dependencies: - dependency-name: org.junit.jupiter:junit-jupiter dependency-type: direct:development update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6ff3f4dd..1093ce58 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,7 @@ org.junit.jupiter junit-jupiter - 5.9.2 + 5.10.2 test From 95be7b8261b48ba0e8a5b86fb09e0169307dff63 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:14:55 +0000 Subject: [PATCH 29/44] Bump org.apache.maven.plugins:maven-failsafe-plugin from 3.2.1 to 3.2.5 Bumps [org.apache.maven.plugins:maven-failsafe-plugin](https://github.com/apache/maven-surefire) from 3.2.1 to 3.2.5. - [Release notes](https://github.com/apache/maven-surefire/releases) - [Commits](https://github.com/apache/maven-surefire/compare/surefire-3.2.1...surefire-3.2.5) --- updated-dependencies: - dependency-name: org.apache.maven.plugins:maven-failsafe-plugin dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 6ff3f4dd..f21fbd25 100644 --- a/pom.xml +++ b/pom.xml @@ -143,7 +143,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.2.1 + 3.2.5 From dfba93e11de2ef4858ef069ae07e15c85ecf8757 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:44:28 +0000 Subject: [PATCH 30/44] Bump docker/login-action from 2 to 3 Bumps [docker/login-action](https://github.com/docker/login-action) from 2 to 3. - [Release notes](https://github.com/docker/login-action/releases) - [Commits](https://github.com/docker/login-action/compare/v2...v3) --- updated-dependencies: - dependency-name: docker/login-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b0963335..d1fd73bf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,13 +35,13 @@ jobs: uses: docker/setup-buildx-action@v2 - name: Login to Docker Hub - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Login to GitHub Container Registry - uses: docker/login-action@v2 + uses: docker/login-action@v3 with: registry: ghcr.io username: ${{ github.actor }} From b0304926046d60b4cea2ec3277ba44540e303597 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:44:31 +0000 Subject: [PATCH 31/44] Bump actions/setup-java from 3 to 4 Bumps [actions/setup-java](https://github.com/actions/setup-java) from 3 to 4. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/v3...v4) --- updated-dependencies: - dependency-name: actions/setup-java dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/maven.yml | 2 +- .github/workflows/release.yml | 2 +- .github/workflows/sonar.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index 8b2b364d..16320988 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -27,7 +27,7 @@ jobs: Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - name: Set up JDK 19 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: ${{ env.Java_Version }} distribution: 'temurin' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b0963335..a401c8b3 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,7 +19,7 @@ jobs: Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - name: Set up JDK 19 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: ${{ env.Java_Version }} distribution: 'temurin' diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index ddcae766..04900b29 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -18,7 +18,7 @@ jobs: Java_Version=$(mvn help:evaluate "-Dexpression=maven.compiler.release" -q -DforceStdout | sed -e 's/^1\./1.0./') echo "Java_Version=$Java_Version" >> $GITHUB_ENV - name: Set up JDK 19 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: ${{ env.Java_Version }} distribution: 'temurin' From 4dbfe5c8d27ba7f1fab3da7c1cb784a21251e6f9 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:44:34 +0000 Subject: [PATCH 32/44] Bump docker/build-push-action from 4 to 5 Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 4 to 5. - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v4...v5) --- updated-dependencies: - dependency-name: docker/build-push-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b0963335..6b81727b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -62,7 +62,7 @@ jobs: type=sha - name: Build and push - uses: docker/build-push-action@v4 + uses: docker/build-push-action@v5 with: context: . platforms: linux/amd64,linux/arm64,linux/arm/v7 From 480f5969389691ca19f4fdfd0cbe07dab1ff61c1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:44:37 +0000 Subject: [PATCH 33/44] Bump release-drafter/release-drafter from 5 to 6 Bumps [release-drafter/release-drafter](https://github.com/release-drafter/release-drafter) from 5 to 6. - [Release notes](https://github.com/release-drafter/release-drafter/releases) - [Commits](https://github.com/release-drafter/release-drafter/compare/v5...v6) --- updated-dependencies: - dependency-name: release-drafter/release-drafter dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release-drafter.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml index 1525b796..11f3a074 100644 --- a/.github/workflows/release-drafter.yml +++ b/.github/workflows/release-drafter.yml @@ -17,7 +17,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: release-drafter/release-drafter@v5 + - uses: release-drafter/release-drafter@v6 with: config-name: release-drafter-config.yml env: From aea1f678872eb7f28d44f1faa63a8588c9ecb489 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 9 Feb 2024 07:44:40 +0000 Subject: [PATCH 34/44] Bump docker/metadata-action from 4 to 5 Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 4 to 5. - [Release notes](https://github.com/docker/metadata-action/releases) - [Upgrade guide](https://github.com/docker/metadata-action/blob/master/UPGRADE.md) - [Commits](https://github.com/docker/metadata-action/compare/v4...v5) --- updated-dependencies: - dependency-name: docker/metadata-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b0963335..5d77f54d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -49,7 +49,7 @@ jobs: - name: Docker meta id: meta - uses: docker/metadata-action@v4 + uses: docker/metadata-action@v5 with: images: | fungover/haze From 1621a45bad6fc31b6ab8a036a04c0e4cd147f302 Mon Sep 17 00:00:00 2001 From: Kourosh Talebzadeh Date: Fri, 9 Feb 2024 09:50:38 +0100 Subject: [PATCH 35/44] Update pom.xml --- pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/pom.xml b/pom.xml index 6ff3f4dd..48bea3d9 100644 --- a/pom.xml +++ b/pom.xml @@ -20,12 +20,6 @@ 5.9.2 test - - org.junit.jupiter - junit-jupiter-engine - 5.9.2 - test - org.mockito mockito-core From f7d43cec44e73b41a92028f4b106a337112ae043 Mon Sep 17 00:00:00 2001 From: Mats Kruskopf Eriksson Date: Fri, 9 Feb 2024 10:43:30 +0100 Subject: [PATCH 36/44] remove linux/arm/v7 --- .github/workflows/release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f7671255..c8292211 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -65,7 +65,7 @@ jobs: uses: docker/build-push-action@v5 with: context: . - platforms: linux/amd64,linux/arm64,linux/arm/v7 + platforms: linux/amd64,linux/arm64 push: true tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} From 5b767a35ff2a140f6965477438eba105d15acac8 Mon Sep 17 00:00:00 2001 From: robinalfengard Date: Fri, 9 Feb 2024 12:24:52 +0100 Subject: [PATCH 37/44] Removed comma which resultet in build fail --- src/main/java/org/fungover/haze/Command.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/fungover/haze/Command.java b/src/main/java/org/fungover/haze/Command.java index 4ab83cb3..88a5334f 100644 --- a/src/main/java/org/fungover/haze/Command.java +++ b/src/main/java/org/fungover/haze/Command.java @@ -1,5 +1,5 @@ package org.fungover.haze; public enum Command { - SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH, LINDEX + SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH, LINDEX, INCR, DECR, } From ababa3e7933601fa7bd2ee414b1f991a354494e0 Mon Sep 17 00:00:00 2001 From: Mats Kruskopf Eriksson Date: Fri, 9 Feb 2024 12:50:57 +0100 Subject: [PATCH 38/44] add test shouldImportCliOptionsWhenInitializingServer --- src/test/java/org/fungover/haze/InitializeTest.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/test/java/org/fungover/haze/InitializeTest.java b/src/test/java/org/fungover/haze/InitializeTest.java index 107a2258..dedbcc3b 100644 --- a/src/test/java/org/fungover/haze/InitializeTest.java +++ b/src/test/java/org/fungover/haze/InitializeTest.java @@ -1,9 +1,13 @@ package org.fungover.haze; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; class InitializeTest { @@ -56,6 +60,15 @@ void passwordSetByCLIWithDashPortShouldReturn1233() { assertThat(initialize.getPassword()).isEqualTo("1233"); } + @Test + void shouldImportCliOptionsWhenInitializingServer() { + String[] args = {"--password", "1234"}; + Initialize initialize = Mockito.mock(Initialize.class); + Auth auth = Mockito.mock(Auth.class); + + Initialize.initializeServer(args, initialize, auth); + verify(initialize).importCliOptions(args); + } } From b54a92b5d54e877c129b452aa96fd981c9dcb64b Mon Sep 17 00:00:00 2001 From: Mats Kruskopf Eriksson Date: Fri, 9 Feb 2024 13:04:47 +0100 Subject: [PATCH 39/44] remove unused import statement --- src/test/java/org/fungover/haze/InitializeTest.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/test/java/org/fungover/haze/InitializeTest.java b/src/test/java/org/fungover/haze/InitializeTest.java index dedbcc3b..f7d51134 100644 --- a/src/test/java/org/fungover/haze/InitializeTest.java +++ b/src/test/java/org/fungover/haze/InitializeTest.java @@ -1,13 +1,11 @@ package org.fungover.haze; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; class InitializeTest { From c14fb90e15a0fdcc310d5aa6f0514a1651ab4173 Mon Sep 17 00:00:00 2001 From: Mats Kruskopf Eriksson Date: Fri, 9 Feb 2024 13:30:36 +0100 Subject: [PATCH 40/44] add test shutdownClientIfNotAuthenticated --- src/test/java/org/fungover/haze/AuthTest.java | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/test/java/org/fungover/haze/AuthTest.java b/src/test/java/org/fungover/haze/AuthTest.java index 908a5ff4..8f12fe63 100644 --- a/src/test/java/org/fungover/haze/AuthTest.java +++ b/src/test/java/org/fungover/haze/AuthTest.java @@ -3,14 +3,19 @@ import org.junit.jupiter.api.Test; import org.mockito.Mock; +import org.mockito.Mockito; import java.io.IOException; +import java.io.OutputStream; +import java.lang.reflect.Method; import java.net.Socket; import java.util.ArrayList; import java.util.List; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; class AuthTest { @@ -81,4 +86,21 @@ void authCommandReceivedNoPassNoAuth() { assertThat(result).isFalse(); } + + @Test + void shutdownClientIfNotAuthenticated() throws Exception { + + Socket client = Mockito.mock(Socket.class); + OutputStream outputStream = Mockito.mock(OutputStream.class); + when(client.getOutputStream()).thenReturn(outputStream); + + Method method = Auth.class.getDeclaredMethod("shutdownClientIfNotAuthenticated", Socket.class, boolean.class, boolean.class); + method.setAccessible(true); + + method.invoke(null, client, false, true); + + verify(outputStream).write(Auth.printAuthError()); + verify(client).shutdownOutput(); + + } } From f3d0f4a4eba576d02b633954eab5bdfb2ce24031 Mon Sep 17 00:00:00 2001 From: Mats Kruskopf Eriksson Date: Fri, 9 Feb 2024 13:49:33 +0100 Subject: [PATCH 41/44] add test clientShouldNotBeShutdownWhenAuthenticatedOrPasswordIsNotSet, rename test shutDownClientIfNotAuthenticated to shutdownClientIfNotAuthenticatedWhenClientNotAuthenticatedAndPasswordIsSet --- src/test/java/org/fungover/haze/AuthTest.java | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/test/java/org/fungover/haze/AuthTest.java b/src/test/java/org/fungover/haze/AuthTest.java index 8f12fe63..362f4fb7 100644 --- a/src/test/java/org/fungover/haze/AuthTest.java +++ b/src/test/java/org/fungover/haze/AuthTest.java @@ -88,7 +88,7 @@ void authCommandReceivedNoPassNoAuth() { } @Test - void shutdownClientIfNotAuthenticated() throws Exception { + void shutdownClientIfNotAuthenticatedWhenClientNotAuthenticatedAndPasswordIsSet() throws Exception { Socket client = Mockito.mock(Socket.class); OutputStream outputStream = Mockito.mock(OutputStream.class); @@ -103,4 +103,23 @@ void shutdownClientIfNotAuthenticated() throws Exception { verify(client).shutdownOutput(); } + + @Test + void clientShouldNotBeShutdownWhenAuthenticatedOrPasswordIsNotSet() throws Exception { + + Socket client = Mockito.mock(Socket.class); + OutputStream outputStream = Mockito.mock(OutputStream.class); + when(client.getOutputStream()).thenReturn(outputStream); + + Method method = Auth.class.getDeclaredMethod("shutdownClientIfNotAuthenticated", Socket.class, boolean.class, boolean.class); + method.setAccessible(true); + + method.invoke(null, client, true, true); + verify(outputStream, Mockito.never()).write(Auth.printAuthError()); + verify(client, Mockito.never()).shutdownOutput(); + + method.invoke(null, client, false, false); + verify(outputStream, Mockito.never()).write(Auth.printAuthError()); + verify(client, Mockito.never()).shutdownOutput(); + } } From f32e334c638e954b41fc0ee91390fcb628aa7c35 Mon Sep 17 00:00:00 2001 From: Mats Kruskopf Eriksson Date: Fri, 9 Feb 2024 14:09:42 +0100 Subject: [PATCH 42/44] add test authenticateClientShouldReturnTrueForValidPassword --- src/test/java/org/fungover/haze/AuthTest.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/test/java/org/fungover/haze/AuthTest.java b/src/test/java/org/fungover/haze/AuthTest.java index 362f4fb7..e80cbaa9 100644 --- a/src/test/java/org/fungover/haze/AuthTest.java +++ b/src/test/java/org/fungover/haze/AuthTest.java @@ -11,9 +11,11 @@ import java.lang.reflect.Method; import java.net.Socket; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -87,6 +89,22 @@ void authCommandReceivedNoPassNoAuth() { } + @Test + void authenticateClientShouldReturnTrueForValidPassword() throws IOException { + + Auth auth = Mockito.mock(Auth.class); + Socket client = Mockito.mock(Socket.class); + List inputList = new ArrayList<>(); + inputList.add("AUTH"); + inputList.add("password"); + + when(auth.authenticate(inputList.get(1), client)).thenReturn(true); + + boolean result = Auth.authenticateClient(auth, true, client, inputList, false); + + assertTrue(result); + } + @Test void shutdownClientIfNotAuthenticatedWhenClientNotAuthenticatedAndPasswordIsSet() throws Exception { From 10ed3cd728436ffa1e705c8812d174b3fdb3fbeb Mon Sep 17 00:00:00 2001 From: Mats Kruskopf Eriksson Date: Fri, 9 Feb 2024 14:23:21 +0100 Subject: [PATCH 43/44] add test authenticateShouldShutdownOutputForInvalidPassword --- src/test/java/org/fungover/haze/AuthTest.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/test/java/org/fungover/haze/AuthTest.java b/src/test/java/org/fungover/haze/AuthTest.java index e80cbaa9..f5735992 100644 --- a/src/test/java/org/fungover/haze/AuthTest.java +++ b/src/test/java/org/fungover/haze/AuthTest.java @@ -1,6 +1,7 @@ package org.fungover.haze; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.Mockito; @@ -89,6 +90,21 @@ void authCommandReceivedNoPassNoAuth() { } + @Test + void authenticateShouldShutdownOutputForInvalidPassword() throws IOException { + + Auth auth = new Auth(); + auth.setPassword("12345"); + + Socket client = Mockito.mock(Socket.class); + OutputStream outputStream = Mockito.mock(OutputStream.class); + when(client.getOutputStream()).thenReturn(outputStream); + + auth.authenticate("wrongPassword", client); + + verify(client).shutdownOutput(); + } + @Test void authenticateClientShouldReturnTrueForValidPassword() throws IOException { From 7e503efbca130192bdf9a763c585175a69482a2d Mon Sep 17 00:00:00 2001 From: ValentinaSukonina Date: Mon, 12 Feb 2024 03:09:20 +0100 Subject: [PATCH 44/44] add tests HazeDatabaseTest, SaveFileTest, MainTest --- src/main/java/org/fungover/haze/Main.java | 2 +- .../org/fungover/haze/HazeDatabaseTest.java | 66 +++++++++++++++++++ src/test/java/org/fungover/haze/MainTest.java | 18 +++++ .../java/org/fungover/haze/SaveFileTest.java | 12 ++++ 4 files changed, 97 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/fungover/haze/Main.java b/src/main/java/org/fungover/haze/Main.java index 23d5aa46..f8314b54 100644 --- a/src/main/java/org/fungover/haze/Main.java +++ b/src/main/java/org/fungover/haze/Main.java @@ -165,7 +165,7 @@ private static void shutdownClientIfNotAuthenticated(Socket client, boolean clie } } - private static boolean authCommandReceived(boolean isPasswordSet, List inputList, boolean clientAuthenticated) { + static boolean authCommandReceived(boolean isPasswordSet, List inputList, boolean clientAuthenticated) { return isPasswordSet && !clientAuthenticated && inputList.size() == 2 && inputList.getFirst().equals("AUTH"); } } diff --git a/src/test/java/org/fungover/haze/HazeDatabaseTest.java b/src/test/java/org/fungover/haze/HazeDatabaseTest.java index 46e4aa2b..54ed9928 100644 --- a/src/test/java/org/fungover/haze/HazeDatabaseTest.java +++ b/src/test/java/org/fungover/haze/HazeDatabaseTest.java @@ -1,5 +1,6 @@ package org.fungover.haze; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import java.util.Arrays; @@ -8,6 +9,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; class HazeDatabaseTest { @@ -33,6 +35,14 @@ void callingDeleteRemovesTheSpecifiedKey() { assertThat(testDatabase.get(List.of("", "1"))).isEqualTo("$-1\r\n"); } + @Test + @DisplayName("Calling delete throw IllegalArgumentException for empty key") + void callingDeleteThrowIllegalArgumentExceptionForEmptyKey() { + assertThrows(IllegalArgumentException.class, () -> { + testDatabase.delete(Collections.emptyList()); + }, "No keys provided"); + } + @Test void callingGetReturnsTheCorrectValueIfItExists() { testDatabase.setNX(List.of("SETNX", "someKey", "someValue")); @@ -92,6 +102,33 @@ void testPingResponseShouldBeSameAsValue() { assertThat(testDatabase.ping(List.of("PING", "test message"))).isEqualTo("$12\r\ntest message\r\n"); } + @Test + @DisplayName("testPing throw Exception for null message list") + void testPingThrowExceptionForNullMessageList() { + + assertThrows(IllegalArgumentException.class, () -> { + testDatabase.ping(null); + }, "No message provided"); + } + + @Test + @DisplayName("testPing throw Exception for Empty message list") + void testPingThrowExceptionForEmptyMessageList() { + + assertThrows(IllegalArgumentException.class, () -> { + testDatabase.ping(List.of()); + }, "No message provided"); + } + + @Test + @DisplayName("testPing throw exception for too many arguments") + void testPingThrowExceptionForTooManyArguments() { + + assertThrows(IllegalArgumentException.class, () -> { + testDatabase.ping(List.of("arg1", "arg2", "arg3")); + }, "Too many arguments for PING command"); + } + @Test void testSetWithValidKeyValuePair() { String result = testDatabase.set(List.of("", "key", "value")); @@ -182,8 +219,37 @@ void callingDecreaseWithKeyWithIntegerShouldDecreaseValueBy1(){ String increaseResult = testDatabase.decreaseValue(List.of("DECR","key1")); assertThat(increaseResult).isEqualTo(":0\r\n"); assertThat(testDatabase.getValue("key1")).isEqualTo("0"); + } + + @Test + @DisplayName("increaseValue should return ERR message when key does not exist") + void increaseValueShouldReturnErrMessageWhenKeyDoesNotExist() { + + String nonExistentKey = "nonExistentKey"; + List inputList = List.of("INCR", nonExistentKey); + + assertThat(testDatabase.increaseValue(inputList)).isEqualTo("-ERR no such key\r\n"); + } + @Test + @DisplayName("decreaseValue should return ERR message when key does not exist") + void decreaseValueShouldReturnErrMessageWhenKeyDoesNotExist() { + + String nonExistentKey = "nonExistentKey"; + List inputList = List.of("DECR", nonExistentKey); + + assertThat(testDatabase.decreaseValue(inputList)).isEqualTo("-ERR no such key\r\n"); } + @Test + @DisplayName("decreaseValue should return WRONGTYPE message when value is not Integer") + void decreaseValueShouldReturnWrongtypeMessageWhenValueIsNotInteger() { + String key = "key"; + testDatabase.addValue(key, "notInteger"); + + assertThat(testDatabase.decreaseValue(List.of("DECR", key))) + .isEqualTo("-WRONGTYPE value is not an integer or out of range\r\n"); + + } } diff --git a/src/test/java/org/fungover/haze/MainTest.java b/src/test/java/org/fungover/haze/MainTest.java index 9ccd9f25..3b2bda27 100644 --- a/src/test/java/org/fungover/haze/MainTest.java +++ b/src/test/java/org/fungover/haze/MainTest.java @@ -7,10 +7,12 @@ import java.io.ByteArrayOutputStream; import java.io.PrintStream; +import java.util.LinkedList; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.fungover.haze.Main.printThreadDebug; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -130,4 +132,20 @@ void testPrintThreadDebug() { assertFalse(outContent.toString().contains("ThreadID")); assertFalse(outContent.toString().contains("Is virtual Thread")); } + + @ParameterizedTest + @CsvSource({ + "true, AUTH, password, false, true", + "false, AUTH, password, false, false", + "true, SET, password, false, false", + "true, AUTH, password, true, false", + "false, AUTH, password, true, false" + }) + void authCommandReceivedTest(boolean isPasswordSet, String command, String password, boolean clientAuthenticated, boolean expected) { + List inputList = new LinkedList<>(List.of(command, password)); + + boolean result = Main.authCommandReceived(isPasswordSet, inputList, clientAuthenticated); + + assertEquals(expected, result); + } } diff --git a/src/test/java/org/fungover/haze/SaveFileTest.java b/src/test/java/org/fungover/haze/SaveFileTest.java index a118eeb2..8d0a2382 100644 --- a/src/test/java/org/fungover/haze/SaveFileTest.java +++ b/src/test/java/org/fungover/haze/SaveFileTest.java @@ -71,4 +71,16 @@ private int compareLastModified(Path p1, Path p2) { throw new RuntimeException(e); } } + + @Test + @DisplayName("File already exists returns +OK\\r\\n") + void fileAlreadyExistsReturnsOK(@TempDir Path tempDir) { + System.setProperty("user.home", tempDir.toString()); + var map = Map.of("key", "value"); + + SaveFile.createFile(); + + assertThat(SaveFile.writeOnFile(map)).isEqualTo("+OK\r\n"); + } } +