Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

115 refactor main #206

Open
wants to merge 45 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
d191597
deleted redundant imports
cmatlak Feb 5, 2024
ad1fcaf
deleted redundant imports
cmatlak Feb 5, 2024
e14b550
Smaller changes of the metod callings
cmatlak Feb 6, 2024
8d989f6
Merge branch 'main' into 115-refactor-main-OldPullRequst-Fix
cmatlak Feb 7, 2024
63536ba
Update mockito dependency
robinalfengard Feb 7, 2024
a34aec1
removed out commented code
cmatlak Feb 7, 2024
14e6de5
Switched public method to private in main + removed method specific t…
robinalfengard Feb 7, 2024
89536e4
Add test method for main execute command with out one empty command
cmatlak Feb 9, 2024
b27eb85
Add test method for main execute command with out one empty command
cmatlak Feb 9, 2024
3ee767c
Merge remote-tracking branch 'origin/115-refactor-main-OldPullRequst-…
cmatlak Feb 9, 2024
9f149cb
fixed an error in pom
cmatlak Feb 9, 2024
5d3b49f
115 refactor main old pull requst fix (#182)
cmatlak Feb 9, 2024
e3a8c41
Merge branch 'main' into 115-refactor-main
cmatlak Feb 9, 2024
aac1444
fixed an error in command
cmatlak Feb 9, 2024
39a95b0
fixed an error in command
cmatlak Feb 9, 2024
7071550
fixed errors
cmatlak Feb 9, 2024
6273b06
fixed errors
cmatlak Feb 12, 2024
6ad90f6
Merge branch 'main' into 115-refactor-main
cmatlak Feb 12, 2024
95e488a
fixed errors
cmatlak Feb 12, 2024
8bd0cc1
fixed potentially endless loop
cmatlak Feb 12, 2024
e11cc1c
Merge remote-tracking branch 'origin/115-refactor-main' into 115-refa…
cmatlak Feb 12, 2024
08e4415
added test for getInitialized
cmatlak Feb 12, 2024
60852a1
added test for getInitialized
cmatlak Feb 12, 2024
2602dd7
updated test method and deleted evergreen test
cmatlak Feb 14, 2024
d594ddb
delete imports
cmatlak Feb 14, 2024
e5faaec
changed deprecated method
cmatlak Feb 14, 2024
a3d26e2
Merge branch 'main' into 115-refactor-main
cmatlak Feb 14, 2024
6ca6812
changed deprecated method
cmatlak Feb 14, 2024
3ca5499
changes
cmatlak Feb 14, 2024
aa09bdd
changes
cmatlak Feb 14, 2024
b969ba8
changes
cmatlak Feb 14, 2024
635bb8a
changes
cmatlak Feb 14, 2024
7f7183f
changes
cmatlak Feb 14, 2024
c882404
changes
cmatlak Feb 14, 2024
6ffefb4
Test disappeared added back
cmatlak Feb 14, 2024
1f9bc50
change of display
cmatlak Feb 14, 2024
a758501
fixed potentially endless loop
cmatlak Feb 12, 2024
a7a41b2
Auth methods
cmatlak Feb 13, 2024
309b6f9
change of display
cmatlak Feb 14, 2024
36e66d6
deleted import
cmatlak Feb 14, 2024
d8f086a
test readinputstream
cmatlak Feb 14, 2024
f201ad9
Merge branch 'main' into 115-refactor-main
cmatlak Feb 16, 2024
f6e8989
Merge branch 'main' into 115-refactor-main
maxerkmar May 27, 2024
6ae9d04
fixed conflict in readInputStream
maxerkmar May 27, 2024
0dea023
changed access modifier on readInputStream to public for tests
maxerkmar May 27, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions .github/workflows/maven.yml
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven

# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

name: Java CI with Maven

Expand All @@ -26,7 +20,10 @@ 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 ${{ env.Java_Version }}

uses: actions/setup-java@v4
with:
java-version: ${{ env.Java_Version }}
Expand All @@ -37,4 +34,3 @@ jobs:

- name: Test with Maven
run: mvn -B test --file pom.xml

8 changes: 7 additions & 1 deletion .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ 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 }}
Expand Down
9 changes: 8 additions & 1 deletion .github/workflows/sonar.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,14 @@ 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 }}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/org/fungover/haze/Auth.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public static boolean authenticateClient(Auth auth, boolean isPasswordSet, Socke
return clientAuthenticated;
}

private static void shutdownClientIfNotAuthenticated(Socket client, boolean clientAuthenticated, boolean isPasswordSet) throws IOException {
public static void shutdownClientIfNotAuthenticated(Socket client, boolean clientAuthenticated, boolean isPasswordSet) throws IOException {
if (!clientAuthenticated && isPasswordSet) {
client.getOutputStream().write(Auth.printAuthError());
client.shutdownOutput();
Expand Down
1 change: 1 addition & 0 deletions src/main/java/org/fungover/haze/Command.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
public enum Command {
SET, GET, DEL, PING, SETNX, EXISTS, SAVE, RPUSH, LPUSH, LPOP, RPOP, LLEN, LMOVE, LTRIM, AUTH, LINDEX, INCR, DECR, LSET, GETDEL, LINSERT
}

8 changes: 7 additions & 1 deletion src/main/java/org/fungover/haze/Initialize.java
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,15 @@ 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;
}

}
127 changes: 75 additions & 52 deletions src/main/java/org/fungover/haze/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,88 +8,108 @@
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
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);


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();
Initialize.initializeServer(args, initialize, auth);
final boolean isPasswordSet = auth.isPasswordSet();


