Compare commits

..

No commits in common. "573e17161b036bba4b68a44ec0a8935a69030834" and "e16f0342a79efe16a4a131596130a060af7e8812" have entirely different histories.

7 changed files with 48 additions and 920 deletions

View File

@ -1,145 +0,0 @@
package com.bib.essensbestellungsverwaltung;
/*
@author Malte Schulze Hobeling
*/
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
public class AccountMgr {
protected static double price = 5.0;
/**
* creates a user with createUser(...) and adds its id to the 'worker' table
* @param userData String[] name, firstname, password, email
* @param addressData String[] street, number, plz, city
* @return userid or -1
*/
public static long createWorker(String[] userData, String[] addressData){
long id = createUser(userData, addressData);
String sId = String.valueOf(id);
Database.insert("worker", new String[]{"userid"}, new String[]{sId});
return id;
}
/**
* creates a user with createUser(...) and adds its id to the 'parent' table
* @param userData String[] name, firstname, password, email
* @param addressData String[] street, number, plz, city
* @return userid or -1
*/
public static long createParent(String[] userData, String[] addressData){
long id = createUser(userData, addressData);
String sId = String.valueOf(id);
Database.insert("parent", new String[]{"userid"}, new String[]{sId});
return id;
}
/**
* adds a user to the database
* @param userData String[] name, firstname, password, email
* @param addressData String[] street, number, plz, city
* @return userid or -1
*/
private static long createUser(String[] userData, String[] addressData) {
String[] addressH = {"street", "number", "plz", "city"};
String[] userH = {"name", "firstname", "addressid", "password", "email"};
String name = userData[0];
String firstname = userData[1];
String pw = hashAndSalt(userData[2]);
String email = userData[3];
long id = Database.insert("address", addressH, addressData);
String sId = String.valueOf(id);
String[] userD = {name, firstname, sId, pw, email};
id = Database.insert("user", userH, userD);
return id;
}
public static long createChild(String[] childData,String[] allergyData, String[] severityData){
String[] childH = {"name","firstname","addressid"};
String[] child_allergyH = {"childid","allergyid","severityid"};
long id = Database.insert("child", childH, childData);
if(allergyData.length > 0){
for(int i = 0; i < allergyData.length; i++){
String sId = String.valueOf(id);
String[] child_allergyD = {sId,allergyData[i],severityData[i]};
Database.insert("child_allergy",child_allergyH,child_allergyD);
}
}
return id;
}
public static long matchParentChild(String parentId, String childId){
String[] parent_childH = {"parentuserid","childid"};
String[] parent_childD = {parentId,childId};
return Database.insert("parent_child", parent_childH,parent_childD);
}
public static long login(String email, String pw){
String[] userH = {"email","password"};
String[] userD = {email,hashAndSalt(pw)};
return Database.getSingleId("user",userH,userD);
}
public static boolean isWorker(String id){
String[] workerH = {"userid"};
String[] workerD = {id};
long workerId = Database.getSingleId("worker",workerH,workerD);
return workerId > 0;
}
public static boolean isParent(String id){
String[] parentH = {"userid"};
String[] parentD = {id};
long parentId = Database.getSingleId("parent",parentH,parentD);
return parentId > 0;
}
public static String hashAndSalt(String pw){
//todo: find a better way to salt
byte[] magicSalt = new byte[]{96, 13, 100, 85, -37, 52, -123, 86, -123, -92, 16, 15, -110, -42, -49, 0};
KeySpec spec = new PBEKeySpec(pw.toCharArray(), magicSalt,310001,256);
String hashedPw;
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] hash = factory.generateSecret(spec).getEncoded();
Base64.Encoder enc = Base64.getEncoder();
hashedPw = enc.encodeToString(hash);
} catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
return hashedPw;
}
public static List<String> getInvoice(String date, String childId){
List<String> invoice = new ArrayList<>();
invoice.add("Monatsabrechnung " + date);
List<String> child = Database.getEntryById("child", Long.parseLong(childId));
String[] childParts = child.get(0).split(":");
invoice.add(childParts[1] + ", " + childParts[2]);
String[] food_planH = {"date"};
String[] food_planD = {date+"%"};
List<String> food_plan = Database.select("food_plan",food_planH,food_planD);
for (String day : food_plan) {
String[] food_planParts = day.split(":");
String[] food_selectionH = {"childid","food_planid"};
String[] food_selectionD = {childId,food_planParts[0]};
List<String> food_selection = Database.select("food_selection",food_selectionH,food_selectionD);
for (String food_select : food_selection) {
String[] food_selectParts = food_select.split(":");
List<String> food = Database.getEntryById("food",Long.parseLong(food_selectParts[3]));
String[] foodParts = food.get(0).split(":");
String line = food_planParts[1] + ": " + foodParts[1];
invoice.add(line);
}
}
invoice.add("Total: " + (invoice.size()-2) + " X " + price + "€ = " + ((invoice.size()-2)*price) + "");
return invoice;
}
}

