From 353a0e0547b45cdc04034af12a1d1e19ecc123a8 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Tue, 31 Mar 2026 16:25:07 +0200 Subject: [PATCH 01/26] Added a new Template type: DynamicHTMLTemplate this one is basically meant as a hook for plugins to inject their own templates into pages without completely rewriting the pages --- .../de/igslandstuhl/database/Registry.java | 5 +++ .../database/client/HTMLTemplate.java | 4 ++ .../client/dynamic/DynamicFieldType.java | 44 +++++++++++++++++++ .../client/dynamic/DynamicHTMLTemplate.java | 27 ++++++++++++ .../meta/dynamic/dynamic_field_types.json | 3 ++ 5 files changed, 83 insertions(+) create mode 100644 src/main/java/de/igslandstuhl/database/client/dynamic/DynamicFieldType.java create mode 100644 src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java create mode 100644 src/main/resources/meta/dynamic/dynamic_field_types.json diff --git a/src/main/java/de/igslandstuhl/database/Registry.java b/src/main/java/de/igslandstuhl/database/Registry.java index 6e756e2..12e09f8 100644 --- a/src/main/java/de/igslandstuhl/database/Registry.java +++ b/src/main/java/de/igslandstuhl/database/Registry.java @@ -8,6 +8,7 @@ import java.util.stream.Stream; import de.igslandstuhl.database.client.HTMLTemplate; +import de.igslandstuhl.database.client.dynamic.DynamicFieldType; import de.igslandstuhl.database.client.navigation.NavigationElement; import de.igslandstuhl.database.client.navigation.NavigationType; import de.igslandstuhl.database.plugins.Plugin; @@ -28,6 +29,7 @@ public class Registry implements Closeable { private static final Registry WEB_PATH_REGISTRY = new Registry<>(); private static final EnumRegistry NAVIGATION_REGISTRY = new EnumRegistry<>(NavigationType.class); + private static final EnumRegistry DYNAMIC_TEMPLATES_REGISTRY = new EnumRegistry<>(DynamicFieldType.class); private static final Registry TEMPLATE_REGISTRY = new Registry<>(); public static Registry commandRegistry() { @@ -51,6 +53,9 @@ public static Registry webPathRegistry() { public static EnumRegistry navigationRegistry() { return NAVIGATION_REGISTRY; } + public static EnumRegistry dynamicTemplatesRegistry() { + return DYNAMIC_TEMPLATES_REGISTRY; + } public static Registry templateRegistry() { return TEMPLATE_REGISTRY; } diff --git a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java index 79a3d20..2315956 100644 --- a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java +++ b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java @@ -4,6 +4,8 @@ import java.util.Map; import de.igslandstuhl.database.Registry; +import de.igslandstuhl.database.client.dynamic.DynamicFieldType; +import de.igslandstuhl.database.client.dynamic.DynamicHTMLTemplate; import de.igslandstuhl.database.client.navigation.HTMLNavigationTemplate; import de.igslandstuhl.database.client.navigation.NavigationAppearance; import de.igslandstuhl.database.client.navigation.NavigationElement; @@ -36,6 +38,8 @@ public static void registerAll() { break; case "HTMLNavigationTemplate": register(new HTMLNavigationTemplate(NavigationAppearance.valueOf((String) template.get("appearance")), NavigationType.valueOf((String) template.get("navigation_type"))), key); + case "DynamicHTMLTemplate": + register(new DynamicHTMLTemplate(DynamicFieldType.valueOf((String) template.get("dynamic_field_type"))), key); default: break; } diff --git a/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicFieldType.java b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicFieldType.java new file mode 100644 index 0000000..7220797 --- /dev/null +++ b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicFieldType.java @@ -0,0 +1,44 @@ +package de.igslandstuhl.database.client.dynamic; + +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import de.igslandstuhl.database.Registry; +import de.igslandstuhl.database.server.resources.ResourceLocation; +import de.igslandstuhl.database.utils.RegistryEnum; + +public class DynamicFieldType extends RegistryEnum { + protected DynamicFieldType(Registry registry, String key) { + super(registry, key); + } + + private static final ResourceLocation meta = new ResourceLocation("meta", "dynamic", "dynamic_field_types.json"); + @Override + protected DynamicFieldType[] values(Registry registry) { + List DynamicFieldTypes = registry.stream().toList(); + DynamicFieldType[] arr = new DynamicFieldType[DynamicFieldTypes.size()]; + return DynamicFieldTypes.toArray(arr); + } + + @Override + protected void initValues() { + initUsingJSONMeta(meta); + } + + @Override + protected DynamicFieldType initValue(Registry registry,String key) { + return new DynamicFieldType(registry, key); + } + + public static DynamicFieldType valueOf(String string) { + return RegistryEnum.valueOf(string, DynamicFieldType.class); + } + public static void init() { + try { + RegistryEnum.init(DynamicFieldType.class); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException + | NoSuchMethodException | SecurityException e) { + throw new ExceptionInInitializerError(e); + } + } +} diff --git a/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java new file mode 100644 index 0000000..9558733 --- /dev/null +++ b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java @@ -0,0 +1,27 @@ +package de.igslandstuhl.database.client.dynamic; + +import java.io.IOException; +import java.util.Map; + +import de.igslandstuhl.database.Registry; +import de.igslandstuhl.database.client.HTMLTemplate; +import de.igslandstuhl.database.client.TemplatingPreprocessor; + +public record DynamicHTMLTemplate(DynamicFieldType type) implements HTMLTemplate { + @Override + public String fill(Map args) { + return Registry.dynamicTemplatesRegistry().stream(type) + .map(Registry.templateRegistry()::get) + .map((t) -> t.fill(args)) + .map(arg0 -> { + try { + return TemplatingPreprocessor.getInstance().executeTemplating(arg0); + } catch (IOException e) { + System.err.println("Failed filling template " + arg0); + e.printStackTrace(); + return ""; + } + }) + .reduce("", (s1, s2) -> s1 + "\n" + s2); + } +} \ No newline at end of file diff --git a/src/main/resources/meta/dynamic/dynamic_field_types.json b/src/main/resources/meta/dynamic/dynamic_field_types.json new file mode 100644 index 0000000..1610ea1 --- /dev/null +++ b/src/main/resources/meta/dynamic/dynamic_field_types.json @@ -0,0 +1,3 @@ +[ + +] \ No newline at end of file From fa49f6c004c4880ee1c16ca0a1c3c53a44b7e634 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Tue, 31 Mar 2026 16:57:18 +0200 Subject: [PATCH 02/26] Added the first dynamic field type: student_header --- .../igslandstuhl/database/client/HTMLTemplate.java | 2 ++ .../client/dynamic/DynamicHTMLTemplate.java | 14 ++++++++++++++ .../resources/meta/dynamic/dynamic_elements.json | 6 ++++++ .../meta/dynamic/dynamic_field_types.json | 2 +- src/main/resources/meta/templates/templates.json | 9 +++++++++ .../templates/html/student_dashboard.html | 3 +-- .../resources/templates/html/student_header.html | 4 ++++ 7 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 src/main/resources/meta/dynamic/dynamic_elements.json create mode 100644 src/main/resources/templates/html/student_header.html diff --git a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java index 2315956..8b20614 100644 --- a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java +++ b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java @@ -21,6 +21,7 @@ private static void register(HTMLTemplate template, String key) { } public static void registerAll() { NavigationElement.registerAll(); + DynamicHTMLTemplate.registerDynamicElements(); Map json = Server.getInstance().getResourceManager().readJsonResourceMerged(meta); json.keySet().forEach((key) -> { @SuppressWarnings("unchecked") @@ -38,6 +39,7 @@ public static void registerAll() { break; case "HTMLNavigationTemplate": register(new HTMLNavigationTemplate(NavigationAppearance.valueOf((String) template.get("appearance")), NavigationType.valueOf((String) template.get("navigation_type"))), key); + break; case "DynamicHTMLTemplate": register(new DynamicHTMLTemplate(DynamicFieldType.valueOf((String) template.get("dynamic_field_type"))), key); default: diff --git a/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java index 9558733..e425e1a 100644 --- a/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java +++ b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java @@ -1,11 +1,16 @@ package de.igslandstuhl.database.client.dynamic; import java.io.IOException; +import java.util.List; import java.util.Map; +import com.google.gson.reflect.TypeToken; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.client.HTMLTemplate; import de.igslandstuhl.database.client.TemplatingPreprocessor; +import de.igslandstuhl.database.server.Server; +import de.igslandstuhl.database.server.resources.ResourceLocation; public record DynamicHTMLTemplate(DynamicFieldType type) implements HTMLTemplate { @Override @@ -24,4 +29,13 @@ public String fill(Map args) { }) .reduce("", (s1, s2) -> s1 + "\n" + s2); } + public static final ResourceLocation meta = new ResourceLocation("meta", "dynamic", "dynamic_elements.json"); + public static void registerDynamicElements() { + List> elements = Server.getInstance().getResourceManager().readJsonListMerged(meta, new TypeToken>>() {}); + elements.forEach((m) -> { + DynamicFieldType type = DynamicFieldType.valueOf(m.get("type")); + String template = m.get("template"); + Registry.dynamicTemplatesRegistry().register(type, template); + }); + } } \ No newline at end of file diff --git a/src/main/resources/meta/dynamic/dynamic_elements.json b/src/main/resources/meta/dynamic/dynamic_elements.json new file mode 100644 index 0000000..9f25510 --- /dev/null +++ b/src/main/resources/meta/dynamic/dynamic_elements.json @@ -0,0 +1,6 @@ +[ + { + "type": "STUDENT_HEADER", + "template": "student_header_builtin" + } +] \ No newline at end of file diff --git a/src/main/resources/meta/dynamic/dynamic_field_types.json b/src/main/resources/meta/dynamic/dynamic_field_types.json index 1610ea1..a2a6757 100644 --- a/src/main/resources/meta/dynamic/dynamic_field_types.json +++ b/src/main/resources/meta/dynamic/dynamic_field_types.json @@ -1,3 +1,3 @@ [ - + "STUDENT_HEADER" ] \ No newline at end of file diff --git a/src/main/resources/meta/templates/templates.json b/src/main/resources/meta/templates/templates.json index 69d6494..3e854a1 100644 --- a/src/main/resources/meta/templates/templates.json +++ b/src/main/resources/meta/templates/templates.json @@ -27,6 +27,10 @@ "type": "HTMLFileTemplate", "path": "subject_info" }, + "student_header_builtin": { + "type": "HTMLFileTemplate", + "path": "student_header" + }, "admin_dashboard_nav": { "type": "HTMLNavigationTemplate", @@ -92,5 +96,10 @@ "type": "HTMLNavigationTemplate", "navigation_type": "STUDENT_OTHER", "appearance": "BUTTON_APPEARANCE" + }, + + "student_header": { + "type": "DynamicHTMLTemplate", + "dynamic_field_type": "STUDENT_HEADER" } } \ No newline at end of file diff --git a/src/main/resources/templates/html/student_dashboard.html b/src/main/resources/templates/html/student_dashboard.html index 196edfc..88a92f0 100644 --- a/src/main/resources/templates/html/student_dashboard.html +++ b/src/main/resources/templates/html/student_dashboard.html @@ -1,8 +1,7 @@ %[site;title=Schüler-Dashboard;content=!FOLLOWS]
-

Schüler:

-

Klasse: | E-Mail: | Graduierung:

+ %[student_header]
diff --git a/src/main/resources/templates/html/student_header.html b/src/main/resources/templates/html/student_header.html new file mode 100644 index 0000000..3ab1306 --- /dev/null +++ b/src/main/resources/templates/html/student_header.html @@ -0,0 +1,4 @@ +
+

Schüler:

+

Klasse: | E-Mail: | Graduierung:

+
\ No newline at end of file From 1b1386256ec3a9d6b3eef01fbfa610fe4f46b222 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Tue, 31 Mar 2026 18:36:06 +0200 Subject: [PATCH 03/26] Added new dynamic templates --- src/main/resources/html/admin/teacher.html | 4 +--- src/main/resources/html/teacher/dashboard.html | 4 +--- .../meta/dynamic/dynamic_elements.json | 18 ++++++++++++++++++ .../meta/dynamic/dynamic_field_types.json | 4 +++- .../resources/meta/templates/templates.json | 12 ++++++++++++ .../templates/html/room_selection.html | 4 ++++ .../templates/html/student_dashboard.html | 5 +---- 7 files changed, 40 insertions(+), 11 deletions(-) create mode 100644 src/main/resources/templates/html/room_selection.html diff --git a/src/main/resources/html/admin/teacher.html b/src/main/resources/html/admin/teacher.html index e6c43f5..96eb3ee 100644 --- a/src/main/resources/html/admin/teacher.html +++ b/src/main/resources/html/admin/teacher.html @@ -19,9 +19,7 @@

Lehrer bearbeiten

- %[class_info] - %[subject_info] - %[room_info] + %[teacher_infos]
\ No newline at end of file diff --git a/src/main/resources/meta/dynamic/dynamic_elements.json b/src/main/resources/meta/dynamic/dynamic_elements.json index 9f25510..c3c7475 100644 --- a/src/main/resources/meta/dynamic/dynamic_elements.json +++ b/src/main/resources/meta/dynamic/dynamic_elements.json @@ -2,5 +2,23 @@ { "type": "STUDENT_HEADER", "template": "student_header_builtin" + }, + + { + "type": "STUDENT_TOP", + "template": "room_selection" + }, + + { + "type": "TEACHER_INFOS", + "template": "class_info" + }, + { + "type": "TEACHER_INFOS", + "template": "subject_info" + }, + { + "type": "TEACHER_INFOS", + "template": "room_info" } ] \ No newline at end of file diff --git a/src/main/resources/meta/dynamic/dynamic_field_types.json b/src/main/resources/meta/dynamic/dynamic_field_types.json index a2a6757..e457ceb 100644 --- a/src/main/resources/meta/dynamic/dynamic_field_types.json +++ b/src/main/resources/meta/dynamic/dynamic_field_types.json @@ -1,3 +1,5 @@ [ - "STUDENT_HEADER" + "STUDENT_HEADER", + "STUDENT_TOP", + "TEACHER_INFOS" ] \ No newline at end of file diff --git a/src/main/resources/meta/templates/templates.json b/src/main/resources/meta/templates/templates.json index 3e854a1..7afddcd 100644 --- a/src/main/resources/meta/templates/templates.json +++ b/src/main/resources/meta/templates/templates.json @@ -31,6 +31,10 @@ "type": "HTMLFileTemplate", "path": "student_header" }, + "room_selection": { + "type": "HTMLFileTemplate", + "path": "room_selection" + }, "admin_dashboard_nav": { "type": "HTMLNavigationTemplate", @@ -101,5 +105,13 @@ "student_header": { "type": "DynamicHTMLTemplate", "dynamic_field_type": "STUDENT_HEADER" + }, + "student_top": { + "type": "DynamicHTMLTemplate", + "dynamic_field_type": "STUDENT_TOP" + }, + "teacher_infos": { + "type": "DynamicHTMLTemplate", + "dynamic_field_type": "TEACHER_INFOS" } } \ No newline at end of file diff --git a/src/main/resources/templates/html/room_selection.html b/src/main/resources/templates/html/room_selection.html new file mode 100644 index 0000000..a5150e7 --- /dev/null +++ b/src/main/resources/templates/html/room_selection.html @@ -0,0 +1,4 @@ +
+ + +
\ No newline at end of file diff --git a/src/main/resources/templates/html/student_dashboard.html b/src/main/resources/templates/html/student_dashboard.html index 88a92f0..abbb85b 100644 --- a/src/main/resources/templates/html/student_dashboard.html +++ b/src/main/resources/templates/html/student_dashboard.html @@ -3,10 +3,7 @@
%[student_header]
-
- - -
+ %[student_top]

Fächer

From ca64da1543c280f922610f8f852b970b9725badf Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Tue, 31 Mar 2026 19:45:49 +0200 Subject: [PATCH 04/26] Moved rooms to external plugin --- .../de/igslandstuhl/database/api/Room.java | 240 ------------------ .../de/igslandstuhl/database/api/Student.java | 22 -- .../igslandstuhl/database/server/Server.java | 3 - .../database/server/commands/Command.java | 65 ----- .../handlers/PostRequestHandler.java | 46 +--- .../webserver/requests/APIPostRequest.java | 6 - .../resources/html/admin/manage_rooms.html | 46 ---- .../resources/js/site/student-database.js | 49 ---- .../meta/dynamic/dynamic_elements.json | 9 - .../meta/navigation/navigation_elements.json | 5 - src/main/resources/meta/paths/get_paths.json | 28 -- .../resources/meta/templates/templates.json | 8 - src/main/resources/sql/pushes/add_room.sql | 5 - src/main/resources/sql/pushes/delete_room.sql | 2 - .../resources/sql/queries/get_all_rooms.sql | 1 - .../sql/queries/get_room_by_label.sql | 3 - src/main/resources/sql/tables/rooms.sql | 4 - .../resources/templates/html/room_info.html | 20 -- .../templates/html/room_selection.html | 4 - .../igslandstuhl/database/api/RoomTest.java | 43 ---- 20 files changed, 2 insertions(+), 607 deletions(-) delete mode 100644 src/main/java/de/igslandstuhl/database/api/Room.java delete mode 100644 src/main/resources/html/admin/manage_rooms.html delete mode 100644 src/main/resources/sql/pushes/add_room.sql delete mode 100644 src/main/resources/sql/pushes/delete_room.sql delete mode 100644 src/main/resources/sql/queries/get_all_rooms.sql delete mode 100644 src/main/resources/sql/queries/get_room_by_label.sql delete mode 100644 src/main/resources/sql/tables/rooms.sql delete mode 100644 src/main/resources/templates/html/room_info.html delete mode 100644 src/main/resources/templates/html/room_selection.html delete mode 100644 src/test/java/de/igslandstuhl/database/api/RoomTest.java diff --git a/src/main/java/de/igslandstuhl/database/api/Room.java b/src/main/java/de/igslandstuhl/database/api/Room.java deleted file mode 100644 index 9919a6c..0000000 --- a/src/main/java/de/igslandstuhl/database/api/Room.java +++ /dev/null @@ -1,240 +0,0 @@ -package de.igslandstuhl.database.api; - -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import de.igslandstuhl.database.server.Server; -import de.igslandstuhl.database.server.sql.SQLHelper; - -/** - * Represents a room in the system. - * Each room has a label and a minimum level required for students to access it. - */ -public class Room implements APIObject { - private static final String[] SQL_FIELDS = {"label", "minimum_level"}; - /** - * A map to store all rooms, keyed by their label. - * This allows for quick access to room information without repeated database queries. - */ - private static final Map rooms = new HashMap<>(); - /** - * The label of the room, which is a unique identifier. - */ - private final String label; - /** - * The minimum level required for students to access this room. - * This is used to determine if a student is eligible to enter the room. - */ - private final int minimumLevel; - - /** - * Constructs a new Room. - * @param label the label of the room - * @param minimumLevel the minimum level required to access the room - */ - private Room(String label, int minimumLevel) { - this.label = label; - this.minimumLevel = minimumLevel; - } - /** - * Creates a Room instance from SQL result fields. - * This method is used to convert the result of a database query into a Room object. - * @param sqlResult the result fields from the SQL query - * @return a Room object constructed from the SQL fields - * @see Room#SQL_FIELDS - */ - private static Room fromSQLFields(String[] sqlResult) { - String label = sqlResult[0]; - int minimumLevel = Integer.parseInt(sqlResult[1]); - return new Room(label, minimumLevel); - } - /** - * Fetches all rooms from the database and populates the static map. - * This method retrieves all room records and stores them in the `rooms` map for quick access. - * @throws SQLException if there is an error accessing the database - */ - public static void fetchAll() throws SQLException { - rooms.clear(); - Server.getInstance().processRequest((fields) -> { - Room room = fromSQLFields(fields); - rooms.put(room.getLabel(), room); - }, "get_all_rooms", SQL_FIELDS); - } - /** - * Checks if the rooms map is empty and fetches all rooms if it is. - * This method ensures that the rooms are loaded into memory only once, - * preventing unnecessary database queries in subsequent calls. - * @throws SQLException if there is an error accessing the database - */ - public static void fetchAllIfNotExists() throws SQLException { - if (rooms.size() == 0) { - fetchAll(); - } - } - - /** - * Returns a map of all rooms. - * This method ensures that all rooms are fetched from the database if they haven't been loaded yet. - * @return a map of room labels to Room objects - * @throws IllegalStateException if there is an error fetching rooms from the database - */ - public static Map getRooms() { - try { - fetchAllIfNotExists(); - } catch (SQLException e) { - throw new IllegalStateException("Could not fetch rooms", e); - } - return rooms; - } - /** - * Retrieves a room by its label. - * This method checks if the room is already in the static map; if not, it fetches it from the database. - * @param label the label of the room to retrieve - * @return the Room object corresponding to the label, or null if not found - */ - public static Room getRoom(String label) { - if (rooms.keySet().contains(label)) { - return rooms.get(label); - } else { - try { - Room room = Server.getInstance().processSingleRequest(Room::fromSQLFields, "get_room_by_label", SQL_FIELDS, label); - if (room == null) { - return null; - } - rooms.put(label, room); - return room; - } catch (SQLException e) { - e.printStackTrace(); - return null; - } - } - } - /** - * Adds a new room to the database and the static map. - * This method creates a new Room object, inserts it into the database, - * and adds it to the `rooms` map for future access. - * @param label the label of the new room - * @param minimumLevel the minimum level required to access the new room - * @return the newly created Room object - * @throws SQLException if there is an error inserting the room into the database - */ - public static Room addRoom(String label, int minimumLevel) throws SQLException { - Room room = new Room(label, minimumLevel); - Server.getInstance().getConnection().executeVoidProcessSecure(SQLHelper.getAddObjectProcess("room", label, String.valueOf(minimumLevel))); - rooms.put(label, room); - return room; - } - public void delete() throws SQLException { - Server.getInstance().getConnection().executeVoidProcessSecure(SQLHelper.getDeleteObjectProcess("room", getLabel())); - rooms.remove(getLabel()); - } - /** - * Returns the label of the room. - * This is used to identify the room in various operations. - * @return the label of the room - */ - public String getLabel() { - return label; - } - /** - * Returns the minimum level required to access the room. - * This is used to determine if a student meets the requirements to enter the room. - * @return the minimum level required for access - */ - public int getMinimumLevel() { - return minimumLevel; - } - - public Room setMinimumLevel(int level) throws SQLException { - if (level < 0 || level > 3) throw new IllegalArgumentException("Level " + level + " out of range"); - Server.getInstance().getConnection().executeVoidProcessSecure(SQLHelper.getUpdateObjectProcess("level_of_room", getLabel(), String.valueOf(level))); - rooms.remove(getLabel()); - return getRoom(getLabel()); - } - - @Override - public String toString() { - return "{\"label\": \""+label+ "\", \"minimumLevel\": \"" + minimumLevel + "\"}"; - } - /** - * Adds multiple rooms to the database and the static map. - * This method allows for batch creation of rooms, ensuring that all rooms are added in a single operation. - * @param labels a list of room labels - * @param minimumLevels a list of minimum levels corresponding to each room - * @return a list of Room objects created - * @throws SQLException if there is an error inserting any of the rooms into the database - */ - public static List addAllRooms(List labels, List minimumLevels) throws SQLException { - if (labels.size() != minimumLevels.size()) { - throw new IllegalArgumentException("Labels and minimum levels must have the same size"); - } - List rooms = new ArrayList<>(); - for (int i = 0; i < labels.size(); i++) { - rooms.add(addRoom(labels.get(i), minimumLevels.get(i))); - } - return rooms; - } - /** - * Generates a list of Room objects from a CSV string. - * This method parses the CSV data and creates Room objects for each entry. - * @param csv the CSV string containing room data - * @return an array of Room objects created from the CSV data - */ - public static Room[] generateRoomsFromCSV(String csv) throws SQLException, IllegalArgumentException { - String[] lines = csv.split("\n"); - List labels = new ArrayList<>(); - List minimumLevels = new ArrayList<>(); - for (int i = 0; i < lines.length; i++) { - String[] parts = lines[i].split(","); - if (parts.length != 2) { - throw new IllegalArgumentException("Invalid CSV format for room: " + lines[i]); - } - String label = parts[0].trim(); - int minimumLevel; - try { - minimumLevel = Integer.parseInt(parts[1].trim()); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Invalid minimum level for room: " + lines[i], e); - } - labels.add(label); - minimumLevels.add(minimumLevel); - } - List rooms = Room.addAllRooms(labels, minimumLevels); - return rooms.toArray(new Room[rooms.size()]); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((label == null) ? 0 : label.hashCode()); - result = prime * result + minimumLevel; - return result; - } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Room other = (Room) obj; - if (label == null) { - if (other.label != null) - return false; - } else if (!label.equals(other.label)) - return false; - if (minimumLevel != other.minimumLevel) - return false; - return true; - } - @Override - public String toJSON() { - return "{\"label\": \""+label+ "\", \"minimumLevel\": \"" + minimumLevel + "\"}"; - } - -} diff --git a/src/main/java/de/igslandstuhl/database/api/Student.java b/src/main/java/de/igslandstuhl/database/api/Student.java index 79eb120..933b89b 100644 --- a/src/main/java/de/igslandstuhl/database/api/Student.java +++ b/src/main/java/de/igslandstuhl/database/api/Student.java @@ -87,11 +87,6 @@ public class Student extends User { */ private final Map currentTopics = new ConcurrentHashMap<>(); - /** - * The current room of the student. - */ - private Room currentRoom = null; - /** * Constructs a new Student. * @@ -223,10 +218,6 @@ public static List getAll() { .collect(Collectors.toList()); } - public static List getByRoom(Room room) { - return students.values().stream().filter((s) -> room.equals(s.getCurrentRoom())).toList(); - } - /** * Registers a new student with a password. * This method creates a new student in the database and returns the created Student object. @@ -352,18 +343,6 @@ public String getUsername() { */ public GraduationLevel getGraduationLevel() { return graduationLevel; } - /** - * Returns the student's current room. - * @return the current room - */ - public Room getCurrentRoom() { return currentRoom; } - - /** - * Sets the student's current room. - * @param currentRoom the new room - */ - public void setCurrentRoom(Room currentRoom) { this.currentRoom = currentRoom; } - /** * Returns the set of selected tasks. * @return selected tasks @@ -553,7 +532,6 @@ public String toJSON() { .append("\"selectedTasks\": ").append(selectedTasks).append(",\n") .append("\"completedTasks\": ").append(completedTasks).append(",\n") .append("\"lockedTasks\": ").append(lockedTasks).append(",\n") - .append("\"currentRoom\": ").append(String.valueOf(currentRoom)).append(",\n") .append("\"currentRequests\": {").append(currentRequests.entrySet().stream() .map(entry -> "\"" + entry.getKey() + "\": " + entry.getValue().stream().map((r) -> '"' + r.getGermanTranslation() + '"').toList()) .reduce((a, b) -> a + ", " + b).orElse("")).append("},\n") diff --git a/src/main/java/de/igslandstuhl/database/server/Server.java b/src/main/java/de/igslandstuhl/database/server/Server.java index a4b2f98..e669d53 100644 --- a/src/main/java/de/igslandstuhl/database/server/Server.java +++ b/src/main/java/de/igslandstuhl/database/server/Server.java @@ -13,7 +13,6 @@ import org.apache.commons.codec.digest.DigestUtils; import de.igslandstuhl.database.Application; -import de.igslandstuhl.database.api.Room; import de.igslandstuhl.database.api.SchoolClass; import de.igslandstuhl.database.api.Student; import de.igslandstuhl.database.api.Subject; @@ -209,8 +208,6 @@ public String getSQLResource(String username, String resource) { if (resource.equals("mydata")) { User user = User.getUser(username); return user.toJSON(); - } else if (resource.equals("rooms")) { - return new HashSet<>(Room.getRooms().values()).toString(); } else if (resource.equals("mysubjects")) { User user = User.getUser(username); if (user instanceof Student student) { diff --git a/src/main/java/de/igslandstuhl/database/server/commands/Command.java b/src/main/java/de/igslandstuhl/database/server/commands/Command.java index 795833d..38469b1 100644 --- a/src/main/java/de/igslandstuhl/database/server/commands/Command.java +++ b/src/main/java/de/igslandstuhl/database/server/commands/Command.java @@ -78,71 +78,6 @@ public static void registerCommands() { return String.valueOf(level.getRatio() * 100) + "%"; }, new CommandDescription("get-level-ratio", "Gets the ratio of a task level", "get-level-ratio [level]")); - // Room commands - registerCommand("list-rooms", (args) -> { - try { - Room.fetchAll(); - } catch (SQLException e) { - return "Error while trying to access database:\n" + CommonUtils.getStacktrace(e); - } - return Room.getRooms().keySet().stream().reduce("Rooms:", (s1, s2) -> s1 + "\n" + s2); - }, new CommandDescription("list-rooms", "Lists all available rooms", "list-rooms")); - registerCommand("get-room-level", (args) -> { - if (args.length < 1) return "Usage: get-room-level [room]"; - Room room = Room.getRoom(argsPart(args, 0, args.length)); - if (room == null) return "Room not found. Try list-rooms for a list of available rooms"; - return "Room " + room.getLabel() + " has access level " + room.getMinimumLevel(); - }, new CommandDescription("get-room-level", "Gets the minimum level required to access a room", "get-room-level [room]")); - registerCommand("set-room-level", (args) -> { - if (args.length < 2) return "Usage: set-room-level [room] [level]"; - Room room = Room.getRoom(argsPart(args, 0, args.length-1)); - if (room == null) return "Room not found. Try list-rooms for a list of available rooms"; - int level; - try { - level = Integer.parseInt(args[args.length - 1]); - } catch (NumberFormatException e) { - return args[1] + " is not a valid number."; - } - try { - room.setMinimumLevel(level); - } catch (SQLException e) { - return "Error while trying to access database: \n" + CommonUtils.getStacktrace(e); - } catch (IllegalArgumentException e) { - return e.getMessage(); - } - return "Successfully changed room level"; - }, new CommandDescription("set-room-level", "Sets the minimum level required to access a room", "set-room-level [room] [level]")); - registerCommand("add-room", (args) -> { - if (args.length < 2) return "Usage: add-room [room] [level]"; - if (Room.getRoom(args[0]) != null) return "Room already present"; - - try { - String label = argsPart(args, 0, args.length-1); - int level = Integer.parseInt(args[args.length-1]); - - Room.addRoom(label, level); - } catch (NumberFormatException e) { - return args[args.length - 1] + " is not a valid number."; - } catch (IllegalArgumentException e) { - return e.getMessage(); - } catch (SQLException e) { - throw new IllegalStateException(e); - } - return "Room successfully added"; - }, new CommandDescription("add-room", "Adds a new room", "add-room [room] [level]")); - registerCommand("remove-room", (args) -> { - if (args.length < 1) return "Usage: remove-room [room]"; - - Room room = Room.getRoom(argsPart(args, 0, args.length)); - try { - room.delete(); - } catch (SQLException e) { - return "Error while trying to access database: \n" + CommonUtils.getStacktrace(e); - } - return "Room successfully deleted"; - }, new CommandDescription("remove-room", "Removes a room", "remove-room [room]")); - - // class commands registerCommand("list-classes", (args) -> { return SchoolClass.getAll().stream().map(SchoolClass::getLabel).reduce("Classes:", (s1,s2) -> s1 + "\n" + s2); diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java index 6b8d4e3..5bbb557 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java @@ -20,7 +20,6 @@ import de.igslandstuhl.database.Application; import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.api.APIObject; -import de.igslandstuhl.database.api.Room; import de.igslandstuhl.database.api.SchoolClass; import de.igslandstuhl.database.api.Student; import de.igslandstuhl.database.api.Subject; @@ -205,15 +204,6 @@ public static void registerHandlers() { } }, PostRequestHandler::csvResult) ); - HttpHandler.registerPostRequestHandler("/add-rooms", AccessLevel.ADMIN, (rq) -> - handleBatchInsertCSV(rq, "rooms", ContentType.JSON, t -> { - try { - return Room.generateRoomsFromCSV(t); - } catch (SQLException e) { - throw new IllegalStateException(e); - } - }, Arrays::toString) - ); HttpHandler.registerPostRequestHandler("/add-teacher", AccessLevel.ADMIN, (rq) -> { String firstName = prepare(rq.getString("firstName")); String lastName = prepare(rq.getString("lastName")); @@ -271,14 +261,6 @@ public static void registerHandlers() { HttpHandler.registerPostRequestHandler("/tasks", AccessLevel.USER, (rq) -> { return PostResponse.ok(JSONUtils.toJSON(rq.getTaskList()), ContentType.JSON, rq); }); - HttpHandler.registerPostRequestHandler("/update-room", AccessLevel.USER, (rq) -> { - Student student = rq.getCurrentStudent(); - if (student == null) return PostResponse.unauthorized(rq); - Room room = rq.getRoom(); - if (room == null) return PostResponse.badRequest("Room not found", rq); - student.setCurrentRoom(room); - return PostResponse.ok("Changed current room", ContentType.TEXT_PLAIN, rq); - }); HttpHandler.registerPostRequestHandler("/begin-task", AccessLevel.USER, (rq) -> handleTaskChange(rq, Task.STATUS_IN_PROGRESS)); HttpHandler.registerPostRequestHandler("/complete-task", AccessLevel.USER, (rq) -> handleTaskChange(rq, Task.STATUS_COMPLETED)); HttpHandler.registerPostRequestHandler("/cancel-task", AccessLevel.USER, (rq) -> handleTaskChange(rq, Task.STATUS_NOT_STARTED)); @@ -301,30 +283,7 @@ public static void registerHandlers() { .addProperty("id", student.getId()) .addProperty("name", student.getFirstName() + " " + student.getLastName()) .addProperty("actionRequired", student.isActionRequired()) - .addProperty("graduationLevel", student.getGraduationLevel()) - .addProperty("room", student.getCurrentRoom() != null ? student.getCurrentRoom().getLabel() : "None"); - if (rq.getJson().containsKey("subjectId") && rq.getSubject() != null) { - Set subjectRequests = student.getCurrentRequests(rq.getSubject()); - builder.addProperty("experiment",subjectRequests.stream().anyMatch(r -> r == SubjectRequest.EXPERIMENT)) - .addProperty("help", subjectRequests.stream().anyMatch(r -> r == SubjectRequest.HELP)) - .addProperty("test", subjectRequests.stream().anyMatch(r -> r == SubjectRequest.EXAM)) - .addProperty("partner", subjectRequests.stream().anyMatch(r -> r == SubjectRequest.PARTNER)); - } - }), - ContentType.JSON, rq - ); - }); - HttpHandler.registerPostRequestHandler("/get-students-by-room", AccessLevel.TEACHER, (rq) -> { - Room room = rq.getRoom(); - List students = Student.getByRoom(room); - return PostResponse.ok( - JSONUtils.toJSON(students, (student, builder) -> { - builder - .addProperty("id", student.getId()) - .addProperty("name", student.getFirstName() + " " + student.getLastName()) - .addProperty("actionRequired", student.isActionRequired()) - .addProperty("graduationLevel", student.getGraduationLevel()) - .addProperty("room", student.getCurrentRoom() != null ? student.getCurrentRoom().getLabel() : "None"); + .addProperty("graduationLevel", student.getGraduationLevel()); if (rq.getJson().containsKey("subjectId") && rq.getSubject() != null) { Set subjectRequests = student.getCurrentRequests(rq.getSubject()); builder.addProperty("experiment",subjectRequests.stream().anyMatch(r -> r == SubjectRequest.EXPERIMENT)) @@ -364,8 +323,7 @@ public static void registerHandlers() { .toList(); return PostResponse.ok(JSONUtils.toJSON(students, (partner, builder) -> { builder.addProperty("id", partner.getId()) - .addProperty("name", partner.getFirstName() + " " + partner.getLastName()) - .addProperty("room", partner.getCurrentRoom() != null ? partner.getCurrentRoom().getLabel() : "None"); + .addProperty("name", partner.getFirstName() + " " + partner.getLastName()); }), ContentType.JSON, rq); }); HttpHandler.registerPostRequestHandler("/delete-subject", AccessLevel.ADMIN, (rq) -> diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/requests/APIPostRequest.java b/src/main/java/de/igslandstuhl/database/server/webserver/requests/APIPostRequest.java index 72edc41..2c070a4 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/requests/APIPostRequest.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/requests/APIPostRequest.java @@ -7,7 +7,6 @@ import com.google.gson.reflect.TypeToken; import de.igslandstuhl.database.api.APIObject; -import de.igslandstuhl.database.api.Room; import de.igslandstuhl.database.api.SchoolClass; import de.igslandstuhl.database.api.Student; import de.igslandstuhl.database.api.Subject; @@ -58,9 +57,6 @@ public Topic getTopic() { public SubjectRequest getSubjectRequest() { return SubjectRequest.fromGermanTranslation(getString("subjectRequest")); } - public Room getRoom() { - return Room.getRoom(getString("room")); - } public Task getTask() { return Task.get(getInt("taskId")); } @@ -86,8 +82,6 @@ public T getAPIObject(TypeToken type) { return (T) getSubjectRequest(); } else if (rawType.getTypeName().contains("Task")) { return (T) getTask(); - } else if (rawType.getTypeName().contains("Room")) { - return (T) getRoom(); } else if (rawType.getTypeName().contains("SchoolClass")) { return (T) getSchoolClass(); } else { diff --git a/src/main/resources/html/admin/manage_rooms.html b/src/main/resources/html/admin/manage_rooms.html deleted file mode 100644 index bda0d6d..0000000 --- a/src/main/resources/html/admin/manage_rooms.html +++ /dev/null @@ -1,46 +0,0 @@ -%[site;title=Raumverwaltung;content=!FOLLOWS] -
-
-

Raumverwaltung

-
-
-
-

Räume hinzufügen

-
- - - -
-
-
-

Raumliste

- - - - - - - - - - -
RaumnameMindestlevel
-
-
- -
- \ No newline at end of file diff --git a/src/main/resources/js/site/student-database.js b/src/main/resources/js/site/student-database.js index ec439b1..0c24c10 100644 --- a/src/main/resources/js/site/student-database.js +++ b/src/main/resources/js/site/student-database.js @@ -50,10 +50,6 @@ async function fetchMyClasses() { const classes = await fetchJson('/myclasses'); return classes; } -async function fetchRooms() { - const rooms = await fetchJson('/rooms'); - return rooms; -} async function fetchTeacherClasses(teacherId) { const classes = await getJsonWithPost('/teacher-classes', { teacherId }); return classes; @@ -108,9 +104,6 @@ async function getStudents(classId) { async function getStudentsBySubject(classId, subjectId) { return await getJsonWithPost('/student-list', { classId, subjectId }); } -async function getStudentsByRoom(room) { - return await getJsonWithPost('/get-students-by-room', { room }); -} async function searchPartner(subjectId, topicId, classId, studentId) { return await getJsonWithPost('/search-partner', { subjectId, topicId, classId, studentId}); } @@ -159,9 +152,6 @@ async function reopenTask(studentId, taskId) { async function beginTask(studentId, taskId) { return await post('/begin-task', { studentId, taskId }); } -async function updateRoom(studentId, room) { - return await post('/update-room', { studentId, room }); -} async function togglePlugin(pluginKey) { return await post('/toggle-plugin', { key: pluginKey }); } @@ -221,21 +211,6 @@ async function populateSubjectStudentList(subjectSelectId, classSelectId, studen studentTable.appendChild(row); }); } -async function populateRoomStudentList(room) { - const students = await getStudentsByRoom(room); - - const studentTable = document.getElementById("roomStudentTableBody"); - studentTable.innerHTML = ""; // clear previous rows - students.forEach(student => { - const row = document.createElement('tr'); - row.innerHTML = ` - ${student.name} - ${student.actionRequired ? "Ja" : "Nein"} - - `; - studentTable.appendChild(row); - }); -} async function populatePartnerSubjectStudentList(subjectId, studentData) { const topicId = (await fetchMyCurrentTopic(subjectId)).id; const classId = studentData.schoolClass.id; @@ -310,30 +285,6 @@ async function populateGradeSelect(gradeSelectId, subjectId) { gradeSelect.appendChild(option) }) } -async function populateRoomSelect(roomSelectId) { - const roomSelect = document.getElementById(roomSelectId); - roomSelect.innerHTML = ""; // clear previous options if any - const rooms = await fetchRooms(); - rooms.forEach(room => { - const option = document.createElement('option'); - option.value = room.label; - option.textContent = room.label; - roomSelect.appendChild(option); - }); -} -async function populateRoomSelectWithLevel(roomSelectId, graduationLevel) { - const roomSelect = document.getElementById(roomSelectId); - roomSelect.innerHTML = ""; // clear previous options if any - const rooms = await fetchRooms(); - rooms.forEach(room => { - if (room.minimumLevel <= graduationLevel){ - const option = document.createElement('option'); - option.value = room.label; - option.textContent = room.label; - roomSelect.appendChild(option); - } - }); -} async function populateSubjectList(subjectListId, classId) { const subjectList = document.getElementById(subjectListId); const subjects = await fetchJson("/class-subjects", { diff --git a/src/main/resources/meta/dynamic/dynamic_elements.json b/src/main/resources/meta/dynamic/dynamic_elements.json index c3c7475..d095c99 100644 --- a/src/main/resources/meta/dynamic/dynamic_elements.json +++ b/src/main/resources/meta/dynamic/dynamic_elements.json @@ -4,11 +4,6 @@ "template": "student_header_builtin" }, - { - "type": "STUDENT_TOP", - "template": "room_selection" - }, - { "type": "TEACHER_INFOS", "template": "class_info" @@ -16,9 +11,5 @@ { "type": "TEACHER_INFOS", "template": "subject_info" - }, - { - "type": "TEACHER_INFOS", - "template": "room_info" } ] \ No newline at end of file diff --git a/src/main/resources/meta/navigation/navigation_elements.json b/src/main/resources/meta/navigation/navigation_elements.json index 530ef9c..90aa2ce 100644 --- a/src/main/resources/meta/navigation/navigation_elements.json +++ b/src/main/resources/meta/navigation/navigation_elements.json @@ -4,11 +4,6 @@ "path": "/manage_classes", "label": "Klassen verwalten" }, - { - "type": "ADMIN_DASHBOARD", - "path": "/manage_rooms", - "label": "Räume verwalten" - }, { "type": "ADMIN_DASHBOARD", "path": "/manage_students", diff --git a/src/main/resources/meta/paths/get_paths.json b/src/main/resources/meta/paths/get_paths.json index 137e12a..0cee789 100644 --- a/src/main/resources/meta/paths/get_paths.json +++ b/src/main/resources/meta/paths/get_paths.json @@ -6,13 +6,6 @@ "context": "virtual", "access_level": "user" }, - "/rooms": { - "type": "GET", - "handler_type": "SQLRequestHandler", - "namespaces": ["sql"], - "context": "virtual", - "access_level": "public" - }, "/mysubjects": { "type": "GET", "handler_type": "SQLRequestHandler", @@ -136,13 +129,6 @@ "context": "html", "access_level": "admin" }, - "/manage_rooms": { - "type": "GET", - "handler_type": "TemplatingFileRequestHandler", - "namespaces": ["admin"], - "context": "html", - "access_level": "admin" - }, "/editor": { "type": "GET", "handler_type": "TemplatingFileRequestHandler", @@ -158,13 +144,6 @@ "context": "html", "access_level": "admin" }, - "/room": { - "type": "GET", - "handler_type": "TemplatingFileRequestHandler", - "namespaces": ["admin"], - "context": "html", - "access_level": "admin" - }, "/subject": { "type": "GET", "handler_type": "TemplatingFileRequestHandler", @@ -252,13 +231,6 @@ "context": "js", "access_level": "admin" }, - "/build_room.js": { - "type": "GET", - "handler_type": "FileRequestHandler", - "namespaces": ["admin"], - "context": "js", - "access_level": "admin" - }, "/build_subject.js": { "type": "GET", "handler_type": "FileRequestHandler", diff --git a/src/main/resources/meta/templates/templates.json b/src/main/resources/meta/templates/templates.json index 7afddcd..f07031f 100644 --- a/src/main/resources/meta/templates/templates.json +++ b/src/main/resources/meta/templates/templates.json @@ -11,10 +11,6 @@ "type": "HTMLFileTemplate", "path": "login" }, - "room_info": { - "type": "HTMLFileTemplate", - "path": "room_info" - }, "site": { "type": "HTMLFileTemplate", "path": "site" @@ -31,10 +27,6 @@ "type": "HTMLFileTemplate", "path": "student_header" }, - "room_selection": { - "type": "HTMLFileTemplate", - "path": "room_selection" - }, "admin_dashboard_nav": { "type": "HTMLNavigationTemplate", diff --git a/src/main/resources/sql/pushes/add_room.sql b/src/main/resources/sql/pushes/add_room.sql deleted file mode 100644 index 1470ab2..0000000 --- a/src/main/resources/sql/pushes/add_room.sql +++ /dev/null @@ -1,5 +0,0 @@ -INSERT INTO rooms (label, minimum_level) -VALUES (?, ?) -ON CONFLICT(label) DO UPDATE SET - label = excluded.label, - minimum_level = excluded.minimum_level \ No newline at end of file diff --git a/src/main/resources/sql/pushes/delete_room.sql b/src/main/resources/sql/pushes/delete_room.sql deleted file mode 100644 index 7065216..0000000 --- a/src/main/resources/sql/pushes/delete_room.sql +++ /dev/null @@ -1,2 +0,0 @@ -DELETE FROM rooms -WHERE label = ? \ No newline at end of file diff --git a/src/main/resources/sql/queries/get_all_rooms.sql b/src/main/resources/sql/queries/get_all_rooms.sql deleted file mode 100644 index ff39647..0000000 --- a/src/main/resources/sql/queries/get_all_rooms.sql +++ /dev/null @@ -1 +0,0 @@ -SELECT * FROM rooms \ No newline at end of file diff --git a/src/main/resources/sql/queries/get_room_by_label.sql b/src/main/resources/sql/queries/get_room_by_label.sql deleted file mode 100644 index bb49047..0000000 --- a/src/main/resources/sql/queries/get_room_by_label.sql +++ /dev/null @@ -1,3 +0,0 @@ -SELECT * -FROM rooms -WHERE label=? \ No newline at end of file diff --git a/src/main/resources/sql/tables/rooms.sql b/src/main/resources/sql/tables/rooms.sql deleted file mode 100644 index a34fa52..0000000 --- a/src/main/resources/sql/tables/rooms.sql +++ /dev/null @@ -1,4 +0,0 @@ -CREATE TABLE IF NOT EXISTS rooms ( - label TEXT PRIMARY KEY, - minimum_level INTEGER NOT NULL -) \ No newline at end of file diff --git a/src/main/resources/templates/html/room_info.html b/src/main/resources/templates/html/room_info.html deleted file mode 100644 index 46a5a9b..0000000 --- a/src/main/resources/templates/html/room_info.html +++ /dev/null @@ -1,20 +0,0 @@ -
-

Raumübersicht

-
- - -
-
-

Schüler im Raum:

- - - - - - - - - -
NameBraucht Unterstützung
-
-
\ No newline at end of file diff --git a/src/main/resources/templates/html/room_selection.html b/src/main/resources/templates/html/room_selection.html deleted file mode 100644 index a5150e7..0000000 --- a/src/main/resources/templates/html/room_selection.html +++ /dev/null @@ -1,4 +0,0 @@ -
- - -
\ No newline at end of file diff --git a/src/test/java/de/igslandstuhl/database/api/RoomTest.java b/src/test/java/de/igslandstuhl/database/api/RoomTest.java deleted file mode 100644 index d79681f..0000000 --- a/src/test/java/de/igslandstuhl/database/api/RoomTest.java +++ /dev/null @@ -1,43 +0,0 @@ -package de.igslandstuhl.database.api; - -import static org.junit.jupiter.api.Assertions.*; - -import java.sql.SQLException; -import java.util.List; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import de.igslandstuhl.database.server.Server; - -public class RoomTest { - Server server; - @BeforeEach - public void setupServer() throws SQLException { - PreConditions.setupDatabase(); - server = Server.getInstance(); - } - @Test - public void addRoom() throws SQLException { - Room room = Room.addRoom("Gelingensnachweis", 0); - assertNotNull(room); - assertEquals("Gelingensnachweis", room.getLabel()); - assertEquals(0, room.getMinimumLevel()); - } - @Test - public void getRoom() throws SQLException { - Room added = Room.addRoom("Gelingensnachweis", 0); - Room room = Room.getRoom("Gelingensnachweis"); - assertNotNull(room); - assertEquals(added, room); - } - @Test - public void addAllRooms() throws SQLException { - List rooms = Room.addAllRooms( - List.of("5 Einzelarbeitsraum", "5 Teamarbeitsraum", "5 Inputraum groß", "5 Inputraum klein", - "5 Gruppenarbeitsraum 1", "5 Gruppenarbeitsraum 2", "5 Gruppenarbeitsraum 3"), - List.of(0, 0, 0, 0, 0, 0, 0) - ); - assertEquals(7, rooms.size()); - } -} From 7bb34738bfda26656cbd5874ded5f574c22640ca Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Tue, 31 Mar 2026 20:08:59 +0200 Subject: [PATCH 05/26] Also removed rooms from javascript Introduced a few javascript events that will be necessary for the room plugin --- .../resources/js/site/student-database.js | 51 +++++++++++-------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/src/main/resources/js/site/student-database.js b/src/main/resources/js/site/student-database.js index 0c24c10..3104254 100644 --- a/src/main/resources/js/site/student-database.js +++ b/src/main/resources/js/site/student-database.js @@ -165,6 +165,29 @@ async function deleteClass(classId) { async function deleteSubject(subjectId) { return await post('/delete-subject', { id: subjectId }); } + +// Events +function populateStudentRowEvent(row, student) { + const event = new CustomEvent("populate-student-row", { detail: {row, student} }); + document.dispatchEvent(event); +} +function populatePartnerRowEvent(row, student) { + const event = new CustomEvent("populate-partner-row", { detail: {row, student} }); + document.dispatchEvent(event); +} +function populateTeacherClassRowEvent(row, student) { + const event = new CustomEvent("populate-teacher-class-row", { detail: { row, student } }); + document.dispatchEvent(event); +} +function teacherDashboardLoadEvent() { + const event = new Event('teacher-dashboard-load'); + document.dispatchEvent(event); +} +function studentDashboardLoadEvent() { + const event = new Event('student-dashboard-load'); + document.dispatchEvent(event); +} + // Populating functions async function populateTable(url, tableId, rowBuilder) { const data = await fetchJson(url); @@ -223,9 +246,9 @@ async function populatePartnerSubjectStudentList(subjectId, studentData) { students.forEach(student => { const row = document.createElement('tr'); row.innerHTML = ` - ${student.name} - ${student.room} + ${student.name} `; + populatePartnerRowEvent(row, student); studentTable.appendChild(row); }); } @@ -373,10 +396,10 @@ async function buildTeacherDashboard(classes, subjects) { populateStudentTable(Number(event.target.value), "studentTable", (row, student) => { row.innerHTML = ` ${student.name} - ${student.room} ${graduationLevels[student.graduationLevel]} `; + populateTeacherClassRowEvent(row, student); }); } @@ -393,9 +416,7 @@ async function buildTeacherDashboard(classes, subjects) { subjectSelect.addEventListener('change', (_) => populateSubjectStudentList('subjectSelect', 'classSelectSubject', 'subjectStudentTable')); populateSubjectStudentList('subjectSelect', 'classSelectSubject', 'subjectStudentTable'); // Trigger initial load - await populateRoomSelect('roomSelect'); - document.getElementById('roomSelect').addEventListener('change', (e) => populateRoomStudentList(e.target.value)); - populateRoomStudentList(document.getElementById('roomSelect').value); // Trigger initial load + teacherDashboardLoadEvent(); } function createRequestButton(subject, type, label) { const btn = document.createElement('button'); @@ -625,26 +646,14 @@ function decodeEntities(str) { function loadStudentDashboard(studentData, subjects, teacherPerms) { // Show student info setStudentInfo(studentData); - // Show rooms - populateRoomSelectWithLevel('room', studentData.graduationLevel); - - // Wait for the browser to render (next tick) - setTimeout(() => { - // Set room select value to current room - if (studentData.currentRoom && studentData.currentRoom.label) { - roomSelect.value = studentData.currentRoom.label; - } - }, 0); - - const roomSelect = document.getElementById('room'); - roomSelect.addEventListener('change', async () => updateRoom(studentData.id, roomSelect.value)); - // Show subjects const subjectList = document.getElementById('subject-list'); subjects.forEach(subject => { const panel = createSubjectPanel(subject, studentData, teacherPerms); subjectList.appendChild(panel); }); + + studentDashboardLoadEvent(); } let plugin_panels = {} function loadPluginSection(pluginKey) { @@ -704,10 +713,10 @@ document.addEventListener('DOMContentLoaded', async () => { populateStudentTable(currentClass.id, 'studentTable', (row, student) => { row.innerHTML = ` ${student.name} - ${student.room} ${graduationLevels[student.graduationLevel]} `; + populateStudentRowEvent(row, student); }) } if (document.getElementById('subjectSelect')) { From 2367ff370d4a0ef1e4779681bb3183333d179068 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Tue, 31 Mar 2026 20:22:33 +0200 Subject: [PATCH 06/26] Added SQLRequestHandler + Registry so plugins can also define sql requests --- .../de/igslandstuhl/database/Application.java | 2 + .../de/igslandstuhl/database/Registry.java | 5 ++ .../igslandstuhl/database/server/Server.java | 45 +--------------- .../handlers/get/SQLRequestHandler.java | 51 +++++++++++++++++++ 4 files changed, 60 insertions(+), 43 deletions(-) create mode 100644 src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java diff --git a/src/main/java/de/igslandstuhl/database/Application.java b/src/main/java/de/igslandstuhl/database/Application.java index d84ca56..19cd206 100644 --- a/src/main/java/de/igslandstuhl/database/Application.java +++ b/src/main/java/de/igslandstuhl/database/Application.java @@ -17,6 +17,7 @@ import de.igslandstuhl.database.server.webserver.WebPath; import de.igslandstuhl.database.server.webserver.handlers.GetRequestHandler; import de.igslandstuhl.database.server.webserver.handlers.PostRequestHandler; +import de.igslandstuhl.database.server.webserver.handlers.get.SQLRequestHandler; import de.igslandstuhl.database.utils.CommandLineUtils; /** @@ -110,6 +111,7 @@ public static void main(String[] args) throws Exception { Holiday.setupCurrentSchoolYear(); PostRequestHandler.registerHandlers(); + SQLRequestHandler.register(); PluginLoader.getInstance().registerPlugins(); WebPath.registerPaths(); diff --git a/src/main/java/de/igslandstuhl/database/Registry.java b/src/main/java/de/igslandstuhl/database/Registry.java index 12e09f8..e0604f0 100644 --- a/src/main/java/de/igslandstuhl/database/Registry.java +++ b/src/main/java/de/igslandstuhl/database/Registry.java @@ -16,6 +16,7 @@ import de.igslandstuhl.database.server.commands.CommandDescription; import de.igslandstuhl.database.server.webserver.WebPath; import de.igslandstuhl.database.server.webserver.handlers.HttpHandler; +import de.igslandstuhl.database.server.webserver.handlers.get.SQLRequestHandler; import de.igslandstuhl.database.server.webserver.requests.APIPostRequest; import de.igslandstuhl.database.server.webserver.requests.GetRequest; import de.igslandstuhl.database.utils.RegistryEnum; @@ -25,6 +26,7 @@ public class Registry implements Closeable { private static final Registry COMMAND_DESCRIPTION_REGISTRY = new Registry<>(); private static final Registry> POST_HANDLER_REGISTRY = new Registry<>(); private static final Registry> GET_HANDLER_REGISTRY = new Registry<>(); + private static final Registry SQL_REQUEST_HANDLER_REGISTRY = new Registry<>(); private static final Registry PLUGIN_REGISTRY = new Registry<>(); private static final Registry WEB_PATH_REGISTRY = new Registry<>(); @@ -41,6 +43,9 @@ public static Registry> postRequestHandlerRe public static Registry> getRequestHandlerRegistry() { return GET_HANDLER_REGISTRY; } + public static Registry sqlRequestHandlerRegistry() { + return SQL_REQUEST_HANDLER_REGISTRY; + } public static Registry pluginRegistry() { return PLUGIN_REGISTRY; } diff --git a/src/main/java/de/igslandstuhl/database/server/Server.java b/src/main/java/de/igslandstuhl/database/server/Server.java index e669d53..df4aafc 100644 --- a/src/main/java/de/igslandstuhl/database/server/Server.java +++ b/src/main/java/de/igslandstuhl/database/server/Server.java @@ -3,24 +3,19 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; -import java.util.HashSet; import java.util.LinkedList; import java.util.List; -import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import org.apache.commons.codec.digest.DigestUtils; import de.igslandstuhl.database.Application; -import de.igslandstuhl.database.api.SchoolClass; -import de.igslandstuhl.database.api.Student; -import de.igslandstuhl.database.api.Subject; -import de.igslandstuhl.database.api.Teacher; import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.server.resources.ResourceManager; import de.igslandstuhl.database.server.sql.SQLHelper; import de.igslandstuhl.database.server.sql.SQLiteConnection; +import de.igslandstuhl.database.server.webserver.handlers.get.SQLRequestHandler; /** * Represents the main server class that handles all incoming requests and manages the database connection. @@ -205,43 +200,7 @@ public boolean isValidUser(String username, String password) { */ public String getSQLResource(String username, String resource) { resource = resource.intern(); - if (resource.equals("mydata")) { - User user = User.getUser(username); - return user.toJSON(); - } else if (resource.equals("mysubjects")) { - User user = User.getUser(username); - if (user instanceof Student student) { - return student.getSchoolClass().getSubjects().toString(); - } else if (user instanceof Teacher teacher) { - return teacher.getSubjects().toString(); - } else { - return null; - } - } else if (resource.equals("myclasses")) { - User user = User.getUser(username); - if (user instanceof Teacher teacher) { - Set classIDs = teacher.getClassIds(); - Set classes = new HashSet<>(); - for (Integer classID : classIDs) { - classes.add("{\"classId\": " + classID + ", \"name\": \"" + SchoolClass.get(classID).getLabel() + "\"}"); - } - return classes.toString(); - } else { - return null; - } - } else if (resource.equals("teachers")) { - return new HashSet<>(Teacher.getAll()).toString(); - } else if (resource.equals("students")) { - return new HashSet<>(Student.getAll()).toString(); - } else if (resource.equals("subjects")) { - return new HashSet<>(Subject.getAll()).toString(); - } else if (resource.equals("classes")) { - return new HashSet<>(SchoolClass.getAll()).toString(); - } else if (resource.equals("all-student-results")) { - return Student.getAllResultsCSV(); - } else { - return null; - } + return SQLRequestHandler.getResource(resource, User.getUser(username)); } @Override diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java new file mode 100644 index 0000000..391c9f4 --- /dev/null +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java @@ -0,0 +1,51 @@ +package de.igslandstuhl.database.server.webserver.handlers.get; + +import java.util.HashSet; +import java.util.Set; + +import de.igslandstuhl.database.Registry; +import de.igslandstuhl.database.api.SchoolClass; +import de.igslandstuhl.database.api.Student; +import de.igslandstuhl.database.api.Subject; +import de.igslandstuhl.database.api.Teacher; +import de.igslandstuhl.database.api.User; + +@FunctionalInterface +public interface SQLRequestHandler { + public String get(User user); + + public static String getResource(String resource, User user) { + return Registry.sqlRequestHandlerRegistry().get(resource).get(user); + } + public static void register() { + Registry.sqlRequestHandlerRegistry().register("mydata", (user) -> user.toJSON()); + + Registry.sqlRequestHandlerRegistry().register("mysubjects", (user) -> { + if (user instanceof Student student) { + return student.getSchoolClass().getSubjects().toString(); + } else if (user instanceof Teacher teacher) { + return teacher.getSubjects().toString(); + } else { + return null; + } + }); + Registry.sqlRequestHandlerRegistry().register("myclasses", (user) -> { + if (user instanceof Teacher teacher) { + Set classIDs = teacher.getClassIds(); + Set classes = new HashSet<>(); + for (Integer classID : classIDs) { + classes.add("{\"classId\": " + classID + ", \"name\": \"" + SchoolClass.get(classID).getLabel() + "\"}"); + } + return classes.toString(); + } else { + return null; + } + }); + + Registry.sqlRequestHandlerRegistry().register("teachers", (user) -> new HashSet<>(Teacher.getAll()).toString()); + Registry.sqlRequestHandlerRegistry().register("students", (user) -> new HashSet<>(Student.getAll()).toString()); + Registry.sqlRequestHandlerRegistry().register("subjects", (user) -> new HashSet<>(Subject.getAll()).toString()); + Registry.sqlRequestHandlerRegistry().register("classes", (user) -> new HashSet<>(SchoolClass.getAll()).toString()); + Registry.sqlRequestHandlerRegistry().register("all-student-resukts", (user) -> Student.getAllResultsCSV()); + } +} From 9b1d5313c42e6bc345a055ca049020abc0812c8b Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Tue, 31 Mar 2026 20:23:50 +0200 Subject: [PATCH 07/26] bumped version to v1.1.0-SNAPSHOT-1 --- build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index 300b4f8..80bab18 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,7 +7,7 @@ plugins { group = "igs-landstuhl" -version = "v1.1.0-SNAPSHOT-0" +version = "v1.1.0-SNAPSHOT-1" application { mainClass.set("de.igslandstuhl.database.Application") From 65743a01dfecaa178c20673704c2468ffc3a7dbf Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Tue, 28 Apr 2026 17:17:13 +0200 Subject: [PATCH 08/26] Little updates --- build.gradle.kts | 2 +- src/main/resources/html/admin/class.html | 1 - src/main/resources/templates/html/class_info.html | 1 - 3 files changed, 1 insertion(+), 3 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 80bab18..0243174 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,7 +7,7 @@ plugins { group = "igs-landstuhl" -version = "v1.1.0-SNAPSHOT-1" +version = "v1.1.0-SNAPSHOT-2" application { mainClass.set("de.igslandstuhl.database.Application") diff --git a/src/main/resources/html/admin/class.html b/src/main/resources/html/admin/class.html index cec7d6a..513c556 100644 --- a/src/main/resources/html/admin/class.html +++ b/src/main/resources/html/admin/class.html @@ -40,7 +40,6 @@

Schüler in der Klasse

Name - Raum Graduierung diff --git a/src/main/resources/templates/html/class_info.html b/src/main/resources/templates/html/class_info.html index ca36e3a..647744e 100644 --- a/src/main/resources/templates/html/class_info.html +++ b/src/main/resources/templates/html/class_info.html @@ -10,7 +10,6 @@

Schüler in der Klasse:

Name - Raum Graduierung From c149dbeb6de103cc8a66e09b44444e0f8ed6ef28 Mon Sep 17 00:00:00 2001 From: Lukas Morgenstern <139539229+Schlaumeier5@users.noreply.github.com> Date: Tue, 28 Apr 2026 17:50:16 +0200 Subject: [PATCH 09/26] Add GNU GPL v3 license file Added the GNU General Public License version 3 to the project. --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From a0d88f3e9fc95114117f4dd2725af3ad642cdd9f Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Tue, 12 May 2026 19:15:32 +0200 Subject: [PATCH 10/26] Bumped version to v2.0.0-SNAPSHOT-0 to reflect great changes --- build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index 0243174..cfdecc4 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,7 +7,7 @@ plugins { group = "igs-landstuhl" -version = "v1.1.0-SNAPSHOT-2" +version = "v2.0.0-SNAPSHOT-0" application { mainClass.set("de.igslandstuhl.database.Application") From 3e29789ccc5c7b33987dfd1a2817863c19f64039 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Wed, 13 May 2026 20:48:41 +0200 Subject: [PATCH 11/26] Added slf4j as logging library Added a few fundamental logs --- .gitignore | 3 +- build.gradle.kts | 4 ++ .../de/igslandstuhl/database/Application.java | 15 +++++- .../database/client/HTMLTemplate.java | 5 ++ .../database/holidays/Holiday.java | 5 ++ .../igslandstuhl/database/plugins/Plugin.java | 7 +++ .../database/plugins/PluginLoader.java | 7 +++ .../database/server/sql/SQLiteConnection.java | 6 +++ .../database/server/webserver/WebPath.java | 6 +++ .../webserver/handlers/GetRequestHandler.java | 5 ++ .../handlers/PostRequestHandler.java | 5 ++ .../handlers/get/SQLRequestHandler.java | 6 +++ src/main/resources/logback.xml | 48 +++++++++++++++++++ 13 files changed, 120 insertions(+), 2 deletions(-) create mode 100644 src/main/resources/logback.xml diff --git a/.gitignore b/.gitignore index e6d18f3..d1f804e 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ bin .gradle build /modules -/plugins \ No newline at end of file +/plugins +logs \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index cfdecc4..21c32a5 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -25,6 +25,10 @@ dependencies { implementation("org.jline:jline:3.30.6") // for better console input handling implementation("org.yaml:snakeyaml:2.2") // plugin imports + // Logging + implementation("org.slf4j:slf4j-api:2.0.13") + implementation("ch.qos.logback:logback-classic:1.5.6") + testImplementation("org.junit.jupiter:junit-jupiter:5.13.4") // using JUnit 5 (latest) testRuntimeOnly("org.junit.platform:junit-platform-launcher") } diff --git a/src/main/java/de/igslandstuhl/database/Application.java b/src/main/java/de/igslandstuhl/database/Application.java index 19cd206..0ced9e0 100644 --- a/src/main/java/de/igslandstuhl/database/Application.java +++ b/src/main/java/de/igslandstuhl/database/Application.java @@ -5,6 +5,8 @@ import java.util.List; import org.jline.reader.UserInterruptException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import de.igslandstuhl.database.api.SerializationException; import de.igslandstuhl.database.api.Subject; @@ -30,6 +32,9 @@ public final class Application { public static final String TITLE_DELIMITER = "¶"; public static final String TASK_TITLE_DELIMITER = "\\|"; public static final String TASK_DELIMITER = "¤"; + + public static final Logger LOGGER = LoggerFactory.getLogger(Application.class); + private static Application instance = new Application(new String[] {"--test-environment", "true"}); public static Application getInstance() { return instance; @@ -98,15 +103,20 @@ public Topic[] readFile(String file) throws SerializationException, SQLException } public static void main(String[] args) throws Exception { + LOGGER.info("Starting up student-database..."); + instance = new Application(args); PluginLoader.getInstance().preloadPlugins(); if (!getInstance().suppressCmd()) { + LOGGER.info("Setting up command line..."); Command.registerCommands(); CommandLineUtils.setup(); } - + + LOGGER.info("Setting up server..."); + Server.getInstance().getConnection().createTables(); Holiday.setupCurrentSchoolYear(); @@ -119,14 +129,17 @@ public static void main(String[] args) throws Exception { GetRequestHandler.getInstance().registerHandlers(); if (getInstance().runsWebServer()) { + LOGGER.info("Starting WebServer..."); Server.getInstance().getWebServer().start(); } PluginLoader.getInstance().enablePlugins(); + LOGGER.info("Adding shutdown hook for plugin cleanup..."); Runtime.getRuntime().addShutdownHook(new Thread(() -> PluginLoader.getInstance().unloadPlugins(),"Plugin cleanup thread")); try { + LOGGER.info("Starting main loop..."); while (true) { if (!getInstance().suppressCmd()) { CommandLineUtils.waitForCommandAndExec(); diff --git a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java index 8b20614..6fbd1bb 100644 --- a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java +++ b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java @@ -3,6 +3,9 @@ import java.io.FileNotFoundException; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.client.dynamic.DynamicFieldType; import de.igslandstuhl.database.client.dynamic.DynamicHTMLTemplate; @@ -20,6 +23,8 @@ private static void register(HTMLTemplate template, String key) { Registry.templateRegistry().register(key, template); } public static void registerAll() { + final Logger LOGGER = LoggerFactory.getLogger(HTMLTemplate.class); + LOGGER.info("Registering HTML templates..."); NavigationElement.registerAll(); DynamicHTMLTemplate.registerDynamicElements(); Map json = Server.getInstance().getResourceManager().readJsonResourceMerged(meta); diff --git a/src/main/java/de/igslandstuhl/database/holidays/Holiday.java b/src/main/java/de/igslandstuhl/database/holidays/Holiday.java index 66ff791..277a798 100644 --- a/src/main/java/de/igslandstuhl/database/holidays/Holiday.java +++ b/src/main/java/de/igslandstuhl/database/holidays/Holiday.java @@ -16,6 +16,9 @@ import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -25,6 +28,7 @@ public final class Holiday { private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient(); private static final String API_URL = "https://www.mehr-schulferien.de/api/v2.1/schools/66849-integrierte-gesamtschule-am-na/periods"; private static final String SUMMER_HOLIDAY_ID = "Sommer"; + private static final Logger LOGGER = LoggerFactory.getLogger(Holiday.class); private final int id; private final String name; @@ -167,6 +171,7 @@ public static int getActualWeek() { return (int) SchoolWeek.getAll(getLastSummerHoliday().getEnd(), Instant.now(), ZoneId.of("UTC")).stream().filter(SchoolWeek::noSchoolUTC).count(); } public static void setupCurrentSchoolYear() throws SQLException { + LOGGER.info("Trying to set up current school year..."); String name = getLastSummerHoliday().getEnd().toString().substring(0, 4) + "/" + getNextSummerHoliday().getStart().toString().substring(0, 4); int totalWeeks = getTotalWeeks(); int actualWeek = getActualWeek(); diff --git a/src/main/java/de/igslandstuhl/database/plugins/Plugin.java b/src/main/java/de/igslandstuhl/database/plugins/Plugin.java index 08c8317..0cbac36 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/Plugin.java +++ b/src/main/java/de/igslandstuhl/database/plugins/Plugin.java @@ -2,6 +2,9 @@ import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.plugins.config.PluginConfig; import de.igslandstuhl.database.plugins.config.PluginSetting; @@ -86,6 +89,10 @@ void load() { onLoad(); } + public Logger getLogger() { + return LoggerFactory.getLogger(id); + } + static class DummyModule extends Plugin { private final PluginConfig config; public DummyModule(String id, String name, String description, List> settings) { diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java index 85bf0a3..e3d99f9 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java +++ b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java @@ -13,11 +13,14 @@ import java.util.Map; import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.yaml.snakeyaml.Yaml; import de.igslandstuhl.database.Registry; public class PluginLoader { + private final Logger LOGGER = LoggerFactory.getLogger(getClass()); private final List pluginInfos = new ArrayList<>(); public List getPluginInfos() { return pluginInfos; @@ -146,6 +149,7 @@ public void loadAllPlugins(File folder) { pluginInfos.forEach(this::load); } public void enablePlugins() { + LOGGER.info("Enabling plugins..."); pluginInfos.forEach((p) -> { Plugin plugin = Registry.pluginRegistry().get(p.description().id()); if (plugin.getConfig().isEnabledOnStart()) { @@ -154,6 +158,7 @@ public void enablePlugins() { }); } public void unloadPlugins() { + LOGGER.info("Unloading plugins..."); Collections.reverse(pluginInfos); pluginInfos.forEach((p) -> { Plugin plugin = Registry.pluginRegistry().get(p.description().id()); @@ -182,9 +187,11 @@ private void registerPlugin(Plugin plugin) { Registry.pluginRegistry().register(plugin.getId(), plugin); } public void preloadPlugins() { + LOGGER.info("Preloading plugins from directory \"plugins\"..."); preloadAllPlugins(new File("plugins")); } public void registerPlugins() { + LOGGER.info("Registering plugins from directory \"plugins\"..."); loadAllPlugins(new File("plugins")); } } diff --git a/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java b/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java index a39a389..7208b49 100644 --- a/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java +++ b/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java @@ -10,6 +10,9 @@ import java.sql.Statement; import java.util.regex.Pattern; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.utils.TrackingReadWriteLock; @@ -38,6 +41,8 @@ public Connection getSQLConnection() { private final TrackingReadWriteLock lock = new TrackingReadWriteLock(); + private final Logger LOGGER = LoggerFactory.getLogger(getClass()); + /** * Creates the necessary tables in the database by executing SQL scripts. * This method reads SQL files matching the pattern "./tables/*.sql" (regex: .*tables.+\\.sql) and executes their content. @@ -157,6 +162,7 @@ public void closePendingStatement() throws SQLException { * @throws SQLException if an SQL error occurs during table creation */ public void createTables() throws SQLException { + LOGGER.debug("Creating Database Tables..."); executeVoidProcessSecure(this::createTables); } diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/WebPath.java b/src/main/java/de/igslandstuhl/database/server/webserver/WebPath.java index 3c11767..075401d 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/WebPath.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/WebPath.java @@ -4,16 +4,22 @@ import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.resources.ResourceLocation; import de.igslandstuhl.database.server.webserver.requests.RequestType; public record WebPath(RequestType type, String handlerType, List namespaces, String context, AccessLevel accessLevel) { + private static final Logger LOGGER = LoggerFactory.getLogger(WebPath.class); + public static void registerPath(String path, RequestType type, String handlerType, List namespaces, String context, AccessLevel accessLevel) { Registry.webPathRegistry().register(path, new WebPath(type, handlerType, namespaces, context, accessLevel)); } public static void registerPaths() throws IOException { + LOGGER.info("Registering get request paths..."); if (Registry.webPathRegistry().stream().count() > 0) return; // already registered ResourceLocation metaLocation = new ResourceLocation("meta", "paths", "get_paths.json"); Map pathData = Server.getInstance().getResourceManager().readJsonResourceMerged(metaLocation); diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/GetRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/GetRequestHandler.java index ff9e130..befe33a 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/GetRequestHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/GetRequestHandler.java @@ -2,6 +2,9 @@ import java.util.List; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.server.Server; @@ -15,6 +18,7 @@ import de.igslandstuhl.database.utils.ThrowingFunction; public class GetRequestHandler { + private static final Logger LOGGER = LoggerFactory.getLogger(GetRequestHandler.class); private static final GetRequestHandler instance = new GetRequestHandler(); public static GetRequestHandler getInstance() { return instance; @@ -65,6 +69,7 @@ public static GetResponse handlePluginRequest(GetRequest request) { } public final void registerHandlers() { + LOGGER.info("Registering Get Request Handlers..."); if (Registry.getRequestHandlerRegistry().stream().count() > 0) return; // already registered List getPaths = Registry.webPathRegistry().keyStream().filter((p) -> Registry.webPathRegistry().get(p).type() == RequestType.GET).toList(); for (String path : getPaths) { diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java index 5bbb557..5c9c605 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java @@ -14,6 +14,8 @@ import org.owasp.html.PolicyFactory; import org.owasp.html.Sanitizers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import com.google.gson.reflect.TypeToken; @@ -66,6 +68,8 @@ private PostRequestHandler() { // Private constructor to prevent instantiation } + private static final Logger LOGGER = LoggerFactory.getLogger(PostRequestHandler.class); + /** * Handles the POST request based on the path specified in the request. * It routes the request to the appropriate handler method based on the path. @@ -166,6 +170,7 @@ public static PostResponse handleObjectAction(APIPostReque return successMessage; } public static void registerHandlers() { + LOGGER.info("Registering Post Request Handlers..."); HttpHandler.registerPostRequestHandler("/login", AccessLevel.PUBLIC, (rq) -> { String username = prepare(rq.getString("username"), false); // Do not sanitize / url-decode password to allow special characters like % diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java index 391c9f4..37bd4e1 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/get/SQLRequestHandler.java @@ -3,6 +3,9 @@ import java.util.HashSet; import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.api.SchoolClass; import de.igslandstuhl.database.api.Student; @@ -12,12 +15,15 @@ @FunctionalInterface public interface SQLRequestHandler { + public static final Logger LOGGER = LoggerFactory.getLogger(SQLRequestHandler.class); public String get(User user); public static String getResource(String resource, User user) { return Registry.sqlRequestHandlerRegistry().get(resource).get(user); } public static void register() { + LOGGER.info("Registering SQL request handlers..."); + Registry.sqlRequestHandlerRegistry().register("mydata", (user) -> user.toJSON()); Registry.sqlRequestHandlerRegistry().register("mysubjects", (user) -> { diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml new file mode 100644 index 0000000..a22b447 --- /dev/null +++ b/src/main/resources/logback.xml @@ -0,0 +1,48 @@ + + + + + + + + %d{HH:mm:ss} [%thread|%logger{36}] %-5level: %msg%n + + + + + + + + logs/latest.log + + + + + logs/archive/app-%d{yyyy-MM-dd}.log + + + 30 + + + + + + %d{yyyy-MM-dd HH:mm:ss} + [%thread] + %-5level + %logger{36} + - %msg%n + + + + + + + + + + + \ No newline at end of file From 9e9cc5a1b0c0a0a2bd918129f62fd6cecf636ad3 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Wed, 13 May 2026 23:30:16 +0200 Subject: [PATCH 12/26] Replaced error and debug prints in api with logging --- .../java/de/igslandstuhl/database/Application.java | 2 +- .../java/de/igslandstuhl/database/api/Admin.java | 3 ++- .../de/igslandstuhl/database/api/SchoolClass.java | 12 ++++++------ .../de/igslandstuhl/database/api/SchoolYear.java | 10 ++++++---- .../de/igslandstuhl/database/api/SpecialTask.java | 5 +++-- .../java/de/igslandstuhl/database/api/Student.java | 11 ++++++----- .../java/de/igslandstuhl/database/api/Subject.java | 14 +++++++------- .../java/de/igslandstuhl/database/api/Task.java | 4 ++-- .../java/de/igslandstuhl/database/api/Teacher.java | 13 +++++++------ .../java/de/igslandstuhl/database/api/Topic.java | 9 +++++---- 10 files changed, 45 insertions(+), 38 deletions(-) diff --git a/src/main/java/de/igslandstuhl/database/Application.java b/src/main/java/de/igslandstuhl/database/Application.java index 0ced9e0..b1ac18e 100644 --- a/src/main/java/de/igslandstuhl/database/Application.java +++ b/src/main/java/de/igslandstuhl/database/Application.java @@ -34,6 +34,7 @@ public final class Application { public static final String TASK_DELIMITER = "¤"; public static final Logger LOGGER = LoggerFactory.getLogger(Application.class); + public static final Logger LOGGER_API = LoggerFactory.getLogger("de.igslandstuhl.database.api"); private static Application instance = new Application(new String[] {"--test-environment", "true"}); public static Application getInstance() { @@ -94,7 +95,6 @@ public Topic[] readFile(String file) throws SerializationException, SQLException } } } catch (Throwable t) { - t.printStackTrace(); throw new SerializationException("Failed to read file", t); } diff --git a/src/main/java/de/igslandstuhl/database/api/Admin.java b/src/main/java/de/igslandstuhl/database/api/Admin.java index cc1c69f..04b83a9 100644 --- a/src/main/java/de/igslandstuhl/database/api/Admin.java +++ b/src/main/java/de/igslandstuhl/database/api/Admin.java @@ -2,6 +2,7 @@ import java.sql.SQLException; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -61,7 +62,7 @@ public static Admin get(String username) { try { return Server.getInstance().processSingleRequest(Admin::fromSQL, "get_admin_by_username", SQL_FIELDS, username); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve Admin user '{}' from database", username, e); return null; } } diff --git a/src/main/java/de/igslandstuhl/database/api/SchoolClass.java b/src/main/java/de/igslandstuhl/database/api/SchoolClass.java index 90485d9..73ffd24 100644 --- a/src/main/java/de/igslandstuhl/database/api/SchoolClass.java +++ b/src/main/java/de/igslandstuhl/database/api/SchoolClass.java @@ -8,6 +8,7 @@ import java.util.Objects; import java.util.stream.Collectors; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -157,7 +158,7 @@ public List getStudents() { "get_students_by_class", new String[] {"id"}, String.valueOf(id) ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve student list from database", e); } return studentIds.stream().map(Student::get).toList(); } @@ -168,7 +169,6 @@ public void delete() throws SQLException { try { s.delete(); } catch (SQLException e) { - e.printStackTrace(); throw new IllegalStateException(e); } }); @@ -214,7 +214,7 @@ public static SchoolClass get(int id) { try { return Server.getInstance().processSingleRequest(SchoolClass::fromSQL, "get_class_by_id", SQL_FIELDS, String.valueOf(id)); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SchoolClass with id {} from database", id, e); return null; } } @@ -229,7 +229,7 @@ public static SchoolClass get(String label) { try { return Server.getInstance().processSingleRequest(SchoolClass::fromSQL, "get_class_by_label", SQL_FIELDS, label); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SchoolClass with label '{}' from database", label, e); return null; } } @@ -254,7 +254,7 @@ public static SchoolClass getOrCreate(String label) { try { schoolClass = addClass(label, grade); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to create previously not existing class with label {} and grade {}", label, grade, e); } } return schoolClass; @@ -268,7 +268,7 @@ public static List getAll() { "get_all_classes", new String[] {"id"} ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve a list of all classes from the database", e); } return ids.stream() .map(SchoolClass::get) diff --git a/src/main/java/de/igslandstuhl/database/api/SchoolYear.java b/src/main/java/de/igslandstuhl/database/api/SchoolYear.java index 56d1002..6901840 100644 --- a/src/main/java/de/igslandstuhl/database/api/SchoolYear.java +++ b/src/main/java/de/igslandstuhl/database/api/SchoolYear.java @@ -2,6 +2,8 @@ import java.sql.SQLException; import java.util.*; + +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -124,7 +126,7 @@ public static SchoolYear get(int id) { if (year != null) years.put(id, year); return year; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SchoolYear with id {} from database", id, e); return null; } } @@ -134,7 +136,7 @@ public static SchoolYear get(String label) { return get(Integer.parseInt(fields[0])); }, "get_school_year_by_label", new String[] {"id"}, label); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SchoolYear with label '{}' from database", label, e); return null; } } @@ -156,7 +158,7 @@ public static List getAll() { "get_all_school_years", SQL_FIELDS ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve a list of all school years from the database", e); } return all; } @@ -176,7 +178,7 @@ public static SchoolYear getCurrentYear() { if (year != null) years.put(year.getId(), year); return year; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to load current school year from database", e); return null; } } diff --git a/src/main/java/de/igslandstuhl/database/api/SpecialTask.java b/src/main/java/de/igslandstuhl/database/api/SpecialTask.java index c199912..709c0cf 100644 --- a/src/main/java/de/igslandstuhl/database/api/SpecialTask.java +++ b/src/main/java/de/igslandstuhl/database/api/SpecialTask.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -89,7 +90,7 @@ public static SpecialTask get(int id) { specialTasks.put(id, task); return task; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SpecialTask with id {} from database", id, e); return null; } } @@ -114,7 +115,7 @@ public static List getSpecialTasksByName(String name) { try { Server.getInstance().processRequest(SpecialTask::addToCache, "get_special_tasks_by_name", SQL_FIELDS, name); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get SpecialTask with name {} from database", name, e); return new ArrayList<>(); } return specialTasks.values().stream() diff --git a/src/main/java/de/igslandstuhl/database/api/Student.java b/src/main/java/de/igslandstuhl/database/api/Student.java index 933b89b..f7c336f 100644 --- a/src/main/java/de/igslandstuhl/database/api/Student.java +++ b/src/main/java/de/igslandstuhl/database/api/Student.java @@ -13,6 +13,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.api.results.StudentGenerationResult; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -169,7 +170,7 @@ public static Student get(int id) { student.fetchTasks(); return student; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Student with id {} from database", id, e); return null; } } @@ -190,7 +191,7 @@ public static Student getByEmail(String email) { } catch (NullPointerException e) { return null; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Student with email {} from database", email, e); return null; } } @@ -210,7 +211,7 @@ public static List getAll() { "get_all_students", SQL_FIELDS ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve student list from database", e); } return studentIDs.stream() .map(Student::get) @@ -247,7 +248,7 @@ public static String[] generatePasswords(int count, int length) { try { Thread.sleep(new Random().nextInt(1,10)); // Sleep to ensure different seeds } catch (InterruptedException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Thread sleep while generating passwords was interrupted", e); } } return passwords; @@ -581,7 +582,7 @@ private void loadCurrentTopics() { } } } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to load current topics for '{}'", this.email, e); } } diff --git a/src/main/java/de/igslandstuhl/database/api/Subject.java b/src/main/java/de/igslandstuhl/database/api/Subject.java index cffbc48..ac92e36 100644 --- a/src/main/java/de/igslandstuhl/database/api/Subject.java +++ b/src/main/java/de/igslandstuhl/database/api/Subject.java @@ -9,6 +9,7 @@ import java.util.Objects; import java.util.stream.Collectors; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -94,7 +95,7 @@ public static Subject get(int id) { subjects.put(id, subject); return subject; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Subject with id {} from database", id, e); return null; } } @@ -116,7 +117,7 @@ public static Subject get(String name) { subjects.put(subject.getId(), subject); return subject; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Subject with name {} from database", name, e); return null; } } @@ -137,7 +138,7 @@ public static List getAll() { SQL_FIELDS ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve subject list from database", e); } return subjectIds.stream() .map(Subject::get) @@ -199,7 +200,7 @@ public List getTopics(int grade) { String.valueOf(id) ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve topic list for subject '{}' in grade {} from database", this.name, grade, e); } return topicIds.stream() .map(Topic::get) @@ -218,7 +219,7 @@ public int[] getGrades() { new String[] {"grade"}, String.valueOf(id)); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve list of available grades for subject '{}' from database", this.name, e); } return grades.stream().mapToInt(Integer::intValue).toArray(); } @@ -242,8 +243,7 @@ public void delete() throws SQLException { try { t.delete(); } catch (SQLException e) { - e.printStackTrace(); - throw new IllegalStateException(e); + throw new IllegalStateException("Failed to delete topic " + t.getName() + " which is necessary to delete subject " + this.name, e); } })); } catch (IllegalStateException e) { diff --git a/src/main/java/de/igslandstuhl/database/api/Task.java b/src/main/java/de/igslandstuhl/database/api/Task.java index b4188c8..9460245 100644 --- a/src/main/java/de/igslandstuhl/database/api/Task.java +++ b/src/main/java/de/igslandstuhl/database/api/Task.java @@ -180,7 +180,7 @@ public static Task get(int id) { tasks.put(id, task); return task; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Task with id {} from database", id, e); return null; } } @@ -194,7 +194,7 @@ public static List getByName(String name) { String[][] table = Server.getInstance().processRequest("get_tasks_by_name", new String[] {"id"}, name); Arrays.stream(table).map(s -> s[0]).map(Integer::parseInt).map(Task::get).forEach((t) -> t.getId()); // Do something because streams are lazy } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Task with name {} from database", name, e); return new ArrayList<>(); } return tasks.values().stream() diff --git a/src/main/java/de/igslandstuhl/database/api/Teacher.java b/src/main/java/de/igslandstuhl/database/api/Teacher.java index db39ccc..1c617b2 100644 --- a/src/main/java/de/igslandstuhl/database/api/Teacher.java +++ b/src/main/java/de/igslandstuhl/database/api/Teacher.java @@ -4,6 +4,7 @@ import java.util.*; import java.util.stream.Collectors; +import de.igslandstuhl.database.Application; import de.igslandstuhl.database.api.results.TeacherGenerationResult; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.sql.SQLHelper; @@ -200,7 +201,7 @@ public static Teacher get(int id) { teachersByEmail.put(teacher.getEmail(), teacher); return teacher; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Teacher with id {} from database", id, e); return null; } } @@ -223,7 +224,7 @@ public static Teacher fromEmail(String email) { teachersByEmail.put(email, teacher); return teacher; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Teacher with email {} from database", email, e); return null; } } @@ -243,7 +244,7 @@ public static List getAll() { "get_all_teachers", SQL_FIELDS ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve teacher list from database", e); } return teacherIDs.stream() .map(Teacher::get) @@ -259,7 +260,7 @@ public List getSubjects() { "get_subjects_by_teacher", Subject.SQL_FIELDS, String.valueOf(id) ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve subject list for teacher '{}' from database", this.email, e); } return subjectIds.stream() .map(Subject::get) @@ -312,7 +313,7 @@ public static TeacherGenerationResult[] generateTeachersFromCSV(String csv) thro try { Thread.sleep(new Random().nextInt(100)); // Sleep to ensure unique passwords } catch (InterruptedException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Thread sleep while generating passwords was interrupted", e); } } @@ -337,7 +338,7 @@ private void loadClasses() { "get_teacher_classes", CLASS_FIELDS, String.valueOf(id) ); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to retrieve class list of teacher '{}' from database", this.email, e); } } diff --git a/src/main/java/de/igslandstuhl/database/api/Topic.java b/src/main/java/de/igslandstuhl/database/api/Topic.java index e56d764..ceb5892 100644 --- a/src/main/java/de/igslandstuhl/database/api/Topic.java +++ b/src/main/java/de/igslandstuhl/database/api/Topic.java @@ -120,7 +120,7 @@ public static Topic get(int id) { topics.put(id, topic); return topic; } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Topic with id {} from database", id, e); return null; } } @@ -271,7 +271,7 @@ private void loadTasks() { tasksLevel2 = getTasksByLevel(tasks, TaskLevel.LEVEL2); tasksLevel3 = getTasksByLevel(tasks, TaskLevel.LEVEL3); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get task list for topic '{}' from database", this.name, e); } } private static void addToCache(String[] fields) { @@ -287,7 +287,7 @@ public static List getByName(String name) { try { Server.getInstance().processRequest(Topic::addToCache, "get_topics_by_name", SQL_FIELDS, name); } catch (SQLException e) { - e.printStackTrace(); + Application.LOGGER_API.error("Failed to get Topic with name '{}' from database", name, e); return new ArrayList<>(); } return topics.values().stream() @@ -399,6 +399,7 @@ public boolean equals(Object obj) { return true; } public static Topic fromSerialized(String serialized, Subject subject, int grade, int number) throws SerializationException, SQLException { + Application.LOGGER_API.debug("Reading topic from serialized...");; // Gathering general info (topic name and ratio) String[] parts = serialized.split(Application.TITLE_DELIMITER); String[] generalInfo = parts[0].split(Application.TASK_DELIMITER); @@ -427,7 +428,7 @@ public static Topic fromSerialized(String serialized, Subject subject, int grade } topic.loadTasks(); - System.out.println(topic.getTasks()); + Application.LOGGER_API.debug("Loaded tasks for topic {}: {}", topic.getName(), topic.getTasks()); } return topic; } From df2b115fc52ae50ce98a1b5b09a06326217d4091 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Thu, 14 May 2026 12:31:57 +0200 Subject: [PATCH 13/26] Replaced error prints and command prints with logging --- .../database/client/HTMLTemplate.java | 5 ++- .../client/dynamic/DynamicHTMLTemplate.java | 3 +- .../database/holidays/Holiday.java | 1 - .../database/plugins/PluginLoader.java | 32 ++++++++++--------- .../plugins/PluginResourceProvider.java | 7 ++-- .../database/plugins/config/PluginConfig.java | 5 +-- .../igslandstuhl/database/server/Server.java | 10 ++++-- .../database/server/WebServer.java | 12 ++++--- .../database/server/commands/Command.java | 9 ++++-- .../resources/CoreResourceProvider.java | 2 +- .../resources/FileResourceProvider.java | 2 +- .../server/resources/ResourceManager.java | 4 +++ .../sql/SQLMultipleAccessesException.java | 2 +- .../server/webserver/AccessManager.java | 9 ++++-- .../webserver/handlers/HttpHandler.java | 8 +++-- .../handlers/PostRequestHandler.java | 2 +- .../webserver/responses/GetResponse.java | 3 +- .../webserver/responses/PostResponse.java | 3 +- .../webserver/sessions/SessionManager.java | 13 +++++--- .../database/utils/CommandLineUtils.java | 2 +- 20 files changed, 84 insertions(+), 50 deletions(-) diff --git a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java index 6fbd1bb..32516bd 100644 --- a/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java +++ b/src/main/java/de/igslandstuhl/database/client/HTMLTemplate.java @@ -17,13 +17,13 @@ import de.igslandstuhl.database.server.resources.ResourceLocation; public interface HTMLTemplate { + public static final Logger LOGGER = LoggerFactory.getLogger(HTMLTemplate.class); public static final ResourceLocation meta = new ResourceLocation("meta", "templates", "templates.json"); public String fill(Map args); private static void register(HTMLTemplate template, String key) { Registry.templateRegistry().register(key, template); } public static void registerAll() { - final Logger LOGGER = LoggerFactory.getLogger(HTMLTemplate.class); LOGGER.info("Registering HTML templates..."); NavigationElement.registerAll(); DynamicHTMLTemplate.registerDynamicElements(); @@ -38,8 +38,7 @@ public static void registerAll() { try { register(new HTMLFileTemplate((String) template.get("path")), key); } catch (FileNotFoundException e) { - System.err.println("Failed to load html template " + key); - e.printStackTrace(); + LOGGER.error("Failed to load html template '{}'", key, e); } break; case "HTMLNavigationTemplate": diff --git a/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java index e425e1a..133f14c 100644 --- a/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java +++ b/src/main/java/de/igslandstuhl/database/client/dynamic/DynamicHTMLTemplate.java @@ -22,8 +22,7 @@ public String fill(Map args) { try { return TemplatingPreprocessor.getInstance().executeTemplating(arg0); } catch (IOException e) { - System.err.println("Failed filling template " + arg0); - e.printStackTrace(); + HTMLTemplate.LOGGER.error("Failed filling template '{}'", arg0, e); return ""; } }) diff --git a/src/main/java/de/igslandstuhl/database/holidays/Holiday.java b/src/main/java/de/igslandstuhl/database/holidays/Holiday.java index 277a798..91ff9d5 100644 --- a/src/main/java/de/igslandstuhl/database/holidays/Holiday.java +++ b/src/main/java/de/igslandstuhl/database/holidays/Holiday.java @@ -142,7 +142,6 @@ public static Holiday[] holidaysInterval(Instant start, Instant end) { } catch (URISyntaxException | IOException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { - e.printStackTrace(); throw new IllegalStateException(e); } } diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java index e3d99f9..6f6a070 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java +++ b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java @@ -1,6 +1,7 @@ package de.igslandstuhl.database.plugins; import java.io.File; +import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; @@ -20,7 +21,7 @@ import de.igslandstuhl.database.Registry; public class PluginLoader { - private final Logger LOGGER = LoggerFactory.getLogger(getClass()); + public static final Logger LOGGER = LoggerFactory.getLogger(PluginLoader.class); private final List pluginInfos = new ArrayList<>(); public List getPluginInfos() { return pluginInfos; @@ -38,7 +39,7 @@ private Map loadYaml(URLClassLoader classLoader) { Yaml yaml = new Yaml(); return yaml.load(is); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error("Failed loading yaml from classLoader {}", classLoader.getName()); return null; } } @@ -55,22 +56,22 @@ public PreLoadedPlugin loadPluginFromJar(File jarFile) { null ); } catch (MalformedURLException e) { - e.printStackTrace(); + LOGGER.error("URL of {} corrupted", jarFile.getName(), e); return null; } try { Map yaml = loadYaml(classLoader); if (yaml == null) { - System.err.println("No plugin.yml found in " + jarFile.getName()); - classLoader.close(); - return null; + LOGGER.error("No plugin.yml found in {}", jarFile.getName()); + throw new FileNotFoundException("No plugin.yml found"); } String mainClassName = (String) yaml.get("main"); String id = (String) yaml.get("id"); if (id == null || mainClassName == null) { - throw new IllegalStateException("Invalid plugin.yml in " + jarFile.getName() + ": you must define id and main"); + LOGGER.error("Invalid plugin.yml in {}: you must define id and main", jarFile.getName()); + throw new IllegalArgumentException("Invalid plugin.yml"); } String name = (String) yaml.getOrDefault("name", id); String description = (String) yaml.getOrDefault("description", ""); @@ -89,18 +90,18 @@ public PreLoadedPlugin loadPluginFromJar(File jarFile) { Class clazz = classLoader.loadClass(mainClassName); if (!Plugin.class.isAssignableFrom(clazz)) { - throw new IllegalStateException("Main class does not extend Plugin"); + LOGGER.error("{}, the main class of {} does not extend Plugin", clazz.getCanonicalName(), jarFile.getName()); + throw new ClassCastException("Plugin main class does not extend Plugin"); } return new PreLoadedPlugin(new PluginDescription(id, name, description, mainClassName, depends), clazz, classLoader, resourceLoader); } catch (Exception e) { - e.printStackTrace(); + LOGGER.error("Failed to preload plugin {}", jarFile.getName(), e); try { classLoader.close(); } catch (IOException e1) { - System.out.println("FAILED to close class loader"); - e1.printStackTrace(); + LOGGER.error("Failed to close classloader for incomplete plugin {}", jarFile.getName(), e1); } return null; } @@ -113,13 +114,13 @@ public void load(PreLoadedPlugin preload) { registerPlugin(plugin); plugin.load(); if (plugin.getConfig() == null) { + LOGGER.error("Plugin '{}' does not have a config", preload.description().id()); throw new NullPointerException("Plugin must have a config"); } } catch (Exception e) { - System.err.println("Failed to load plugin: " + preload.description().id()); + LOGGER.error("Failed to load plugin '{}'", preload.description().id(), e); pluginInfos.remove(preload); if (Registry.pluginRegistry().get(preload.description().id()) != null) Registry.pluginRegistry().unregister(preload.description().id()); - e.printStackTrace(); } } public void preloadAllPlugins(File folder) { @@ -139,7 +140,8 @@ public void preloadAllPlugins(File folder) { Set ids = new HashSet<>(); for (PreLoadedPlugin p : plugins) { if (!ids.add(p.description().id())) { - throw new IllegalStateException("Duplicate module id: " + p.description().id()); + LOGGER.error("Duplicate plugin id '{}', aborting", p.description().id()); + throw new IllegalStateException("Duplicate plugin id"); } } @@ -172,7 +174,7 @@ public void unloadPlugins() { p.classLoader().close(); p.resourceLoader().close(); } catch (IOException e) { - throw new RuntimeException("Problem while unloading", e); + LOGGER.error("Failed to unload plugin '{}'", plugin.getId()); } }); pluginInfos.clear(); diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java b/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java index 77f46fc..b502ff2 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java +++ b/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java @@ -14,6 +14,7 @@ import de.igslandstuhl.database.server.resources.CoreResourceProvider; import de.igslandstuhl.database.server.resources.ResourceLocation; +import de.igslandstuhl.database.server.resources.ResourceManager; import de.igslandstuhl.database.server.resources.ResourceProvider; public class PluginResourceProvider implements ResourceProvider { @@ -57,8 +58,8 @@ public Collection list(Pattern pattern) { // Virtual root – no real filesystem access needed final Path virtualRoot = Paths.get("").toAbsolutePath().normalize(); - for (PreLoadedPlugin module : PluginLoader.getInstance().getPluginInfos()) { - try (ZipFile zip = new ZipFile(new File(module.resourceLoader().getURLs()[0].toURI()))) { + for (PreLoadedPlugin plugin : PluginLoader.getInstance().getPluginInfos()) { + try (ZipFile zip = new ZipFile(new File(plugin.resourceLoader().getURLs()[0].toURI()))) { Enumeration entries = zip.entries(); @@ -80,7 +81,7 @@ public Collection list(Pattern pattern) { } } catch (Exception e) { - e.printStackTrace(); + ResourceManager.LOGGER.error("Failed to get resource locations of pattern {} from plugin '{}'", pattern.pattern(), plugin.description().id()); } } diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java b/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java index 61c88c3..b0735f6 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java +++ b/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java @@ -12,6 +12,7 @@ import com.google.gson.JsonObject; import de.igslandstuhl.database.plugins.Plugin; +import de.igslandstuhl.database.plugins.PluginLoader; public abstract class PluginConfig { private final T plugin; @@ -108,7 +109,7 @@ public void save() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(root, writer); } catch (IOException e) { - e.printStackTrace(); + PluginLoader.LOGGER.error("Failed to save plugin config for {}", plugin.getId(), e); } } public void load() { @@ -128,7 +129,7 @@ public void load() { enabledOnStart = root.get("enabled").getAsBoolean(); } catch (IOException e) { - e.printStackTrace(); + PluginLoader.LOGGER.error("Failed to load plugin config for {}", plugin.getId(), e); } } } \ No newline at end of file diff --git a/src/main/java/de/igslandstuhl/database/server/Server.java b/src/main/java/de/igslandstuhl/database/server/Server.java index df4aafc..4901f49 100644 --- a/src/main/java/de/igslandstuhl/database/server/Server.java +++ b/src/main/java/de/igslandstuhl/database/server/Server.java @@ -9,6 +9,8 @@ import java.util.function.Function; import org.apache.commons.codec.digest.DigestUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import de.igslandstuhl.database.Application; import de.igslandstuhl.database.api.User; @@ -79,6 +81,8 @@ public ResourceManager getResourceManager() { return resourceManager; } + public static final Logger LOGGER = LoggerFactory.getLogger(Server.class); + /** * Private constructor to initialize the server instance. * This constructor sets up the database connection and initializes the web server. @@ -151,15 +155,15 @@ public void processRequest(Consumer callback, String request, String[] callback.accept(results.toArray(resultArr)); } } catch (SQLException e) { - e.printStackTrace(); + LOGGER.error("Failed to process sql request {} with args {}", request, args, e); throw new IllegalStateException(e); } - }); + }, "SQL Request Subroutine"); subroutine.start(); try { subroutine.join(); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.error("Request subroutine was interrupted", e); throw new IllegalStateException(e); } } finally { diff --git a/src/main/java/de/igslandstuhl/database/server/WebServer.java b/src/main/java/de/igslandstuhl/database/server/WebServer.java index 7091055..570f317 100644 --- a/src/main/java/de/igslandstuhl/database/server/WebServer.java +++ b/src/main/java/de/igslandstuhl/database/server/WebServer.java @@ -9,6 +9,10 @@ import java.nio.charset.StandardCharsets; import javax.net.ssl.*; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; @@ -40,6 +44,7 @@ public class WebServer implements Runnable { public static final int SESSION_DURATION = 21600; // six hours public static final int MAXIMUM_INACTIVITY_DURATION = 3600; // An hour public static final int RATELIMIT = 60; + public static final Logger LOGGER = LoggerFactory.getLogger(Server.class); private volatile boolean running; private final SSLServerSocket serverSocket; @@ -112,7 +117,7 @@ public void run() { } } } catch (Exception e) { - e.printStackTrace(); + LOGGER.error("Failed to handle client {}", clientIp, e); } finally { try { clientSocket.close(); } catch (IOException ignored) {} } @@ -233,7 +238,7 @@ public void start() { public void stop() { running = false; - try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } + try { serverSocket.close(); } catch (IOException e) { LOGGER.error("Failed to close server socket", e); } clientPool.shutdownNow(); } @@ -245,8 +250,7 @@ public void run() { clientPool.submit(new ClientHandler(clientSocket)); } catch (IOException e) { if (running) { - System.err.println("Error while accepting client"); - e.printStackTrace(); + LOGGER.error("Unexpected Exception while accepting client", e); } } } diff --git a/src/main/java/de/igslandstuhl/database/server/commands/Command.java b/src/main/java/de/igslandstuhl/database/server/commands/Command.java index 38469b1..6b07495 100644 --- a/src/main/java/de/igslandstuhl/database/server/commands/Command.java +++ b/src/main/java/de/igslandstuhl/database/server/commands/Command.java @@ -5,6 +5,9 @@ import java.util.List; import java.util.Random; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.api.*; import de.igslandstuhl.database.server.Server; @@ -12,6 +15,7 @@ @FunctionalInterface public interface Command { + public static final Logger LOGGER = LoggerFactory.getLogger(Command.class); public String execute(String[] args); public default CommandDescription getDescription() { return Registry.commandDescriptionRegistry().get(Registry.commandDescriptionRegistry() @@ -25,7 +29,7 @@ public static String executeCommand(String command, String[] args) { } catch (NullPointerException e) { return "Command not found: " + command; } catch (Exception e) { - e.printStackTrace(); + LOGGER.error("Failed to execute command '{}'", command, e); return ""; } } @@ -34,8 +38,9 @@ public static void registerCommand(String name, Command command, CommandDescript Registry.commandDescriptionRegistry().register(name, description); } public static void registerCommands() { + LOGGER.info("Registering commands..."); registerCommand("exit", (args) -> { - System.out.println("Exiting..."); + LOGGER.info("Program exit through command;exiting..."); System.exit(0); return ""; }, new CommandDescription("exit", "Exits the application", "exit")); diff --git a/src/main/java/de/igslandstuhl/database/server/resources/CoreResourceProvider.java b/src/main/java/de/igslandstuhl/database/server/resources/CoreResourceProvider.java index 1c67d53..005b25c 100644 --- a/src/main/java/de/igslandstuhl/database/server/resources/CoreResourceProvider.java +++ b/src/main/java/de/igslandstuhl/database/server/resources/CoreResourceProvider.java @@ -119,7 +119,7 @@ private Collection getResourcesFromDirectory(final Path direct } }); } catch (IOException e) { - e.printStackTrace(); + ResourceManager.LOGGER.error("Failed to get resources from directory '{}'", directory.toString(), e); return retval; } return retval; diff --git a/src/main/java/de/igslandstuhl/database/server/resources/FileResourceProvider.java b/src/main/java/de/igslandstuhl/database/server/resources/FileResourceProvider.java index 7c2f9c5..53de6d3 100644 --- a/src/main/java/de/igslandstuhl/database/server/resources/FileResourceProvider.java +++ b/src/main/java/de/igslandstuhl/database/server/resources/FileResourceProvider.java @@ -58,7 +58,7 @@ public Collection list(Pattern pattern) { } }); } catch (IOException e) { - e.printStackTrace(); + ResourceManager.LOGGER.error("Failed to get resource locations of pattern {} from file root '{}'", pattern.pattern(), root, e); } return result; diff --git a/src/main/java/de/igslandstuhl/database/server/resources/ResourceManager.java b/src/main/java/de/igslandstuhl/database/server/resources/ResourceManager.java index 567495c..9f26871 100644 --- a/src/main/java/de/igslandstuhl/database/server/resources/ResourceManager.java +++ b/src/main/java/de/igslandstuhl/database/server/resources/ResourceManager.java @@ -19,6 +19,9 @@ import java.util.regex.Pattern; import java.util.stream.Stream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; @@ -29,6 +32,7 @@ * Manages Resources in the application */ public class ResourceManager { + public static final Logger LOGGER = LoggerFactory.getLogger(ResourceManager.class); private final List providers; public ResourceManager(ResourceProvider... providers) { this.providers = Arrays.asList(providers); diff --git a/src/main/java/de/igslandstuhl/database/server/sql/SQLMultipleAccessesException.java b/src/main/java/de/igslandstuhl/database/server/sql/SQLMultipleAccessesException.java index c4bdf58..97f54bb 100644 --- a/src/main/java/de/igslandstuhl/database/server/sql/SQLMultipleAccessesException.java +++ b/src/main/java/de/igslandstuhl/database/server/sql/SQLMultipleAccessesException.java @@ -2,7 +2,7 @@ public class SQLMultipleAccessesException extends RuntimeException { public SQLMultipleAccessesException() {} - public SQLMultipleAccessesException(String msg) { super(msg); System.out.println("Test");} + public SQLMultipleAccessesException(String msg) { super(msg); } public SQLMultipleAccessesException(Throwable cause) { super(cause); } public SQLMultipleAccessesException(String msg, Throwable cause) { super(msg, cause); } } diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/AccessManager.java b/src/main/java/de/igslandstuhl/database/server/webserver/AccessManager.java index f287017..53ca04a 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/AccessManager.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/AccessManager.java @@ -5,6 +5,9 @@ import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.server.Server; @@ -15,6 +18,7 @@ * It determines whether a user has access to a specific resource based on predefined rules. */ public class AccessManager { + private static final Logger LOGGER = LoggerFactory.getLogger(AccessManager.class); private static final AccessManager INSTANCE = new AccessManager(); public static AccessManager getInstance() { return INSTANCE; @@ -60,6 +64,7 @@ public static AccessManager getInstance() { @SuppressWarnings("unchecked") private AccessManager() { + LOGGER.info("Setting up AccessManager..."); ResourceLocation metaLocation = new ResourceLocation("meta", "paths", "spaces.json"); String userSpace = "user"; String teacherSpace = "teacher"; @@ -71,6 +76,7 @@ private AccessManager() { String[] teacherLocations = {}; String[] adminLocations = {"students", "teachers", "classes"}; try { + LOGGER.debug("Trying to read spaces metadata..."); Map pathData = Server.getInstance().getResourceManager().readJsonResourceAsMap(metaLocation); List publicSpacesList = (List) pathData.get("public_spaces"); List publicLocationsList = (List) pathData.get("public_locations"); @@ -86,8 +92,7 @@ private AccessManager() { teacherLocations = teacherLocationsList.toArray(new String[teacherLocationsList.size()]); adminLocations = adminLocationsList.toArray(new String[adminLocationsList.size()]); } catch (IOException e) { - System.err.println("Could not read spaces metadata!"); - e.printStackTrace(); + LOGGER.error("Could not read spaces metadata!", e); } finally { USER_SPACE = userSpace; TEACHER_SPACE = teacherSpace; diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/HttpHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/HttpHandler.java index 2477732..d64604b 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/HttpHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/HttpHandler.java @@ -1,5 +1,8 @@ package de.igslandstuhl.database.server.webserver.handlers; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.Registry; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.webserver.AccessLevel; @@ -12,6 +15,7 @@ import de.igslandstuhl.database.utils.ThrowingFunction; public class HttpHandler { + public static final Logger LOGGER = LoggerFactory.getLogger(HttpHandler.class); private final String path; private final AccessLevel accessLevel; private final ThrowingFunction handler; @@ -31,13 +35,13 @@ public HttpResponse handleHttpRequest(Rq request) { if (!accessLevel.hasAccess(sessionManager.getSessionUser(request))) { return HttpResponse.error(request, Status.UNAUTHORIZED); } else if (!path.equals(request.getPath().split("\\?")[0])) { - System.err.println("Wrong path for HTTP handler: " + handler + ", path: " + request.getPath()); + LOGGER.error("Wrong path for HTTP handler: path {} does not match handler path {}", request.getPath(), path); return HttpResponse.error(request, Status.INTERNAL_SERVER_ERROR); } else { try { return handler.apply(request); } catch (Throwable t) { - t.printStackTrace(); + LOGGER.error("Failed to apply HTTP handler", t); return HttpResponse.error(request, Status.INTERNAL_SERVER_ERROR); } } diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java index 5c9c605..c9d5991 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java @@ -95,7 +95,7 @@ private static String prepare(String webInput, boolean sanitize) { try { webInput = URLDecoder.decode(webInput, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { - e.printStackTrace(); + LOGGER.error("Encoding is not supported by URLDecoder", e); } ; if (sanitize) { diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/responses/GetResponse.java b/src/main/java/de/igslandstuhl/database/server/webserver/responses/GetResponse.java index 71d10da..7189ed0 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/responses/GetResponse.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/responses/GetResponse.java @@ -11,6 +11,7 @@ import de.igslandstuhl.database.server.webserver.ContentType; import de.igslandstuhl.database.server.webserver.NoWebResourceException; import de.igslandstuhl.database.server.webserver.Status; +import de.igslandstuhl.database.server.webserver.handlers.HttpHandler; import de.igslandstuhl.database.server.webserver.handlers.get.PluginRequestHandler; import de.igslandstuhl.database.server.webserver.requests.HttpRequest; @@ -211,7 +212,7 @@ public void respond(PrintStream out) { } catch (FileNotFoundException e) { notFound(request).respond(out); } catch (Exception e) { - e.printStackTrace(); + HttpHandler.LOGGER.warn("Exception while trying to write output stream for get request {}", request, e); if (status != Status.INTERNAL_SERVER_ERROR) { internalServerError(request).respond(out); } else { diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java b/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java index 344de23..9226521 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java @@ -12,6 +12,7 @@ import de.igslandstuhl.database.server.webserver.Cookie; import de.igslandstuhl.database.server.webserver.NoWebResourceException; import de.igslandstuhl.database.server.webserver.Status; +import de.igslandstuhl.database.server.webserver.handlers.HttpHandler; import de.igslandstuhl.database.server.webserver.requests.HttpRequest; import de.igslandstuhl.database.server.webserver.requests.PostRequest; @@ -165,7 +166,7 @@ public static PostResponse getResource(ResourceLocation resourceLocation, String } catch (FileNotFoundException e) { return notFound("The requested resource was not found: " + resourceLocation, request); } catch (Exception e) { - e.printStackTrace(); + HttpHandler.LOGGER.warn("Failed to get resource for request {} on resource location {}", request, resourceLocation); return internalServerError("An error occurred while processing your request.", request); } } diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/sessions/SessionManager.java b/src/main/java/de/igslandstuhl/database/server/webserver/sessions/SessionManager.java index 4c226ee..dd5114c 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/sessions/SessionManager.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/sessions/SessionManager.java @@ -5,12 +5,16 @@ import java.util.Map; import java.util.UUID; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.server.webserver.Cookie; import de.igslandstuhl.database.server.webserver.handlers.SessionValidationResult; import de.igslandstuhl.database.server.webserver.requests.HttpRequest; public class SessionManager { + private static final Logger LOGGER = LoggerFactory.getLogger(SessionManager.class); private Map sessionStore = new HashMap<>(); /** * A map to store session IDs and their associated usernames. @@ -33,6 +37,7 @@ public SessionManager(int sessionExpireDuration, int maximumInactivityDuration, this.sessionExpireDuration = sessionExpireDuration; this.maximumInactivityDuration = maximumInactivityDuration; this.maxRequests = maxRequests; + LOGGER.debug("Starting session cleanup job..."); new Thread(this::cleanSecondsJob, "Session Expiring").start(); } @@ -63,7 +68,7 @@ private void cleanSecondsJob() { try { Thread.sleep(60000); } catch (InterruptedException e) { - e.printStackTrace(); + LOGGER.warn("Session manager cleanup job interrupted while sleeping", e); } } } @@ -76,18 +81,18 @@ public SessionValidationResult validateSession(HttpRequest request) { count++; requestCount.set(request, count); if (count > maxRequests && !getSessionUser(request).isAdmin()) { - System.out.println("Ratelimit!"); + LOGGER.warn("Needed to put {} under rate limit: {} requests of maximum {} allowed", getSessionUser(request).getUsername(), count, maxRequests); return SessionValidationResult.RATE_LIMITED; } String userAgent = request.getUserAgent(); if (!getSession(request).getUserAgent().equals(userAgent)) { - System.err.println("SEVERE WARNING: POTENTIAL ATTACK: faked session id (device changed), for user " + getSessionUser(request)); + LOGGER.warn("faked session id (device changed), for user {}" + getSessionUser(request)); return SessionValidationResult.INVALID_SESSION; } String ip = request.getIP(); if (!getSession(request).getIpAddress().equals(ip)) { - System.err.println("SEVERE WARNING: POTENTIAL ATTACK: faked session id (ip address changed) for user " + getSessionUser(request)); + LOGGER.warn("faked session id (ip address changed) for user {}" + getSessionUser(request)); return SessionValidationResult.INVALID_SESSION; } diff --git a/src/main/java/de/igslandstuhl/database/utils/CommandLineUtils.java b/src/main/java/de/igslandstuhl/database/utils/CommandLineUtils.java index 8f43174..7cb11b0 100644 --- a/src/main/java/de/igslandstuhl/database/utils/CommandLineUtils.java +++ b/src/main/java/de/igslandstuhl/database/utils/CommandLineUtils.java @@ -34,6 +34,6 @@ public static void waitForCommandAndExec() { String line = input(); String[] args = line.trim().split(" "); String command = args[0]; - System.out.println(Command.executeCommand(command, Arrays.copyOfRange(args, 1, args.length))); + Command.LOGGER.info("[Commands] {}", Command.executeCommand(command, Arrays.copyOfRange(args, 1, args.length))); } } From 08215a986c6c1c1381cdfcda16f77f49db772b05 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Thu, 14 May 2026 12:44:16 +0200 Subject: [PATCH 14/26] Added ANSI colors to console logs --- src/main/resources/logback.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/logback.xml b/src/main/resources/logback.xml index a22b447..5bd4cbc 100644 --- a/src/main/resources/logback.xml +++ b/src/main/resources/logback.xml @@ -6,7 +6,7 @@ - %d{HH:mm:ss} [%thread|%logger{36}] %-5level: %msg%n + %yellow(%d{HH:mm:ss}) [%cyan(%thread)|%magenta(%logger{20})] %highlight([%level]: %msg%n%ex) From eddc18e5db2783c85127f26b748d9a90fa8cb7e4 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Thu, 14 May 2026 12:44:44 +0200 Subject: [PATCH 15/26] Bumped version to v2.0.0-SNAPSHOT-1 --- build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index 21c32a5..a6c1a1d 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,7 +7,7 @@ plugins { group = "igs-landstuhl" -version = "v2.0.0-SNAPSHOT-0" +version = "v2.0.0-SNAPSHOT-1" application { mainClass.set("de.igslandstuhl.database.Application") From a70db494b876ce3b2cff9594259657ec7b02b723 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Sun, 7 Jun 2026 12:59:17 +0200 Subject: [PATCH 16/26] Changed loadAllPlugins() to loadAllPreloadedPlugins() in PluginLoader (better description of what it does) Removed unused argument --- .../java/de/igslandstuhl/database/plugins/PluginLoader.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java index 6f6a070..1736697 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java +++ b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java @@ -147,7 +147,7 @@ public void preloadAllPlugins(File folder) { PluginSort.sortPlugins(plugins).forEach((p) -> pluginInfos.add(p)); } - public void loadAllPlugins(File folder) { + public void loadAllPreloadedPlugins() { pluginInfos.forEach(this::load); } public void enablePlugins() { @@ -194,6 +194,6 @@ public void preloadPlugins() { } public void registerPlugins() { LOGGER.info("Registering plugins from directory \"plugins\"..."); - loadAllPlugins(new File("plugins")); + loadAllPreloadedPlugins(); } } From c3fbe8b9afe36d55f5cb171cc43b5b707d49feb3 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Sun, 7 Jun 2026 13:12:15 +0200 Subject: [PATCH 17/26] Added built-in plugins --- .../de/igslandstuhl/database/Registry.java | 5 +++++ .../database/plugins/BuiltinPlugin.java | 8 ++++++++ .../igslandstuhl/database/plugins/Plugin.java | 5 +++++ .../database/plugins/PluginLoader.java | 19 +++++++++++++++++-- .../plugins/PluginResourceProvider.java | 1 + 5 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 src/main/java/de/igslandstuhl/database/plugins/BuiltinPlugin.java diff --git a/src/main/java/de/igslandstuhl/database/Registry.java b/src/main/java/de/igslandstuhl/database/Registry.java index e0604f0..2c83a3f 100644 --- a/src/main/java/de/igslandstuhl/database/Registry.java +++ b/src/main/java/de/igslandstuhl/database/Registry.java @@ -11,6 +11,7 @@ import de.igslandstuhl.database.client.dynamic.DynamicFieldType; import de.igslandstuhl.database.client.navigation.NavigationElement; import de.igslandstuhl.database.client.navigation.NavigationType; +import de.igslandstuhl.database.plugins.BuiltinPlugin; import de.igslandstuhl.database.plugins.Plugin; import de.igslandstuhl.database.server.commands.Command; import de.igslandstuhl.database.server.commands.CommandDescription; @@ -28,6 +29,7 @@ public class Registry implements Closeable { private static final Registry> GET_HANDLER_REGISTRY = new Registry<>(); private static final Registry SQL_REQUEST_HANDLER_REGISTRY = new Registry<>(); private static final Registry PLUGIN_REGISTRY = new Registry<>(); + private static final Registry> BUILTIN_PLUGIN_REGISTRY = new Registry<>(); private static final Registry WEB_PATH_REGISTRY = new Registry<>(); private static final EnumRegistry NAVIGATION_REGISTRY = new EnumRegistry<>(NavigationType.class); @@ -49,6 +51,9 @@ public static Registry sqlRequestHandlerRegistry() { public static Registry pluginRegistry() { return PLUGIN_REGISTRY; } + public static Registry> builtinPluginRegistry() { + return BUILTIN_PLUGIN_REGISTRY; + } public static Registry commandDescriptionRegistry() { return COMMAND_DESCRIPTION_REGISTRY; } diff --git a/src/main/java/de/igslandstuhl/database/plugins/BuiltinPlugin.java b/src/main/java/de/igslandstuhl/database/plugins/BuiltinPlugin.java new file mode 100644 index 0000000..0cb700a --- /dev/null +++ b/src/main/java/de/igslandstuhl/database/plugins/BuiltinPlugin.java @@ -0,0 +1,8 @@ +package de.igslandstuhl.database.plugins; + +public abstract class BuiltinPlugin extends Plugin { + protected BuiltinPlugin(PluginDescription description) { + super(); + init(description); + } +} diff --git a/src/main/java/de/igslandstuhl/database/plugins/Plugin.java b/src/main/java/de/igslandstuhl/database/plugins/Plugin.java index 0cbac36..3ecefdf 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/Plugin.java +++ b/src/main/java/de/igslandstuhl/database/plugins/Plugin.java @@ -16,6 +16,8 @@ public abstract class Plugin { private boolean enabled; private boolean initialized = false; + private PluginDescription descriptionAnnotation; + public Plugin() { this.enabled = false; } @@ -40,6 +42,9 @@ public String getName() { public String getDescription() { return description; } + public PluginDescription getDescriptionAnnotation() { + return descriptionAnnotation; + } public boolean isEnabled() { return enabled; } diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java index 1736697..ffa615b 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java +++ b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java @@ -147,6 +147,18 @@ public void preloadAllPlugins(File folder) { PluginSort.sortPlugins(plugins).forEach((p) -> pluginInfos.add(p)); } + public void preloadBuiltinPlugins() { + LOGGER.info("Preloading built-in plugins..."); + Registry.builtinPluginRegistry().keyStream().forEach((id) -> { + Class clazz = Registry.builtinPluginRegistry().get(id); + try { + PluginDescription description = clazz.getDeclaredConstructor().newInstance().getDescriptionAnnotation(); + pluginInfos.add(new PreLoadedPlugin(description, clazz, null, null)); + } catch (Exception e) { + LOGGER.error("Failed to preload built-in plugin '{}'", id, e); + } + }); + } public void loadAllPreloadedPlugins() { pluginInfos.forEach(this::load); } @@ -171,8 +183,10 @@ public void unloadPlugins() { Registry.pluginRegistry().unregister(plugin.getId()); try { - p.classLoader().close(); - p.resourceLoader().close(); + if (p.classLoader() != null) + p.classLoader().close(); + if (p.resourceLoader() != null) + p.resourceLoader().close(); } catch (IOException e) { LOGGER.error("Failed to unload plugin '{}'", plugin.getId()); } @@ -190,6 +204,7 @@ private void registerPlugin(Plugin plugin) { } public void preloadPlugins() { LOGGER.info("Preloading plugins from directory \"plugins\"..."); + preloadBuiltinPlugins(); preloadAllPlugins(new File("plugins")); } public void registerPlugins() { diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java b/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java index b502ff2..247b968 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java +++ b/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java @@ -25,6 +25,7 @@ public InputStream open(ResourceLocation location) { for (PreLoadedPlugin module : PluginLoader.getInstance().getPluginInfos()) { ClassLoader cl = module.resourceLoader(); + if (cl == null) continue; // built-in plugin InputStream stream = cl.getResourceAsStream(path); if (stream != null) { From 3f86956e67b036e96cdb1891e68525fc44c69c7a Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Thu, 18 Jun 2026 12:40:21 +0200 Subject: [PATCH 18/26] Added new input types: IntSetting and ShortAnswerSetting Co-authored-by: Copilot --- .../database/plugins/config/IntSetting.java | 41 +++++++++++ .../database/plugins/config/PluginConfig.java | 72 +++++++++++++++---- .../plugins/config/ShortAnswerSetting.java | 18 +++++ .../handlers/PostRequestHandler.java | 19 +++++ .../resources/js/site/student-database.js | 13 ++++ 5 files changed, 148 insertions(+), 15 deletions(-) create mode 100644 src/main/java/de/igslandstuhl/database/plugins/config/IntSetting.java create mode 100644 src/main/java/de/igslandstuhl/database/plugins/config/ShortAnswerSetting.java diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/IntSetting.java b/src/main/java/de/igslandstuhl/database/plugins/config/IntSetting.java new file mode 100644 index 0000000..c128bf6 --- /dev/null +++ b/src/main/java/de/igslandstuhl/database/plugins/config/IntSetting.java @@ -0,0 +1,41 @@ +package de.igslandstuhl.database.plugins.config; + +public class IntSetting extends PluginSetting { + private int minValue = Integer.MIN_VALUE; + private int maxValue = Integer.MAX_VALUE; + public IntSetting(String key, String name, String description, int defaultValue) { + super(key, name, description, defaultValue); + } + + @Override + public String toJSON() { + return "{" + + "\"key\":\"" + getKey() + "\"," + + "\"name\":\"" + getName() + "\"," + + "\"description\":\"" + getDescription() + "\"," + + "\"defaultValue\":" + getDefaultValue() + "," + + "\"value\":" + getValue() + "," + + "\"minValue\":" + minValue + "," + + "\"maxValue\":" + maxValue + + "}"; + } + public int getMinValue() { + return minValue; + } + public void setMinValue(int minValue) { + if (minValue > maxValue) throw new IllegalArgumentException("minValue cannot be greater than maxValue"); + this.minValue = minValue; + } + public int getMaxValue() { + return maxValue; + } + public void setMaxValue(int maxValue) { + if (maxValue < minValue) throw new IllegalArgumentException("maxValue cannot be less than minValue"); + this.maxValue = maxValue; + } + public void setBounds(int minValue, int maxValue) { + if (minValue > maxValue) throw new IllegalArgumentException("minValue cannot be greater than maxValue"); + this.minValue = minValue; + this.maxValue = maxValue; + } +} diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java b/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java index b0735f6..07c1735 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java +++ b/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java @@ -6,6 +6,7 @@ import java.io.IOException; import java.util.Arrays; import java.util.List; +import java.util.Optional; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -17,22 +18,24 @@ public abstract class PluginConfig { private final T plugin; private final BoolSetting[] boolSettings; + private final IntSetting[] intSettings; + private final ShortAnswerSetting[] shortAnswerSettings; private final File configFile; private boolean enabledOnStart; public PluginConfig(T plugin, PluginSetting... moduleSettings) { - this.plugin = plugin; - List boolSettings = Arrays.stream(moduleSettings).filter((s) -> s instanceof BoolSetting).map((s) -> (BoolSetting) s).toList(); - this.boolSettings = boolSettings.toArray(new BoolSetting[boolSettings.size()]); - this.configFile = new File("plugins/config", plugin.getId() + ".json"); - load(); + this(plugin, Arrays.asList(moduleSettings)); } public PluginConfig(T plugin, List> moduleSettings) { this.plugin = plugin; List boolSettings = moduleSettings.stream().filter((s) -> s instanceof BoolSetting).map((s) -> (BoolSetting) s).toList(); this.boolSettings = boolSettings.toArray(new BoolSetting[boolSettings.size()]); + List intSettings = moduleSettings.stream().filter((s) -> s instanceof IntSetting).map((s) -> (IntSetting) s).toList(); + this.intSettings = intSettings.toArray(new IntSetting[intSettings.size()]); + List shortAnswerSettings = moduleSettings.stream().filter((s) -> s instanceof ShortAnswerSetting).map((s) -> (ShortAnswerSetting) s).toList(); + this.shortAnswerSettings = shortAnswerSettings.toArray(new ShortAnswerSetting[shortAnswerSettings.size()]); this.configFile = new File("plugins/config", plugin.getId() + ".json"); load(); } @@ -44,32 +47,53 @@ public boolean isEnabledOnStart() { return enabledOnStart; } - private BoolSetting findBoolSetting(String key) { + public PluginSetting getSetting(String key) { + Optional> boolSetting = findBoolSetting(key).map((s) -> (PluginSetting) s); + if (boolSetting.isPresent()) { + return boolSetting.get(); + } + Optional> intSetting = findIntSetting(key).map((s) -> (PluginSetting) s); + if (intSetting.isPresent()) { + return intSetting.get(); + } + return findShortAnswerSetting(key).map((s) -> (PluginSetting) s).orElse(null); + } + + private Optional findBoolSetting(String key) { return Arrays.stream(boolSettings) .filter((s) -> s.getKey().equals(key)) - .findAny().orElseThrow(); + .findAny(); } - public boolean getBool(String key) { - return findBoolSetting(key).getValue(); + return findBoolSetting(key).map(BoolSetting::getValue).orElse(false); } - public void setBool(String key, boolean value) { - findBoolSetting(key).setValue(value); + findBoolSetting(key).ifPresent((s) -> s.setValue(value)); save(); } public void enableSetting(String key) { - findBoolSetting(key).enable(); + findBoolSetting(key).ifPresent(BoolSetting::enable); save(); } public void disableSetting(String key) { - findBoolSetting(key).disable(); + findBoolSetting(key).ifPresent(BoolSetting::disable); save(); } public void toggleSetting(String key) { - findBoolSetting(key).toggle(); + findBoolSetting(key).ifPresent(BoolSetting::toggle); save(); } + + private Optional findIntSetting(String key) { + return Arrays.stream(intSettings) + .filter((s) -> s.getKey().equals(key)) + .findAny(); + } + private Optional findShortAnswerSetting(String key) { + return Arrays.stream(shortAnswerSettings) + .filter((s) -> s.getKey().equals(key)) + .findAny(); + } private JsonObject valuesJSON() { JsonObject values = new JsonObject(); @@ -89,7 +113,25 @@ public String toJSON() { } } builder - .append("]}, ") + .append("], ") + .append("\"ints\": ["); + for (int i = 0; i < intSettings.length; i++) { + builder.append(intSettings[i].toJSON()); + if (i < intSettings.length - 1) { + builder.append(", "); + } + } + builder + .append("], ") + .append("\"shortAnswers\": ["); + for (int i = 0; i < shortAnswerSettings.length; i++) { + builder.append(shortAnswerSettings[i].toJSON()); + if (i < shortAnswerSettings.length - 1) { + builder.append(", "); + } + } + builder + .append("},") .append("\"values\": ") .append((new Gson()).toJson(valuesJSON())) .append("}"); diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/ShortAnswerSetting.java b/src/main/java/de/igslandstuhl/database/plugins/config/ShortAnswerSetting.java new file mode 100644 index 0000000..09c56a0 --- /dev/null +++ b/src/main/java/de/igslandstuhl/database/plugins/config/ShortAnswerSetting.java @@ -0,0 +1,18 @@ +package de.igslandstuhl.database.plugins.config; + +public class ShortAnswerSetting extends PluginSetting { + public ShortAnswerSetting(String key, String name, String description, String defaultValue) { + super(key, name, description, defaultValue); + } + + @Override + public String toJSON() { + return "{" + + "\"key\":\"" + getKey() + "\"," + + "\"name\":\"" + getName() + "\"," + + "\"description\":\"" + getDescription() + "\"," + + "\"defaultValue\":\"" + getDefaultValue() + "\"," + + "\"value\":\"" + getValue() + "\"" + + "}"; + } +} diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java index c9d5991..a60266a 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/handlers/PostRequestHandler.java @@ -31,6 +31,11 @@ import de.igslandstuhl.database.api.Topic; import de.igslandstuhl.database.api.User; import de.igslandstuhl.database.api.results.GenerationResult; +import de.igslandstuhl.database.plugins.config.BoolSetting; +import de.igslandstuhl.database.plugins.config.IntSetting; +import de.igslandstuhl.database.plugins.config.PluginConfig; +import de.igslandstuhl.database.plugins.config.PluginSetting; +import de.igslandstuhl.database.plugins.config.ShortAnswerSetting; import de.igslandstuhl.database.server.Server; import de.igslandstuhl.database.server.webserver.AccessLevel; import de.igslandstuhl.database.server.webserver.ContentType; @@ -383,6 +388,20 @@ public static void registerHandlers() { Registry.pluginRegistry().get(key[0]).getConfig().toggleSetting(key[1]); return PostResponse.ok("Plugin setting toggled", ContentType.TEXT_PLAIN, rq); }); + HttpHandler.registerPostRequestHandler("/set-plugin-setting", AccessLevel.ADMIN, (rq) -> { + String[] key = rq.getString("key").split(":"); + PluginConfig config = Registry.pluginRegistry().get(key[0]).getConfig(); + PluginSetting setting = config.getSetting(key[1]); + if (setting instanceof BoolSetting boolSetting) { + boolSetting.setValue(rq.getBoolean("value")); + } else if (setting instanceof IntSetting intSetting) { + intSetting.setValue(rq.getInt("value")); + } else if (setting instanceof ShortAnswerSetting shortAnswerSetting) { + shortAnswerSetting.setValue(rq.getString("value")); + } else { + return PostResponse.badRequest("Setting not found", rq);} + return PostResponse.ok("Plugin setting set", ContentType.TEXT_PLAIN, rq); + }); HttpHandler.registerPostRequestHandler("/student-results-csv", AccessLevel.TEACHER, (rq) -> { Student student = rq.getCurrentStudent(); diff --git a/src/main/resources/js/site/student-database.js b/src/main/resources/js/site/student-database.js index 3104254..eb1d6c4 100644 --- a/src/main/resources/js/site/student-database.js +++ b/src/main/resources/js/site/student-database.js @@ -158,6 +158,9 @@ async function togglePlugin(pluginKey) { async function togglePluginSetting(pluginKey, setting) { return await post('/toggle-plugin-setting', { key: pluginKey + ":" + setting }); } +async function setPluginSetting(pluginKey, setting, value) { + return await post('/set-plugin-setting', { key: pluginKey + ":" + setting, value }); +} async function deleteClass(classId) { return await post('/delete-class', { id: classId }); @@ -682,6 +685,16 @@ function loadPluginSection(pluginKey) { tr.innerHTML = `${b.name}${b.value}`; tbody.appendChild(tr); }); + settings.ints.forEach((i) => { + const tr = document.createElement("tr"); + tr.innerHTML = `${i.name}${i.value}`; + tbody.appendChild(tr); + }) + settings.shortAnswers.forEach((s) => { + const tr = document.createElement("tr"); + tr.innerHTML = `${s.name}${s.value}`; + tbody.appendChild(tr); + }) }) } async function loadPluginsView(pluginContainer) { From 5d85abcdf54d0bb075de7e81f004ceb68eb9ec07 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Thu, 18 Jun 2026 12:43:02 +0200 Subject: [PATCH 19/26] Added new input types to config load and save functionality --- .../database/plugins/config/PluginConfig.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java b/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java index 07c1735..e7724bc 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java +++ b/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java @@ -100,6 +100,12 @@ private JsonObject valuesJSON() { for (BoolSetting s : boolSettings) { values.addProperty(s.getKey(), s.getValue()); } + for (IntSetting s : intSettings) { + values.addProperty(s.getKey(), s.getValue()); + } + for (ShortAnswerSetting s : shortAnswerSettings) { + values.addProperty(s.getKey(), s.getValue()); + } return values; } public String toJSON() { @@ -167,6 +173,16 @@ public void load() { s.setValue(values.get(s.getKey()).getAsBoolean()); } } + for (IntSetting s : intSettings) { + if (values.has(s.getKey())) { + s.setValue(values.get(s.getKey()).getAsInt()); + } + } + for (ShortAnswerSetting s : shortAnswerSettings) { + if (values.has(s.getKey())) { + s.setValue(values.get(s.getKey()).getAsString()); + } + } } enabledOnStart = root.get("enabled").getAsBoolean(); From 8749971011c174ba540f75b71ffeffaee0213a31 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Thu, 18 Jun 2026 13:39:50 +0200 Subject: [PATCH 20/26] Moved plugin loader into builtin plugin --- build.gradle.kts | 13 +- .../database/plugins/BuiltinPlugin.java | 8 - .../igslandstuhl/database/plugins/Plugin.java | 131 ----------- .../database/plugins/PluginDescription.java | 7 - .../database/plugins/PluginLoader.java | 214 ------------------ .../database/plugins/PluginSort.java | 57 ----- .../database/plugins/PreLoadedPlugin.java | 12 - .../database/plugins/config/BoolSetting.java | 31 --- .../database/plugins/config/IntSetting.java | 41 ---- .../database/plugins/config/PluginConfig.java | 193 ---------------- .../plugins/config/PluginSetting.java | 49 ---- .../plugins/config/ShortAnswerSetting.java | 18 -- 12 files changed, 12 insertions(+), 762 deletions(-) delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/BuiltinPlugin.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/Plugin.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/PluginDescription.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/PluginSort.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/PreLoadedPlugin.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/config/BoolSetting.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/config/IntSetting.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/config/PluginSetting.java delete mode 100644 src/main/java/de/igslandstuhl/database/plugins/config/ShortAnswerSetting.java diff --git a/build.gradle.kts b/build.gradle.kts index a6c1a1d..db0a157 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,7 +7,7 @@ plugins { group = "igs-landstuhl" -version = "v2.0.0-SNAPSHOT-1" +version = "v2.0.0-SNAPSHOT-2" application { mainClass.set("de.igslandstuhl.database.Application") @@ -15,6 +15,14 @@ application { repositories { mavenCentral() + maven { + name = "Plugin Loader Repository" + url = uri("https://maven.pkg.github.com/Learn-Monitor/plugin-loader/") + credentials { + username = System.getenv("GITHUB_ACTOR") + password = System.getenv("GITHUB_TOKEN") + } + } } dependencies { @@ -29,6 +37,9 @@ dependencies { implementation("org.slf4j:slf4j-api:2.0.13") implementation("ch.qos.logback:logback-classic:1.5.6") + // built-in plugins + implementation("de.igs-landstuhl:plugin-loader:v1.0.1") + testImplementation("org.junit.jupiter:junit-jupiter:5.13.4") // using JUnit 5 (latest) testRuntimeOnly("org.junit.platform:junit-platform-launcher") } diff --git a/src/main/java/de/igslandstuhl/database/plugins/BuiltinPlugin.java b/src/main/java/de/igslandstuhl/database/plugins/BuiltinPlugin.java deleted file mode 100644 index 0cb700a..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/BuiltinPlugin.java +++ /dev/null @@ -1,8 +0,0 @@ -package de.igslandstuhl.database.plugins; - -public abstract class BuiltinPlugin extends Plugin { - protected BuiltinPlugin(PluginDescription description) { - super(); - init(description); - } -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/Plugin.java b/src/main/java/de/igslandstuhl/database/plugins/Plugin.java deleted file mode 100644 index 3ecefdf..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/Plugin.java +++ /dev/null @@ -1,131 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import de.igslandstuhl.database.plugins.config.PluginConfig; -import de.igslandstuhl.database.plugins.config.PluginSetting; - -public abstract class Plugin { - private String id; - private String name; - private String description; - - private boolean enabled; - private boolean initialized = false; - - private PluginDescription descriptionAnnotation; - - public Plugin() { - this.enabled = false; - } - - void init(String id, String name, String description) { - if (initialized) throw new IllegalStateException("Plugin already initialized"); - this.id = id; - this.name = name; - this.description = description; - this.initialized = true; - } - void init(PluginDescription description) { - init(description.id(), description.name(), description.description()); - } - - public String getId() { - return id; - } - public String getName() { - return name; - } - public String getDescription() { - return description; - } - public PluginDescription getDescriptionAnnotation() { - return descriptionAnnotation; - } - public boolean isEnabled() { - return enabled; - } - - public String toJSON() { - StringBuilder sb = new StringBuilder(); - sb.append("{"); - sb.append("\"id\":\"").append(id).append("\","); - sb.append("\"name\":\"").append(name).append("\","); - sb.append("\"description\":\"").append(description).append("\","); - sb.append("\"enabled\":").append(enabled).append(","); - sb.append("\"config\":").append(getConfig().toJSON()); - sb.append("}"); - return sb.toString(); - } - - /** - * Returns the config of this plugin. - * This should never be null, as it will break the plugin lifecycle otherwise. - * @return the config - */ - public abstract PluginConfig getConfig(); - - protected abstract void onEnable(); - protected abstract void onDisable(); - protected abstract void onLoad(); - - public void enable() { - if (enabled) return; - onEnable(); - enabled = true; - } - public void disable() { - if (!enabled) return; - onDisable(); - enabled = false; - } - public void toggle() { - if (enabled) { - disable(); - } else { - enable(); - } - getConfig().save(); - } - void load() { - onLoad(); - } - - public Logger getLogger() { - return LoggerFactory.getLogger(id); - } - - static class DummyModule extends Plugin { - private final PluginConfig config; - public DummyModule(String id, String name, String description, List> settings) { - init(id, name, description); - config = new PluginConfig(this, settings) { - - }; - } - - @Override - public PluginConfig getConfig() { - return config; - } - - @Override - protected void onEnable() { - // Dummy enable logic - } - - @Override - protected void onDisable() { - // Dummy disable logic - } - - @Override - protected void onLoad() { - // Dummy load logic - } - } - -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginDescription.java b/src/main/java/de/igslandstuhl/database/plugins/PluginDescription.java deleted file mode 100644 index 1a2d7eb..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginDescription.java +++ /dev/null @@ -1,7 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.util.List; - -public record PluginDescription(String id, String name, String description, String main, List depends) { - -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java b/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java deleted file mode 100644 index ffa615b..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginLoader.java +++ /dev/null @@ -1,214 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.yaml.snakeyaml.Yaml; - -import de.igslandstuhl.database.Registry; - -public class PluginLoader { - public static final Logger LOGGER = LoggerFactory.getLogger(PluginLoader.class); - private final List pluginInfos = new ArrayList<>(); - public List getPluginInfos() { - return pluginInfos; - } - private static final PluginLoader INSTANCE = new PluginLoader(); - public static PluginLoader getInstance() { - return INSTANCE; - } - private PluginLoader() {} - - private Map loadYaml(URLClassLoader classLoader) { - try (InputStream is = classLoader.getResourceAsStream("plugin.yml")) { - if (is == null) return null; - - Yaml yaml = new Yaml(); - return yaml.load(is); - } catch (Exception e) { - LOGGER.error("Failed loading yaml from classLoader {}", classLoader.getName()); - return null; - } - } - public PreLoadedPlugin loadPluginFromJar(File jarFile) { - URLClassLoader classLoader; - URLClassLoader resourceLoader; - try { - classLoader = new URLClassLoader( - new URL[]{jarFile.toURI().toURL()}, - getClass().getClassLoader() - ); - resourceLoader = new URLClassLoader( - new URL[]{jarFile.toURI().toURL()}, - null - ); - } catch (MalformedURLException e) { - LOGGER.error("URL of {} corrupted", jarFile.getName(), e); - return null; - } - try { - - Map yaml = loadYaml(classLoader); - if (yaml == null) { - LOGGER.error("No plugin.yml found in {}", jarFile.getName()); - throw new FileNotFoundException("No plugin.yml found"); - } - - String mainClassName = (String) yaml.get("main"); - String id = (String) yaml.get("id"); - if (id == null || mainClassName == null) { - LOGGER.error("Invalid plugin.yml in {}: you must define id and main", jarFile.getName()); - throw new IllegalArgumentException("Invalid plugin.yml"); - } - String name = (String) yaml.getOrDefault("name", id); - String description = (String) yaml.getOrDefault("description", ""); - - Object dependsObj = yaml.get("depends"); - List depends = new ArrayList<>(); - - if (dependsObj instanceof List) { - for (Object o : (List) dependsObj) { - if (o instanceof String s) { - depends.add(s); - } - } - } - - Class clazz = classLoader.loadClass(mainClassName); - - if (!Plugin.class.isAssignableFrom(clazz)) { - LOGGER.error("{}, the main class of {} does not extend Plugin", clazz.getCanonicalName(), jarFile.getName()); - throw new ClassCastException("Plugin main class does not extend Plugin"); - } - - return new PreLoadedPlugin(new PluginDescription(id, name, description, mainClassName, depends), clazz, classLoader, resourceLoader); - - } catch (Exception e) { - LOGGER.error("Failed to preload plugin {}", jarFile.getName(), e); - try { - classLoader.close(); - } catch (IOException e1) { - LOGGER.error("Failed to close classloader for incomplete plugin {}", jarFile.getName(), e1); - } - return null; - } - } - public void load(PreLoadedPlugin preload) { - Plugin plugin; - try { - plugin = (Plugin) preload.clazz().getDeclaredConstructor().newInstance(); - plugin.init(preload.description()); - registerPlugin(plugin); - plugin.load(); - if (plugin.getConfig() == null) { - LOGGER.error("Plugin '{}' does not have a config", preload.description().id()); - throw new NullPointerException("Plugin must have a config"); - } - } catch (Exception e) { - LOGGER.error("Failed to load plugin '{}'", preload.description().id(), e); - pluginInfos.remove(preload); - if (Registry.pluginRegistry().get(preload.description().id()) != null) Registry.pluginRegistry().unregister(preload.description().id()); - } - } - public void preloadAllPlugins(File folder) { - File[] jars = folder.listFiles((dir, name) -> name.endsWith(".jar")); - if (jars == null) return; - - List plugins = new ArrayList<>(); - - for (File jar : jars) { - PreLoadedPlugin m = loadPluginFromJar(jar); - if (m != null) { - plugins.add(m); - } - } - - // Check for duplicate ids - Set ids = new HashSet<>(); - for (PreLoadedPlugin p : plugins) { - if (!ids.add(p.description().id())) { - LOGGER.error("Duplicate plugin id '{}', aborting", p.description().id()); - throw new IllegalStateException("Duplicate plugin id"); - } - } - - PluginSort.sortPlugins(plugins).forEach((p) -> pluginInfos.add(p)); - } - public void preloadBuiltinPlugins() { - LOGGER.info("Preloading built-in plugins..."); - Registry.builtinPluginRegistry().keyStream().forEach((id) -> { - Class clazz = Registry.builtinPluginRegistry().get(id); - try { - PluginDescription description = clazz.getDeclaredConstructor().newInstance().getDescriptionAnnotation(); - pluginInfos.add(new PreLoadedPlugin(description, clazz, null, null)); - } catch (Exception e) { - LOGGER.error("Failed to preload built-in plugin '{}'", id, e); - } - }); - } - public void loadAllPreloadedPlugins() { - pluginInfos.forEach(this::load); - } - public void enablePlugins() { - LOGGER.info("Enabling plugins..."); - pluginInfos.forEach((p) -> { - Plugin plugin = Registry.pluginRegistry().get(p.description().id()); - if (plugin.getConfig().isEnabledOnStart()) { - plugin.enable(); - } - }); - } - public void unloadPlugins() { - LOGGER.info("Unloading plugins..."); - Collections.reverse(pluginInfos); - pluginInfos.forEach((p) -> { - Plugin plugin = Registry.pluginRegistry().get(p.description().id()); - plugin.getConfig().save(); - if (plugin != null && plugin.isEnabled()) { - plugin.disable(); - } - Registry.pluginRegistry().unregister(plugin.getId()); - - try { - if (p.classLoader() != null) - p.classLoader().close(); - if (p.resourceLoader() != null) - p.resourceLoader().close(); - } catch (IOException e) { - LOGGER.error("Failed to unload plugin '{}'", plugin.getId()); - } - }); - pluginInfos.clear(); - } - - - - private void registerPlugin(Plugin plugin) { - if (Registry.pluginRegistry().keyStream().anyMatch(plugin.getId()::equals)) { - throw new IllegalStateException("Duplicate module id: " + plugin.getId()); - } - Registry.pluginRegistry().register(plugin.getId(), plugin); - } - public void preloadPlugins() { - LOGGER.info("Preloading plugins from directory \"plugins\"..."); - preloadBuiltinPlugins(); - preloadAllPlugins(new File("plugins")); - } - public void registerPlugins() { - LOGGER.info("Registering plugins from directory \"plugins\"..."); - loadAllPreloadedPlugins(); - } -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginSort.java b/src/main/java/de/igslandstuhl/database/plugins/PluginSort.java deleted file mode 100644 index 05f59d4..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginSort.java +++ /dev/null @@ -1,57 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class PluginSort { - private PluginSort() {} - private static void visit( - PreLoadedPlugin plugin, - Map map, - List sorted, - Set visited, - Set visiting - ) { - String id = plugin.description().id(); - - if (visited.contains(id)) return; - - if (visiting.contains(id)) { - throw new IllegalStateException("Circular dependency detected: " + id); - } - - visiting.add(id); - - for (String dep : plugin.description().depends()) { - PreLoadedPlugin dependency = map.get(dep); - if (dependency == null) { - throw new IllegalStateException("Missing dependency: " + dep + " for " + id); - } - visit(dependency, map, sorted, visited, visiting); - } - - visiting.remove(id); - visited.add(id); - sorted.add(plugin); - } - public static List sortPlugins(List plugins) { - Map map = new HashMap<>(); - for (PreLoadedPlugin m : plugins) { - map.put(m.description().id(), m); - } - - List sorted = new ArrayList<>(); - Set visited = new HashSet<>(); - Set visiting = new HashSet<>(); - - for (PreLoadedPlugin m : plugins) { - visit(m, map, sorted, visited, visiting); - } - - return sorted; - } -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/PreLoadedPlugin.java b/src/main/java/de/igslandstuhl/database/plugins/PreLoadedPlugin.java deleted file mode 100644 index dcb82df..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/PreLoadedPlugin.java +++ /dev/null @@ -1,12 +0,0 @@ -package de.igslandstuhl.database.plugins; - -import java.net.URLClassLoader; - -record PreLoadedPlugin ( - PluginDescription description, - Class clazz, - URLClassLoader classLoader, - URLClassLoader resourceLoader -) { - -} \ No newline at end of file diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/BoolSetting.java b/src/main/java/de/igslandstuhl/database/plugins/config/BoolSetting.java deleted file mode 100644 index 1e368ff..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/config/BoolSetting.java +++ /dev/null @@ -1,31 +0,0 @@ -package de.igslandstuhl.database.plugins.config; - -public class BoolSetting extends PluginSetting { - public BoolSetting(String key, String name, String description, boolean defaultValue) { - super(key, name, description, defaultValue); - } - - public void toggle() { - setValue(!getValue()); - } - public void enable() { - setValue(true); - } - public void disable() { - setValue(false); - } - public boolean isEnabled() { - return getValue(); - } - - @Override - public String toJSON() { - return "{" + - "\"key\":\"" + getKey() + "\"," + - "\"name\":\"" + getName() + "\"," + - "\"description\":\"" + getDescription() + "\"," + - "\"defaultValue\":" + getDefaultValue() + "," + - "\"value\":" + getValue() + - "}"; - } -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/IntSetting.java b/src/main/java/de/igslandstuhl/database/plugins/config/IntSetting.java deleted file mode 100644 index c128bf6..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/config/IntSetting.java +++ /dev/null @@ -1,41 +0,0 @@ -package de.igslandstuhl.database.plugins.config; - -public class IntSetting extends PluginSetting { - private int minValue = Integer.MIN_VALUE; - private int maxValue = Integer.MAX_VALUE; - public IntSetting(String key, String name, String description, int defaultValue) { - super(key, name, description, defaultValue); - } - - @Override - public String toJSON() { - return "{" + - "\"key\":\"" + getKey() + "\"," + - "\"name\":\"" + getName() + "\"," + - "\"description\":\"" + getDescription() + "\"," + - "\"defaultValue\":" + getDefaultValue() + "," + - "\"value\":" + getValue() + "," + - "\"minValue\":" + minValue + "," + - "\"maxValue\":" + maxValue + - "}"; - } - public int getMinValue() { - return minValue; - } - public void setMinValue(int minValue) { - if (minValue > maxValue) throw new IllegalArgumentException("minValue cannot be greater than maxValue"); - this.minValue = minValue; - } - public int getMaxValue() { - return maxValue; - } - public void setMaxValue(int maxValue) { - if (maxValue < minValue) throw new IllegalArgumentException("maxValue cannot be less than minValue"); - this.maxValue = maxValue; - } - public void setBounds(int minValue, int maxValue) { - if (minValue > maxValue) throw new IllegalArgumentException("minValue cannot be greater than maxValue"); - this.minValue = minValue; - this.maxValue = maxValue; - } -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java b/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java deleted file mode 100644 index e7724bc..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/config/PluginConfig.java +++ /dev/null @@ -1,193 +0,0 @@ -package de.igslandstuhl.database.plugins.config; - -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonObject; - -import de.igslandstuhl.database.plugins.Plugin; -import de.igslandstuhl.database.plugins.PluginLoader; - -public abstract class PluginConfig { - private final T plugin; - private final BoolSetting[] boolSettings; - private final IntSetting[] intSettings; - private final ShortAnswerSetting[] shortAnswerSettings; - - private final File configFile; - private boolean enabledOnStart; - - public PluginConfig(T plugin, PluginSetting... moduleSettings) { - this(plugin, Arrays.asList(moduleSettings)); - } - - public PluginConfig(T plugin, List> moduleSettings) { - this.plugin = plugin; - List boolSettings = moduleSettings.stream().filter((s) -> s instanceof BoolSetting).map((s) -> (BoolSetting) s).toList(); - this.boolSettings = boolSettings.toArray(new BoolSetting[boolSettings.size()]); - List intSettings = moduleSettings.stream().filter((s) -> s instanceof IntSetting).map((s) -> (IntSetting) s).toList(); - this.intSettings = intSettings.toArray(new IntSetting[intSettings.size()]); - List shortAnswerSettings = moduleSettings.stream().filter((s) -> s instanceof ShortAnswerSetting).map((s) -> (ShortAnswerSetting) s).toList(); - this.shortAnswerSettings = shortAnswerSettings.toArray(new ShortAnswerSetting[shortAnswerSettings.size()]); - this.configFile = new File("plugins/config", plugin.getId() + ".json"); - load(); - } - - public T getPlugin() { - return plugin; - } - public boolean isEnabledOnStart() { - return enabledOnStart; - } - - public PluginSetting getSetting(String key) { - Optional> boolSetting = findBoolSetting(key).map((s) -> (PluginSetting) s); - if (boolSetting.isPresent()) { - return boolSetting.get(); - } - Optional> intSetting = findIntSetting(key).map((s) -> (PluginSetting) s); - if (intSetting.isPresent()) { - return intSetting.get(); - } - return findShortAnswerSetting(key).map((s) -> (PluginSetting) s).orElse(null); - } - - private Optional findBoolSetting(String key) { - return Arrays.stream(boolSettings) - .filter((s) -> s.getKey().equals(key)) - .findAny(); - } - public boolean getBool(String key) { - return findBoolSetting(key).map(BoolSetting::getValue).orElse(false); - } - public void setBool(String key, boolean value) { - findBoolSetting(key).ifPresent((s) -> s.setValue(value)); - save(); - } - public void enableSetting(String key) { - findBoolSetting(key).ifPresent(BoolSetting::enable); - save(); - } - public void disableSetting(String key) { - findBoolSetting(key).ifPresent(BoolSetting::disable); - save(); - } - public void toggleSetting(String key) { - findBoolSetting(key).ifPresent(BoolSetting::toggle); - save(); - } - - private Optional findIntSetting(String key) { - return Arrays.stream(intSettings) - .filter((s) -> s.getKey().equals(key)) - .findAny(); - } - private Optional findShortAnswerSetting(String key) { - return Arrays.stream(shortAnswerSettings) - .filter((s) -> s.getKey().equals(key)) - .findAny(); - } - - private JsonObject valuesJSON() { - JsonObject values = new JsonObject(); - for (BoolSetting s : boolSettings) { - values.addProperty(s.getKey(), s.getValue()); - } - for (IntSetting s : intSettings) { - values.addProperty(s.getKey(), s.getValue()); - } - for (ShortAnswerSetting s : shortAnswerSettings) { - values.addProperty(s.getKey(), s.getValue()); - } - return values; - } - public String toJSON() { - StringBuilder builder = new StringBuilder("{"); - builder.append("\"settings\": {") - .append("\"bools\": ["); - for (int i = 0; i < boolSettings.length; i++) { - builder.append(boolSettings[i].toJSON()); - if (i < boolSettings.length - 1) { - builder.append(", "); - } - } - builder - .append("], ") - .append("\"ints\": ["); - for (int i = 0; i < intSettings.length; i++) { - builder.append(intSettings[i].toJSON()); - if (i < intSettings.length - 1) { - builder.append(", "); - } - } - builder - .append("], ") - .append("\"shortAnswers\": ["); - for (int i = 0; i < shortAnswerSettings.length; i++) { - builder.append(shortAnswerSettings[i].toJSON()); - if (i < shortAnswerSettings.length - 1) { - builder.append(", "); - } - } - builder - .append("},") - .append("\"values\": ") - .append((new Gson()).toJson(valuesJSON())) - .append("}"); - return builder.toString(); - } - - // Persistence - public void save() { - if (configFile.getParentFile() != null && !configFile.getParentFile().exists()) { - configFile.getParentFile().mkdirs(); - } - try (FileWriter writer = new FileWriter(configFile)) { - JsonObject root = new JsonObject(); - root.add("values", valuesJSON()); - root.addProperty("enabled", plugin.isEnabled()); - - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - gson.toJson(root, writer); - } catch (IOException e) { - PluginLoader.LOGGER.error("Failed to save plugin config for {}", plugin.getId(), e); - } - } - public void load() { - if (!configFile.exists()) return; - try (FileReader reader = new FileReader(configFile)) { - Gson gson = new Gson(); - JsonObject root = gson.fromJson(reader, JsonObject.class); - - JsonObject values = root.getAsJsonObject("values"); - if (values != null) { - for (BoolSetting s : boolSettings) { - if (values.has(s.getKey())) { - s.setValue(values.get(s.getKey()).getAsBoolean()); - } - } - for (IntSetting s : intSettings) { - if (values.has(s.getKey())) { - s.setValue(values.get(s.getKey()).getAsInt()); - } - } - for (ShortAnswerSetting s : shortAnswerSettings) { - if (values.has(s.getKey())) { - s.setValue(values.get(s.getKey()).getAsString()); - } - } - } - enabledOnStart = root.get("enabled").getAsBoolean(); - - } catch (IOException e) { - PluginLoader.LOGGER.error("Failed to load plugin config for {}", plugin.getId(), e); - } - } -} \ No newline at end of file diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/PluginSetting.java b/src/main/java/de/igslandstuhl/database/plugins/config/PluginSetting.java deleted file mode 100644 index 0d632fa..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/config/PluginSetting.java +++ /dev/null @@ -1,49 +0,0 @@ -package de.igslandstuhl.database.plugins.config; - -public class PluginSetting { - private final String key; - private final String name; - private final String description; - private final T defaultValue; - private T value; - - PluginSetting(String key, String name, String description, T defaultValue) { - this.key = key; - this.name = name; - this.description = description; - this.defaultValue = defaultValue; - this.value = defaultValue; - } - - public String getKey() { - return key; - } - public String getName() { - return name; - } - public String getDescription() { - return description; - } - public T getDefaultValue() { - return defaultValue; - } - - public T getValue() { - return value; - } - - public void setValue(T value) { - this.value = value; - } - - public String toJSON() { - return "{" + - "\"key\":\"" + key + "\"," + - "\"name\":\"" + name + "\"," + - "\"description\":\"" + description + "\"," + - "\"defaultValue\":\"" + defaultValue + "\"," + - "\"value\":\"" + value + "\"" + - "}"; - } - -} diff --git a/src/main/java/de/igslandstuhl/database/plugins/config/ShortAnswerSetting.java b/src/main/java/de/igslandstuhl/database/plugins/config/ShortAnswerSetting.java deleted file mode 100644 index 09c56a0..0000000 --- a/src/main/java/de/igslandstuhl/database/plugins/config/ShortAnswerSetting.java +++ /dev/null @@ -1,18 +0,0 @@ -package de.igslandstuhl.database.plugins.config; - -public class ShortAnswerSetting extends PluginSetting { - public ShortAnswerSetting(String key, String name, String description, String defaultValue) { - super(key, name, description, defaultValue); - } - - @Override - public String toJSON() { - return "{" + - "\"key\":\"" + getKey() + "\"," + - "\"name\":\"" + getName() + "\"," + - "\"description\":\"" + getDescription() + "\"," + - "\"defaultValue\":\"" + getDefaultValue() + "\"," + - "\"value\":\"" + getValue() + "\"" + - "}"; - } -} From e3623b9688fd2a973913d16c3f6f4451a5339ebf Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Thu, 18 Jun 2026 17:54:20 +0200 Subject: [PATCH 21/26] Now registering plugin-loader as builtin plugin --- build.gradle.kts | 2 +- src/main/java/de/igslandstuhl/database/Application.java | 6 ++++++ .../database/plugins/PluginResourceProvider.java | 1 + .../igslandstuhl/database/server/sql/SQLiteConnection.java | 2 +- 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index db0a157..760d621 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -38,7 +38,7 @@ dependencies { implementation("ch.qos.logback:logback-classic:1.5.6") // built-in plugins - implementation("de.igs-landstuhl:plugin-loader:v1.0.1") + implementation("de.igs-landstuhl:plugin-loader:v1.0.4") testImplementation("org.junit.jupiter:junit-jupiter:5.13.4") // using JUnit 5 (latest) testRuntimeOnly("org.junit.platform:junit-platform-launcher") diff --git a/src/main/java/de/igslandstuhl/database/Application.java b/src/main/java/de/igslandstuhl/database/Application.java index b1ac18e..7884e4c 100644 --- a/src/main/java/de/igslandstuhl/database/Application.java +++ b/src/main/java/de/igslandstuhl/database/Application.java @@ -102,11 +102,17 @@ public Topic[] readFile(String file) throws SerializationException, SQLException return topics.toArray(topicsArr); } + private static void registerBuiltinPlugins() { + LOGGER.info("Registering built-in plugins..."); + Registry.builtinPluginRegistry().register("plugin-loader", de.igslandstuhl.database.plugins.PluginLoader.class); + } + public static void main(String[] args) throws Exception { LOGGER.info("Starting up student-database..."); instance = new Application(args); + registerBuiltinPlugins(); PluginLoader.getInstance().preloadPlugins(); if (!getInstance().suppressCmd()) { diff --git a/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java b/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java index 247b968..2cb6e16 100644 --- a/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java +++ b/src/main/java/de/igslandstuhl/database/plugins/PluginResourceProvider.java @@ -43,6 +43,7 @@ public List openAll(ResourceLocation location) { for (PreLoadedPlugin module : PluginLoader.getInstance().getPluginInfos()) { ClassLoader cl = module.resourceLoader(); + if (cl == null) continue; // built-in plugin InputStream stream = cl.getResourceAsStream(path); if (stream != null) { diff --git a/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java b/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java index 7208b49..03f2364 100644 --- a/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java +++ b/src/main/java/de/igslandstuhl/database/server/sql/SQLiteConnection.java @@ -80,7 +80,7 @@ public PreparedStatement prepareStatement(String sql) throws SQLException { public ResultSet executeStatementQuerySecure(PreparedStatement statement) throws SQLException { lock.readLock().lock(); try (statement) { - return statement.executeQuery(); + return statement.executeQuery(); } finally { lock.readLock().unlock(); } From 08f02697dcdfba3822a979dbb81fcd8d01a07e9d Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Sun, 28 Jun 2026 14:14:37 +0200 Subject: [PATCH 22/26] Little bug fix --- build.gradle.kts | 3 +-- .../database/server/webserver/responses/PostResponse.java | 4 +++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/build.gradle.kts b/build.gradle.kts index 760d621..648b95e 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -31,14 +31,13 @@ dependencies { implementation("commons-codec:commons-codec:1.19.0") implementation("com.googlecode.owasp-java-html-sanitizer:owasp-java-html-sanitizer:20260101.1") implementation("org.jline:jline:3.30.6") // for better console input handling - implementation("org.yaml:snakeyaml:2.2") // plugin imports // Logging implementation("org.slf4j:slf4j-api:2.0.13") implementation("ch.qos.logback:logback-classic:1.5.6") // built-in plugins - implementation("de.igs-landstuhl:plugin-loader:v1.0.4") + implementation("de.igs-landstuhl:plugin-loader:v1.0.5") testImplementation("org.junit.jupiter:junit-jupiter:5.13.4") // using JUnit 5 (latest) testRuntimeOnly("org.junit.platform:junit-platform-launcher") diff --git a/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java b/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java index 9226521..f2d373a 100644 --- a/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java +++ b/src/main/java/de/igslandstuhl/database/server/webserver/responses/PostResponse.java @@ -6,6 +6,7 @@ import com.google.gson.Gson; import de.igslandstuhl.database.server.Server; +import de.igslandstuhl.database.server.WebServer; import de.igslandstuhl.database.server.resources.ResourceLocation; import de.igslandstuhl.database.server.webserver.AccessManager; import de.igslandstuhl.database.server.webserver.ContentType; @@ -107,7 +108,7 @@ public void respond(PrintStream out) { out.print("HTTP/1.1 "); statusCode.write(out); out.print("\r\n"); - out.print("Content-Type: " + contentType + "; charset=UTF-8\r\n"); + out.print("Content-Type: " + contentType.getName() + "; charset=UTF-8\r\n"); if (cookie != null) { out.print("Set-Cookie: " + cookie + "; HttpOnly; Secure\r\n"); } @@ -116,6 +117,7 @@ public void respond(PrintStream out) { } out.print("\r\n"); if (body != null) { + WebServer.LOGGER.debug("Response body: {}", body); out.print(body); } out.flush(); From 46f6e869bebe19258b25639cc0f19743fcf62fa0 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Wed, 1 Jul 2026 13:11:41 +0200 Subject: [PATCH 23/26] Updated gradle wrapper to 9.6.0 --- gradle/wrapper/gradle-wrapper.properties | 2 +- gradlew.bat | 184 +++++++++++------------ 2 files changed, 93 insertions(+), 93 deletions(-) diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index a441313..7e7d24f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/gradlew.bat b/gradlew.bat index 25da30d..7101f8e 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,92 +1,92 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega From a771e301a6c26cf1762ec5ae7c64d6133a7aaf89 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Wed, 1 Jul 2026 13:16:12 +0200 Subject: [PATCH 24/26] Added maven publish functionality --- .github/workflows/publish.yml | 27 ++++++++++++++++ build.gradle.kts | 58 +++++++++++++++++++---------------- 2 files changed, 58 insertions(+), 27 deletions(-) create mode 100644 .github/workflows/publish.yml diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..8c4a6e3 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,27 @@ +# .github/workflows/publish.yml + +name: Publish +on: + release: + types: [released, prereleased] +jobs: + publish: + name: Release build and publish + runs-on: macOS-latest + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + distribution: 'zulu' + java-version: 21 + - name: Publish to MavenCentral + run: ./gradlew publishToMavenCentral --no-configuration-cache + env: + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.SIGNING_KEY_ID }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_KEY_CONTENTS }} + diff --git a/build.gradle.kts b/build.gradle.kts index 648b95e..561df6f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -2,10 +2,10 @@ plugins { java application id("com.github.johnrengelman.shadow") version "8.1.1" - id("maven-publish") + id("com.vanniktech.maven.publish") version "0.37.0" } -group = "igs-landstuhl" +group = "io.github.learn-monitor" version = "v2.0.0-SNAPSHOT-2" @@ -15,14 +15,6 @@ application { repositories { mavenCentral() - maven { - name = "Plugin Loader Repository" - url = uri("https://maven.pkg.github.com/Learn-Monitor/plugin-loader/") - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") - } - } } dependencies { @@ -37,7 +29,7 @@ dependencies { implementation("ch.qos.logback:logback-classic:1.5.6") // built-in plugins - implementation("de.igs-landstuhl:plugin-loader:v1.0.5") + implementation("io.github.learn-monitor:plugin-loader:v1.0.5") testImplementation("org.junit.jupiter:junit-jupiter:5.13.4") // using JUnit 5 (latest) testRuntimeOnly("org.junit.platform:junit-platform-launcher") @@ -67,26 +59,38 @@ java { } } -publishing { - publications { - create("mavenJava") { - from(components["java"]) +mavenPublishing { + publishToMavenCentral() - groupId = "igs-landstuhl" - artifactId = "student-database" - version = project.version.toString() - } - } + signAllPublications() + + coordinates(group.toString(), "student-database", version.toString()) - repositories { - maven { - name = "GitHubPackages" - url = uri("https://maven.pkg.github.com/Learn-Monitor/student-database/") + pom { + name = "Student database" + description = "A Java-based application designed to manage and store student information efficiently. It allows admins to perform CRUD (Create, Read, Update, Delete) operations on student records, classes, subjects, and other school-related data, making it a valuable tool for educational institutions. Students can view their progress, and teachers can assign them topics, based on subjects." + url = "https://github.com/Learn-Monitor/student-database" - credentials { - username = System.getenv("GITHUB_ACTOR") - password = System.getenv("GITHUB_TOKEN") + licenses { + license { + name = "GNU General Public License v3.0" + url = "http://www.gnu.org/licenses/gpl-3.0.txt" } } + developers { + developer { + id = "schlaumeier5" + name = "Lukas Morgenstern" + url = "https://github.com/schlaumeier5" + } + } + scm { + url = "https://github.com/Learn-Monitor/student-database" + connection = "scm:git:https://github.com/Learn-Monitor/student-database.git" + developerConnection = "scm:git:ssh://git@github.com/Learn-Monitor/student-database.git" + } } +} +tasks.withType().configureEach { + dependsOn(tasks.withType()) } \ No newline at end of file From 88affc3c2f68743b0e0cab2e03554cdab5379bcc Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Wed, 1 Jul 2026 13:19:09 +0200 Subject: [PATCH 25/26] Changed to GradleUp shadow for integration with Gradle 9 --- build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index 561df6f..8522932 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,7 +1,7 @@ plugins { java application - id("com.github.johnrengelman.shadow") version "8.1.1" + id("com.gradleup.shadow") version "9.4.3" id("com.vanniktech.maven.publish") version "0.37.0" } From 0537d27ce7c2d9421d8bd89884f6e622f94d77f3 Mon Sep 17 00:00:00 2001 From: Schlaumeier5 Date: Wed, 1 Jul 2026 13:20:45 +0200 Subject: [PATCH 26/26] Bumped version to v2.0.0-SNAPSHOT-3 --- build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build.gradle.kts b/build.gradle.kts index 8522932..e7a8a26 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,7 +7,7 @@ plugins { group = "io.github.learn-monitor" -version = "v2.0.0-SNAPSHOT-2" +version = "v2.0.0-SNAPSHOT-3" application { mainClass.set("de.igslandstuhl.database.Application")