Thread printingHook = new Thread(() -> shutdown(hazeDatabase));
Runtime.getRuntime().addShutdownHook(printingHook);
addHook(hazeDatabase);

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()");

Runnable newThread = () -> {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(client.getInputStream()));
boolean clientAuthenticated = false;
while (!client.isClosed()) {
List<String> inputList = new ArrayList<>();

String firstReading = input.readLine();
initSocket(initialize, serverSocket);
whileServerOpen(hazeList, hazeDatabase, auth, isPasswordSet, serverSocket);
} catch (IOException e) {
logger.error(e);
}
logger.info("Shutting down....");
}

if (firstReading == null) {
logger.info("client has closed the connection");
client.close();
return;
}
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()");

readInputStream(input, inputList, firstReading);
runThread(hazeList, hazeDatabase, auth, isPasswordSet, client);
}
}

clientAuthenticated = Auth.authenticateClient(auth, isPasswordSet, client, inputList, clientAuthenticated);

client.getOutputStream().write(executeCommand(hazeDatabase, inputList, hazeList).getBytes());
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);
}

inputList.forEach(System.out::println); // For checking incoming message

printThreadDebug();
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 (!client.isClosed()) {
List<String> inputList = getInputList(input);
clientAuthenticated = Auth.authenticateClient(auth, isPasswordSet, client, inputList, clientAuthenticated);
handleThread(hazeList, hazeDatabase, client, inputList);
}

inputList.clear();
}

} catch (IOException e) {
logger.error(e);
}
};
Thread.startVirtualThread(newThread);
}
} catch (IOException e) {
logger.error(e);
}
logger.info("Shutting down....");
}


private static void handleThread(HazeList hazeList, HazeDatabase hazeDatabase, Socket client, List<String> inputList) throws IOException {
controlCommand(hazeList, hazeDatabase, client, inputList);
printThreadDebug();

inputList.clear();
}

private static void controlCommand(HazeList hazeList, HazeDatabase hazeDatabase, Socket client, List<String> inputList) throws IOException {
client.getOutputStream().write(executeCommand(hazeDatabase, inputList, hazeList).getBytes());

inputList.forEach(System.out::println); // For checking incoming message
}

public static List<String> getInputList(BufferedReader input) throws IOException {
List<String> 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 void shutdown(HazeDatabase hazeDatabase) {
SaveFile.writeOnFile(hazeDatabase.copy());
logger.info("Shutting down....");
}


public static void printThreadDebug() {
logger.debug("ThreadID " + Thread.currentThread().threadId()); // Only for Debug
logger.debug("Is virtual Thread " + Thread.currentThread().isVirtual()); // Only for Debug

static void printThreadDebug() {
logger.debug("ThreadID {}", () -> Thread.currentThread().threadId()); // Only for Debug
logger.debug("Is virtual Thread {}", () -> Thread.currentThread().isVirtual()); // Only for Debug
}

public static String executeCommand(HazeDatabase hazeDatabase, List<String> inputList, HazeList hazeList) {
Expand All @@ -106,8 +126,9 @@ public static String executeCommand(HazeDatabase hazeDatabase, List<String> inpu
commandEnum = Command.valueOf(command);
} catch (IllegalArgumentException ex) {
return "-ERR unknown command\r\n";
}


}
return switch (commandEnum) {
case SET -> hazeDatabase.set(inputList);
case GET -> hazeDatabase.get(inputList);
Expand All @@ -132,9 +153,7 @@ public static String executeCommand(HazeDatabase hazeDatabase, List<String> inpu
case LINSERT -> hazeList.lInsert(inputList);
};
}

private static void readInputStream(BufferedReader input, List<String> inputList, String firstReading) throws
IOException {
public static void readInputStream(BufferedReader input, List<String> inputList, String firstReading) throws IOException {
logger.debug("readInputStream: {} {} {}", () -> input, () -> inputList, () -> firstReading);
int size;
if (firstReading.startsWith("*")) {
Expand All @@ -149,5 +168,9 @@ private static void readInputStream(BufferedReader input, List<String> inputList
inputList.addAll(Arrays.asList(seperated));
}
}

}





24 changes: 22 additions & 2 deletions src/test/java/org/fungover/haze/InitializeTest.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.fungover.haze;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;


import java.lang.reflect.Field;
import java.util.Map;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.mockito.Mockito.verify;

Expand Down Expand Up @@ -60,6 +62,24 @@ void passwordSetByCLIWithDashPortShouldReturn1233() {
assertThat(initialize.getPassword()).isEqualTo("1233");
}

@Test
public void testGetInitialize() throws NoSuchFieldException, IllegalAccessException {

String[] args = {"-p", "1234", "--password", "test"};


Initialize initialize = Initialize.getInitialize(args);


Field field = Initialize.class.getDeclaredField("cliOptions");
field.setAccessible(true);
Object obj = field.get(initialize);

Assertions.assertNotNull(obj);
Assertions.assertEquals("1234", ((Map<String, String>) obj).get("-p"));
Assertions.assertEquals("test", ((Map<String, String>) obj).get("--password"));
}

@Test
void shouldImportCliOptionsWhenInitializingServer() {
String[] args = {"--password", "1234"};
Expand All @@ -71,7 +91,7 @@ void shouldImportCliOptionsWhenInitializingServer() {
verify(initialize).importCliOptions(args);
}

}



}
Loading