View File

@ -1,295 +0,0 @@
package com.bib.essensbestellungsverwaltung;
/*
@author Malte Schulze Hobeling
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ConsoleLib {
public static void createWorkerPrompt(){
Scanner sc = new Scanner(System.in);
System.out.println("Registrierung eines neuen Mitarbeiters");
String[] userData = new String[4];
String[] addressData = new String[4];
System.out.print("Nachname: ");
userData[0] = sc.nextLine();
System.out.print("Vorname: ");
userData[1] = sc.nextLine();
System.out.print("Straße: ");
addressData[0] = sc.nextLine();
System.out.print("Hausnummer: ");
addressData[1] = sc.nextLine();
System.out.print("Postleitzahl: ");
addressData[2] = sc.nextLine();
System.out.print("Stadt: ");
addressData[3] = sc.nextLine();
System.out.print("Email: ");
userData[3] = sc.nextLine();
System.out.print("Passwort: ");
userData[2] = sc.nextLine();
long id = AccountMgr.createWorker(userData,addressData);
if(id < 1){
System.out.println("Fehler beim erstellen");
}
}
public static void createParentPrompt(){
Scanner sc = new Scanner(System.in);
System.out.println("Registrierung eines neuen Elternteils");
String[] userData = new String[4];
String[] addressData = new String[4];
System.out.print("Nachname: ");
userData[0] = sc.nextLine();
System.out.print("Vorname: ");
userData[1] = sc.nextLine();
System.out.print("Straße: ");
addressData[0] = sc.nextLine();
System.out.print("Hausnummer: ");
addressData[1] = sc.nextLine();
System.out.print("Postleitzahl: ");
addressData[2] = sc.nextLine();
System.out.print("Stadt: ");
addressData[3] = sc.nextLine();
System.out.print("Email: ");
userData[3] = sc.nextLine();
System.out.print("Passwort: ");
userData[2] = sc.nextLine();
long id = AccountMgr.createParent(userData,addressData);
if(id < 1){
System.out.println("Fehler beim erstellen");
}
}
public static void createChildPrompt(String parentId){
Scanner sc = new Scanner(System.in);
String[] childData = new String[3];
System.out.println("Registrierung eines neuen Kindes");
System.out.print("Nachname: ");
childData[0] = sc.nextLine();
System.out.print("Vorname: ");
childData[1] = sc.nextLine();
System.out.println("Bitte geben Sie die Nummer der passenden Adresse an: ");
for (String s : Database.getTable("address")) {
String[] parts = s.split(":");
System.out.printf("Nr.: %s Straße: %s Hausnr.: %s PLZ: %s Stadt: %s%n",parts[0],parts[1],parts[2],parts[3],parts[4]);
}
System.out.print("Adressnummer: ");
childData[2] = sc.nextLine();
for (String s : Database.getTable("allergy")) {
String[] parts = s.split(":");
System.out.printf("Nr. %s %s%n",parts[0],parts[1]);
}
System.out.println("Bitte Geben Sie die Nr der Allergien und Ihre Schwere an: ");
System.out.print("Allergien (Nr mit , getrennt[1,4,5,16]): ");
String allergies = sc.nextLine();
String[] allergyData = allergies.split(",");
System.out.print("Schweren (1 Harmlos - 3 Kritisch[2,3,1,3]): ");
String severities = sc.nextLine();
String[] severityData = severities.split(",");
long id = AccountMgr.createChild(childData,allergyData,severityData);
if(id < 1){
System.out.println("Fehler beim erstellen");
return;
}
String sId = String.valueOf(id);
if(AccountMgr.matchParentChild(parentId,sId) == -1){
System.out.println("Fehler beim verknüpfen");
}
}
public static void createFoodPrompt(){
Scanner sc = new Scanner(System.in);
String[] foodData = new String[4];
System.out.println("Registrierung eines neuen Essens");
System.out.print("Name: ");
foodData[0] = sc.nextLine();
System.out.print("Beschreibung: ");
foodData[1] = sc.nextLine();
System.out.print("Ist es ein Dessert?[0/1]: ");
foodData[2] = sc.nextLine();
System.out.print("Ist es vegan[1], vegetarisch[2] oder fleischhaltig[3]: ");
foodData[3] = sc.nextLine();
for (String s : Database.getTable("allergy")) {
String[] parts = s.split(":");
System.out.printf("Nr. %s %s%n",parts[0],parts[1]);
}
System.out.println("Bitte geben Sie die Nr. aller zutreffenden Allergien mit Komma getrennt an [1,3,6]");
System.out.print("Allergienummer: ");
String allergies = sc.nextLine();
String[] allergyData = allergies.split(",");
if(FoodMgr.createFood(foodData,allergyData) < 1){
System.out.println("Fehler");
}
}
public static long loginPrompt(){
System.out.println("Login");
Scanner sc = new Scanner(System.in);
long id = -1;
while (id == -1){
System.out.print("Email: ");
String email = sc.nextLine();
System.out.print("Passwort: ");
String pw = sc.nextLine();
id = AccountMgr.login(email,pw);
if(id == -1){
System.out.println("Login fehlgeschlagen");
}
}
System.out.println("Login erfolgreich");
return id;
}
public static void matchParentChildPrompt(String parentId){
System.out.println("Wählen Sie ihr Kind aus: ");
Database.getTable("child");
Scanner sc = new Scanner(System.in);
System.out.print("Nr: ");
String childId = sc.nextLine();
if(AccountMgr.matchParentChild(parentId,childId) == -1){
System.out.println("Fehler");
}
}
public static void tablePrompt(){
Scanner sc = new Scanner(System.in);
System.out.print("Table: ");
String table = sc.nextLine();
printConsole(Database.getTable(table));
}
public static void deletePrompt(){
Scanner sc = new Scanner(System.in);
System.out.println("Löschen");
System.out.print("Tabelle: ");
String table = sc.nextLine();
System.out.print("Id: ");
long id = sc.nextLong();
sc.nextLine();
Database.delete(table,id);
}
public static void printConsole(List<String> list){
for (String entry : list) {
System.out.println(entry);
}
}
public static void createFood_planPrompt(){
System.out.println("Erstellen eines Essensplans");
String[] food_planData = new String[5];
Scanner sc = new Scanner(System.in);
System.out.print("Bitte geben Sie das Datum im Format YYYY-MM-DD an: ");
food_planData[0] = sc.nextLine();
printConsole(FoodMgr.getVeganFood(false));
System.out.print("Veganes Hauptgericht Nr: ");
food_planData[1] = sc.nextLine();
printConsole(FoodMgr.getFood(false));
System.out.print("Zweites Hauptgericht Nr: ");
food_planData[2] = sc.nextLine();
printConsole(FoodMgr.getVeganFood(true));
System.out.print("Veganes Dessert Nr: ");
food_planData[3] = sc.nextLine();
printConsole(FoodMgr.getFood(true));
System.out.print("Zweites Dessert Nr: ");
food_planData[4] = sc.nextLine();
long id = FoodMgr.createFood_plan(food_planData);
if(id < 0){
System.out.println("Fehler");
}
}
public static void showFood_planPrompt(){
System.out.println("Essensplan zum Anzeigen auswählen");
Scanner sc = new Scanner(System.in);
System.out.print("Bitte geben Sie das Datum im Format YYYY-MM-DD an: ");
String date = sc.nextLine();
List<String> plan = FoodMgr.getFood_plan(date);
List<String> food = new ArrayList<>();
StringBuilder sb;
for (String day : plan) {
sb = new StringBuilder();
String[] parts = day.split(":");
sb.append("Tag: ");
sb.append(parts[1]);
sb.append(" Veganesgericht: ");
food = FoodMgr.getFoodById(Long.parseLong(parts[2]));
String[] foodParts = food.get(0).split(":");
sb.append(foodParts[1]);
sb.append(" Zweites Hauptgericht: ");
food = FoodMgr.getFoodById(Long.parseLong(parts[3]));
foodParts = food.get(0).split(":");
sb.append(foodParts[1]);
sb.append(" Veganesdessert: ");
food = FoodMgr.getFoodById(Long.parseLong(parts[4]));
foodParts = food.get(0).split(":");
sb.append(foodParts[1]);
sb.append(" Zweites Dessert: ");
food = FoodMgr.getFoodById(Long.parseLong(parts[5]));
foodParts = food.get(0).split(":");
sb.append(foodParts[1]);
food.add(sb.toString());
}
printConsole(food);
}
public static void createFood_selectionPrompt(){
System.out.println("Essensauswahl");
Scanner sc = new Scanner(System.in);
String[] food_selectionData = new String[3];
System.out.print("Kind ID: ");
food_selectionData[0] = sc.nextLine();
System.out.print("Datum: ");
String date = sc.nextLine();
String[] foodPlanParts = Database.select("food_plan", new String[]{"date"}, new String[]{date}).get(0).split(":");
food_selectionData[1] = foodPlanParts[0];
System.out.println("Hauptspeisen: ");
System.out.println(Database.select("food",new String[]{"id"},new String[]{foodPlanParts[2]}).get(0));
System.out.println(Database.select("food",new String[]{"id"},new String[]{foodPlanParts[3]}).get(0));
System.out.print("Id: ");
food_selectionData[2] = sc.nextLine();
if(FoodMgr.createFood_selection(food_selectionData) < 1){
System.out.println("Fehler");
}
System.out.println("Nachspeisen: ");
System.out.println(Database.select("food",new String[]{"id"},new String[]{foodPlanParts[4]}).get(0));
System.out.println(Database.select("food",new String[]{"id"},new String[]{foodPlanParts[5]}).get(0));
System.out.print("Id: ");
food_selectionData[2] = sc.nextLine();
if(FoodMgr.createFood_selection(food_selectionData) < 1){
System.out.println("Fehler");
}
}
public static void dayOrderPrompt(){
System.out.println("Zusammenfassung des Tages");
System.out.print("Datum eingeben: ");
Scanner sc = new Scanner(System.in);
String date = sc.nextLine();
List<String> dayOrder = FoodMgr.getDayOrder(date);
for (String food : dayOrder) {
System.out.println(food);
}
}
public static void invoicePrompt(){
System.out.println("Monatsabrechnung");
System.out.print("Monat(YYYY-MM): ");
Scanner sc = new Scanner(System.in);
String date = sc.nextLine();
System.out.print("ID des Kindes: ");
String id = sc.nextLine();
List<String> invoice = AccountMgr.getInvoice(date,id);
printConsole(invoice);
}
public static void changePricePrompt(){
System.out.print("Neuer Preis: ");
Scanner sc = new Scanner(System.in);
double price = sc.nextDouble();
sc.nextLine();
AccountMgr.price = price;
}
}

View File

@ -1,120 +0,0 @@
package com.bib.essensbestellungsverwaltung;
/*
@author Malte Schulze Hobeling
*/
import java.util.Scanner;
public class ConsoleMain {
static long currentUserId = -1;
static boolean isWorker = false;
static boolean isParent = false;
public static void main(String[] args) {
boolean firstRun = Database.init();
if(firstRun){
Database.createDb();
Database.fillDb();
ConsoleLib.createWorkerPrompt();
}
while (true){
if(currentUserId == -2){
break;
}else if(currentUserId < 0){
defaultMenu();
}else{
if(isWorker){
adminMenu();
}else if(isParent){
parentMenu();
}
}
}
}
public static void defaultMenu(){
System.out.println("1: Login");
System.out.println("2: Essensplan anzeigen");
System.out.println("3: Programm beenden");
System.out.print("Auswahl: ");
Scanner sc = new Scanner(System.in);
String selection = sc.nextLine();
switch (selection) {
case "1" -> {
currentUserId = ConsoleLib.loginPrompt();
isWorker = AccountMgr.isWorker(String.valueOf(currentUserId));
isParent = AccountMgr.isParent(String.valueOf(currentUserId));
}
case "2" -> ConsoleLib.showFood_planPrompt();
case "3" -> currentUserId = -2;
}
}
public static void adminMenu(){
System.out.println("0: Ausloggen");
System.out.println("1: Einen neuen Mitarbeiter anlegen");
System.out.println("2: Ein neues Elternteil anlegen");
System.out.println("3: Ein neues Kind anlegen");
System.out.println("4: Kind einem Elternteil zuordnen");
System.out.println("5: Ein neues Essen anlegen");
System.out.println("6: Table");
System.out.println("7: Einen Essensplan erstellen");
System.out.println("8: Essensplan anzeigen");
System.out.println("9: Löschen");
System.out.println("10: Essen auswählen");
System.out.println("11: Bestellungen des Tages sammeln");
System.out.println("12: Monatsabrechnung");
System.out.println("13: Preis ändern");
System.out.print("Auswahl: ");
Scanner sc = new Scanner(System.in);
String selection = sc.nextLine();
switch (selection) {
case "0" -> {
currentUserId = -1;
isWorker = false;
isParent = false;
}
case "1" -> ConsoleLib.createWorkerPrompt();
case "2" -> ConsoleLib.createParentPrompt();
case "3" -> ConsoleLib.createChildPrompt(String.valueOf(currentUserId));
case "4" -> ConsoleLib.matchParentChildPrompt(String.valueOf(currentUserId));
case "5" -> ConsoleLib.createFoodPrompt();
case "6" -> ConsoleLib.tablePrompt();
case "7" -> ConsoleLib.createFood_planPrompt();
case "8" -> ConsoleLib.showFood_planPrompt();
case "9" -> ConsoleLib.deletePrompt();
case "10" -> ConsoleLib.createFood_selectionPrompt();
case "11" -> ConsoleLib.dayOrderPrompt();
case "12" -> ConsoleLib.invoicePrompt();
case "13" -> ConsoleLib.changePricePrompt();
}
}
public static void parentMenu(){
System.out.println("0: Ausloggen");
System.out.println("3: Ein neues Kind anlegen");
System.out.println("4: Kind einem Elternteil zuordnen");
System.out.print("Auswahl: ");
Scanner sc = new Scanner(System.in);
String selection = sc.nextLine();
switch (selection) {
case "0" -> {
currentUserId = -1;
isWorker = false;
isParent = false;
}
case "3" -> ConsoleLib.createChildPrompt(String.valueOf(currentUserId));
case "4" -> ConsoleLib.matchParentChildPrompt(String.valueOf(currentUserId));
case "6" -> ConsoleLib.tablePrompt();
default -> {
}
}
}
}

