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 15 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
19 changes: 7 additions & 12 deletions .github/workflows/maven.yml
cmatlak marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,15 @@ 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@v4
with:
java-version: ${{ env.Java_Version }}
distribution: 'temurin'
cache: maven
- name: Compile with Maven
run: mvn -B compile --file pom.xml

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


- name: Set up JDK ${{env.Java_Version}}




9 changes: 7 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,17 @@ 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


- name: Set up ${{env.Java_Version}}



uses: actions/setup-java@v4
with:
java-version: ${{ env.Java_Version }}
Expand Down
9 changes: 7 additions & 2 deletions .github/workflows/sonar.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,19 @@ 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


- name: Set up ${{env.Java_Version}}



uses: actions/setup-java@v4
with:
java-version: ${{ env.Java_Version }}
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/org/fungover/haze/Initialize.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

}
220 changes: 124 additions & 96 deletions src/main/java/org/fungover/haze/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,83 +10,101 @@
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();
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<String> 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();
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) {
cmatlak marked this conversation as resolved.
Show resolved Hide resolved
List<String> inputList = getInputList(input);
clientAuthenticated = authenticateClient(auth, isPasswordSet, client, inputList, clientAuthenticated);
handleThread(hazeList, hazeDatabase, client, inputList);
}

readInputStream(input,inputList,firstReading);
} catch (IOException e) {
logger.error(e);
}
}

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

client.getOutputStream().write(executeCommand(hazeDatabase, inputList, hazeList).getBytes());
inputList.clear();
}

inputList.forEach(System.out::println); // For checking incoming message
private static void controlCommand(HazeList hazeList, HazeDatabase hazeDatabase, Socket client, List<String> inputList) throws IOException {
client.getOutputStream().write(executeCommand(hazeDatabase, inputList, hazeList).getBytes());

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

inputList.clear();
}
public static List<String> getInputList(BufferedReader input) throws IOException {
List<String> inputList = new ArrayList<>();

} catch (IOException e) {
logger.error(e);
}
};
Thread.startVirtualThread(newThread);
}
} catch (IOException e) {
logger.error(e);
}
logger.info("Shutting down....");
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

private static void printThreadDebug() {
cmatlak marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -105,67 +123,77 @@ public static String executeCommand(HazeDatabase hazeDatabase, List<String> inpu
return "-ERR unknown command\r\n";
}

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 LINDEX -> hazeList.lIndex(inputList);
case AUTH -> "+OK\r\n";
case INCR -> hazeDatabase.increaseValue(inputList);
case DECR -> hazeDatabase.decreaseValue(inputList);
};
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);
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 LINDEX -> hazeList.lIndex(inputList);
case INCR -> hazeDatabase.increaseValue(inputList);
case DECR -> hazeDatabase.decreaseValue(inputList);
case AUTH -> "+OK\r\n";
};
}

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<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 < 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<String> inputList, boolean clientAuthenticated) {
return isPasswordSet && !clientAuthenticated && inputList.size() == 2 && inputList.getFirst().equals("AUTH");
private static boolean authCommandReceived ( boolean isPasswordSet, List<String > inputList, boolean clientAuthenticated){
return isPasswordSet && !clientAuthenticated && inputList.size() == 2 && inputList.getFirst().equals("AUTH");
}
}
}


Loading
Loading