View File

@ -1,6 +1,6 @@
package com.bib.essensbestellungsverwaltung; package com.bib.essensbestellungsverwaltung;
/* /*
@author Malte Schulze Hobeling @author Malte Schulze Hobeling
*/ */
import java.io.File; import java.io.File;
@ -13,10 +13,10 @@ import java.util.List;
public class Database { public class Database {
private static final String dbLocation = "jdbc:sqlite:"+Path.of("").toAbsolutePath()+"/database.db"; private static final String dbLocation = "jdbc:sqlite:"+Path.of("").toAbsolutePath()+"/database.db";
protected static boolean init(){ protected static void init(){
File db = new File(Path.of("").toAbsolutePath()+"/database.db"); File db = new File(Path.of("").toAbsolutePath()+"/database.db");
try { try {
return db.createNewFile(); db.createNewFile();
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
@ -44,17 +44,17 @@ public class Database {
sql[1] = """ sql[1] = """
CREATE TABLE IF NOT EXISTS food_type ( CREATE TABLE IF NOT EXISTS food_type (
id integer PRIMARY KEY, id integer PRIMARY KEY,
name text UNIQUE name text
);"""; );""";
sql[2] = """ sql[2] = """
CREATE TABLE IF NOT EXISTS allergy ( CREATE TABLE IF NOT EXISTS allergy (
id integer PRIMARY KEY, id integer PRIMARY KEY,
name text UNIQUE name text
);"""; );""";
sql[3] = """ sql[3] = """
CREATE TABLE IF NOT EXISTS severity ( CREATE TABLE IF NOT EXISTS severity (
id integer PRIMARY KEY, id integer PRIMARY KEY,
name text UNIQUE severity integer
);"""; );""";
sql[4] = """ sql[4] = """
CREATE TABLE IF NOT EXISTS user ( CREATE TABLE IF NOT EXISTS user (
@ -105,7 +105,7 @@ public class Database {
sql[10] = """ sql[10] = """
CREATE TABLE IF NOT EXISTS food ( CREATE TABLE IF NOT EXISTS food (
id integer PRIMARY KEY, id integer PRIMARY KEY,
name text UNIQUE, name text,
description text, description text,
isdessert integer, isdessert integer,
food_typeid integer, food_typeid integer,
@ -114,19 +114,18 @@ public class Database {
sql[11] = """ sql[11] = """
CREATE TABLE IF NOT EXISTS food_plan ( CREATE TABLE IF NOT EXISTS food_plan (
id integer PRIMARY KEY, id integer PRIMARY KEY,
date text UNIQUE, date text,
food1 integer, food1 integer,
food2 integer, food2 integer,
dessert1 integer, dessert1 integer,
dessert2 integer, dessert2 integer,
issent integer DEFAULT '0',
FOREIGN KEY(food1) REFERENCES food(id), FOREIGN KEY(food1) REFERENCES food(id),
FOREIGN KEY(food2) REFERENCES food(id), FOREIGN KEY(food2) REFERENCES food(id),
FOREIGN KEY(dessert1) REFERENCES food(id), FOREIGN KEY(dessert1) REFERENCES food(id),
FOREIGN KEY(dessert2) REFERENCES food(id) FOREIGN KEY(dessert2) REFERENCES food(id)
);"""; );""";
sql[12] = """ sql[12] = """
CREATE TABLE IF NOT EXISTS food_restriction ( CREATE TABLE IF NOT EXISTS food_restrictions (
id integer PRIMARY KEY, id integer PRIMARY KEY,
foodid integer, foodid integer,
allergyid integer, allergyid integer,
@ -138,10 +137,9 @@ public class Database {
id integer PRIMARY KEY, id integer PRIMARY KEY,
childid integer, childid integer,
food_planid integer, food_planid integer,
foodid integer, selection integer,
FOREIGN KEY(childid) REFERENCES child(id), FOREIGN KEY(childid) REFERENCES child(id),
FOREIGN KEY(food_planid) REFERENCES food_plan(id), FOREIGN KEY(food_planid) REFERENCES food_plan(id)
FOREIGN KEY(foodid) REFERENCES food(id)
);"""; );""";
try(Connection conn = connect(); Statement stmt = conn.createStatement()){ try(Connection conn = connect(); Statement stmt = conn.createStatement()){
for(int i = 0; i < sql.length; i++){ for(int i = 0; i < sql.length; i++){
@ -152,7 +150,7 @@ public class Database {
} }
} }
protected static void fillDb(){ protected static void fillSampleDb(){
List<String> sqls = new ArrayList<>(); List<String> sqls = new ArrayList<>();
sqls.add(""" sqls.add("""
INSERT OR IGNORE INTO food_type (id,name) INSERT OR IGNORE INTO food_type (id,name)
@ -229,15 +227,6 @@ public class Database {
sqls.add(""" sqls.add("""
INSERT OR IGNORE INTO allergy (id,name) INSERT OR IGNORE INTO allergy (id,name)
VALUES('22','Konservierungsstoff');"""); VALUES('22','Konservierungsstoff');""");
sqls.add("""
INSERT OR IGNORE INTO severity (id,name)
VALUES('1','Harmlos');""");
sqls.add("""
INSERT OR IGNORE INTO severity (id,name)
VALUES('2','Warnung');""");
sqls.add("""
INSERT OR IGNORE INTO severity (id,name)
VALUES('3','Kritisch');""");
try(Connection conn = connect(); Statement stmt = conn.createStatement()){ try(Connection conn = connect(); Statement stmt = conn.createStatement()){
for (String sql : sqls) { for (String sql : sqls) {
stmt.execute(sql); stmt.execute(sql);
@ -247,65 +236,16 @@ public class Database {
} }
} }
/** protected static boolean insert(String table, String header, String values){
* inserts data into table and returns its id try (Connection conn = connect(); Statement stmt = conn.createStatement()){
* @param table name of the database table String sql = "INSERT OR IGNORE INTO " + table + " (" + header + ") VALUES(" + values + ");";
* @param header String[] order should match with values stmt.execute(sql);
* @param values String[] order should match with header
* @return id of dataset or -1
*/
protected static long insert(String table, String[] header, String[] values){
long id = -1;
try (Connection conn = connect()){
String query = queryBuilder("exists",table,header,values);
PreparedStatement psQuery = conn.prepareStatement(query);
ResultSet rsQuery = psQuery.executeQuery();
if(rsQuery.next()){
boolean found = rsQuery.getBoolean(1);
if(!found){
String sql = queryBuilder("insert",table,header,values);
String[] rowId = {"id"};
PreparedStatement ps = conn.prepareStatement(sql,rowId);
ps.execute();
ResultSet rs = ps.getGeneratedKeys();
if(rs.next()){
id = rs.getLong(1);
}
}else{
query = queryBuilder("selectMatch",table,header,values);
psQuery = conn.prepareStatement(query);
rsQuery = psQuery.executeQuery();
if(rsQuery.next()) {
id = rsQuery.getLong(1);
}
}
}
} catch (SQLException e) { } catch (SQLException e) {
return id; return false;
} }
return id; return true;
} }
protected static long getSingleId(String table, String[] header, String[] values){
long id = -1;
try(Connection conn = connect()){
String sql = queryBuilder("selectMatch",table,header,values);
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next()){
id = rs.getLong(1);
if(rs.next()){
id = -1;
}
}
}catch (SQLException e){
e.printStackTrace();
return id;
}
return id;
}
protected static void printSampleQuery(){ protected static void printSampleQuery(){
String sql = """ String sql = """
@ -313,17 +253,17 @@ public class Database {
String sql1 = """ String sql1 = """
SELECT * FROM allergy WHERE id > ?;"""; SELECT * FROM allergy WHERE id > ?;""";
try(Connection conn = connect()){ try(Connection conn = connect()){
PreparedStatement ps = conn.prepareStatement(sql); PreparedStatement pstmt = conn.prepareStatement(sql);
PreparedStatement ps1 = conn.prepareStatement(sql1); PreparedStatement pstmt1 = conn.prepareStatement(sql1);
ps.setInt(1,0); pstmt.setInt(1,0);
ResultSet rs = ps.executeQuery(); ResultSet rs = pstmt.executeQuery();
System.out.println("food_type"); System.out.println("food_type");
while (rs.next()){ while (rs.next()){
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
} }
System.out.println("allergy"); System.out.println("allergy");
ps1.setInt(1,0); pstmt1.setInt(1,0);
rs = ps1.executeQuery(); rs = pstmt1.executeQuery();
while (rs.next()){ while (rs.next()){
System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name")); System.out.println("ID: " + rs.getInt("id") + ", Name: " + rs.getString("name"));
} }
@ -332,201 +272,35 @@ public class Database {
} }
} }
protected static void delete(String table, long id){ protected static void deleteSample(){
String sql = "DELETE FROM " + table + " WHERE id = ?;"; String sql = """
try(Connection conn = connect();PreparedStatement ps = conn.prepareStatement(sql)){ DELETE FROM user WHERE id = ?;""";
ps.setLong(1,id); try(Connection conn = connect();PreparedStatement pstmt = conn.prepareStatement(sql)){
ps.executeUpdate(); pstmt.setInt(1,1);
pstmt.executeUpdate();
}catch (SQLException e){ }catch (SQLException e){
e.printStackTrace(); e.printStackTrace();
} }
} }
private static String queryBuilder(String type,String table, String[] header, String[] values){ /* String sql = """
String sql; CREATE TABLE IF NOT EXISTS user (
StringBuilder sb = new StringBuilder(); id integer PRIMARY KEY,
switch (type) { name text);""";
case "exists" -> { String sql2 = "SELECT * FROM user WHERE id > ?";
sb = new StringBuilder("SELECT (count(*) > 0) as found FROM "); String sql3 = "INSERT INTO user (id,name) VALUES (1,'test1')";
sb.append(table); try(Connection conn = connect();
sb.append(" WHERE "); Statement stmt = conn.createStatement()){
sb.append(header[0]); stmt.execute(sql);
sb.append(" LIKE '"); stmt.execute(sql3);
sb.append(values[0]); PreparedStatement pstmt = conn.prepareStatement(sql2);
sb.append("'"); pstmt.setInt(1,0);
for (int i = 1; i < header.length; i++) { ResultSet rs = pstmt.executeQuery();
sb.append(" AND ");
sb.append(header[i]);
sb.append(" LIKE '");
sb.append(values[i]);
sb.append("'");
}
}
case "selectMatch" -> {
sb = new StringBuilder("SELECT * FROM ");
sb.append(table);
sb.append(" WHERE ");
sb.append(header[0]);
sb.append(" LIKE '");
sb.append(values[0]);
sb.append("'");
for (int i = 1; i < header.length; i++) {
sb.append(" AND ");
sb.append(header[i]);
sb.append(" LIKE '");
sb.append(values[i]);
sb.append("'");
}
}
case "insert" -> {
sb = new StringBuilder("INSERT OR IGNORE INTO ");
sb.append(table);
sb.append(" (");
sb.append(header[0]);
for (int i = 1; i < header.length; i++) {
sb.append(",");
sb.append(header[i]);
}
sb.append(") VALUES('");
sb.append(values[0]);
sb.append("'");
for (int i = 1; i < values.length; i++) {
sb.append(",'");
sb.append(values[i]);
sb.append("'");
}
sb.append(");");
}
case "count" -> {
sb = new StringBuilder("SELECT COUNT(*) FROM ");
sb.append(table);
sb.append(" WHERE ");
sb.append(header[0]);
sb.append(" = ");
sb.append(values[0]);
for(int i = 1; i < header.length; i++){
sb.append(" AND ");
sb.append(header[i]);
sb.append(" = ");
sb.append(values[i]);
}
}
case "update" -> {
sb = new StringBuilder("UPDATE ");
sb.append(table);
sb.append(" SET ");
sb.append(header[1]);
sb.append(" = ");
sb.append(values[1]);
for(int i = 2; i < header.length; i++){
sb.append(", ");
sb.append(header[i]);
sb.append(" = ");
sb.append(values[i]);
}
sb.append(" WHERE ");
sb.append(header[0]);
sb.append(" = ");
sb.append(values[0]);
}
}
sql = sb.toString();
return sql;
}
protected static List<String> getTable(String table){
List<String> data = new ArrayList<>();
StringBuilder sb;
try(Connection conn = connect()) {
String sql = "SELECT * FROM " + table;
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
while (rs.next()){ while (rs.next()){
sb = new StringBuilder(); System.out.println(rs.getInt("id"));
sb.append(rs.getString(1));
for(int i = 2; i <= count; i++){
sb.append(":");
sb.append(rs.getString(i));
}
data.add(sb.toString());
}
}catch (SQLException e){
return new ArrayList<>();
}
return data;
}
protected static List<String> select(String table,String[] header, String[] values){
List<String> data = new ArrayList<>();
StringBuilder sb;
String sql = queryBuilder("selectMatch",table,header,values);
try(Connection conn = connect()) {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
while (rs.next()){
sb = new StringBuilder();
sb.append(rs.getString(1));
for(int i = 2; i <= count; i++){
sb.append(":");
sb.append(rs.getString(i));
}
data.add(sb.toString());
} }
}catch (SQLException e){ }catch (SQLException e){
e.printStackTrace(); e.printStackTrace();
return data; return;
} } */
return data;
}
protected static List<String> getEntryById(String table, long id){
List<String> data = new ArrayList<>();
StringBuilder sb;
String sql = "SELECT * FROM " + table + " WHERE id = ?;";
try (Connection conn = connect()) {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setLong(1,id);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
while (rs.next()){
sb = new StringBuilder();
sb.append(rs.getString(1));
for(int i = 2; i <= count; i++){
sb.append(":");
sb.append(rs.getString(i));
}
data.add(sb.toString());
}
} catch (SQLException e) {
e.printStackTrace();
return data;
}
return data;
}
protected static int count(String table,String[] header,String[] values){
String sql = queryBuilder("count",table,header,values);
try(Connection conn = connect()) {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
return rs.getInt(1);
}catch (SQLException e){
return -1;
}
}
protected static int update(String table,String[] header,String[] values){
try(Connection conn = connect()) {
String sql = queryBuilder("update",table,header,values);
PreparedStatement ps = conn.prepareStatement(sql);
return ps.executeUpdate();
}catch (SQLException e){
return -1;
}
}
} }

View File

@ -1,82 +0,0 @@
package com.bib.essensbestellungsverwaltung;
/*
@author Malte Schulze Hobeling
*/
import java.util.ArrayList;
import java.util.List;
public class FoodMgr {
public static long createFood(String[] foodData, String[] allergyData){
String[] foodH = {"name","description","isDessert","food_typeid"};
String[] food_restrictionH = {"foodid","allergyid"};
long id = Database.insert("food",foodH,foodData);
if(allergyData.length > 0){
String sId = String.valueOf(id);
for (String allergyId : allergyData) {
String[] food_restrictionD = {sId,allergyId};
Database.insert("food_restriction",food_restrictionH, food_restrictionD);
}
}
return id;
}
public static long createFood_plan(String[] food_planData){
String[] food_planH = {"date","food1","food2","dessert1","dessert2"};
return Database.insert("food_plan",food_planH,food_planData);
}
public static List<String> getFood(boolean isDessert){
String[] foodH = {"isDessert"};
String[] foodD = {(isDessert ? "1" : "0")};
return Database.select("food",foodH,foodD);
}
public static List<String> getVeganFood(boolean isDessert){
String[] foodH = {"isDessert","food_typeid"};
String[] foodD = {(isDessert ? "1" : "0"),"1"};
return Database.select("food",foodH,foodD);
}
public static List<String> getFood_plan(String date){
String[] food_planH = {"date"};
String[] food_planD = {date};
return Database.select("food_plan",food_planH,food_planD);
}
public static List<String> getFoodById(long id){
return Database.getEntryById("food",id);
}
public static long createFood_selection(String[] food_selectionData){
String[] food_selectionH = {"childid","food_planid","foodid"};
List<String> food_plan = Database.getEntryById("food_plan",Long.parseLong(food_selectionData[1]));
String[] food_planParts = food_plan.get(0).split(":");
if(Long.parseLong(food_planParts[6]) == 0){
return Database.insert("food_selection",food_selectionH,food_selectionData);
}else {
return -1;
}
}
public static List<String> getDayOrder(String date){
List<String> orders = new ArrayList<>();
List<String> food_plan = getFood_plan(date);
String[] food_planParts = food_plan.get(0).split(":");
for(int i = 2; i < 2+4; i++){
List<String> food = getFoodById(Long.parseLong(food_planParts[i]));
String[] foodParts = food.get(0).split(":");
String foodName = foodParts[1];
String[] food_selectionH = {"food_planid","foodid"};
String[] food_selectionD = {food_planParts[0],foodParts[0]};
int count = Database.count("food_selection",food_selectionH,food_selectionD);
orders.add(foodName+":"+count);
}
String[] updateH = {"id","issent"};
String[] updateD = {food_planParts[0],"1"};
if(Database.update("food_plan",updateH,updateD) < 0){
System.out.println("Fehler");
}
return orders;
}
}

View File

@ -25,7 +25,7 @@ public class HelloApplication extends Application {
public static void main(String[] args) { public static void main(String[] args) {
Database.init(); Database.init();
Database.createDb(); Database.createDb();
Database.fillDb(); Database.fillSampleDb();
Database.printSampleQuery(); Database.printSampleQuery();
//Database.deleteSample(); //Database.deleteSample();
launch(); launch();

View File

@ -2,10 +2,6 @@ package com.bib.essensbestellungsverwaltung;
public class SuperMain { public class SuperMain {
public static void main(String[] args) { public static void main(String[] args) {
if(args.length > 0){ HelloApplication.main(args);
ConsoleMain.main(args);
}else {
HelloApplication.main(args);
}
} }
} }