From c17d02d1f8fef32009cdd62949499018dd9d9437 Mon Sep 17 00:00:00 2001 From: flifloo Date: Fri, 18 Dec 2020 11:42:54 +0100 Subject: [PATCH] Add DB config file support --- .gitignore | 5 +++++ build.gradle | 1 + src/main/java/DB/DB.java | 38 +++++++++++++++++++++++++++++++++----- 3 files changed, 39 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index e60a4f1..e5a62e4 100644 --- a/.gitignore +++ b/.gitignore @@ -34,3 +34,8 @@ out/ ############################## .floo .flooignore + +############################## +## Configuration +############################## +config.json diff --git a/build.gradle b/build.gradle index 754317b..ea14aec 100644 --- a/build.gradle +++ b/build.gradle @@ -12,6 +12,7 @@ repositories { dependencies { implementation 'org.projectlombok:lombok:1.18.16' implementation 'org.mariadb.jdbc:mariadb-java-client:2.7.1' + implementation 'com.googlecode.json-simple:json-simple:1.1.1' testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0' testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' } diff --git a/src/main/java/DB/DB.java b/src/main/java/DB/DB.java index 4b5527f..92277b8 100644 --- a/src/main/java/DB/DB.java +++ b/src/main/java/DB/DB.java @@ -3,20 +3,48 @@ package DB; import Exceptions.NotFoundInTable; import lombok.Data; import lombok.Getter; +import org.json.simple.JSONObject; +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; +import java.io.*; +import java.lang.reflect.InvocationTargetException; import java.sql.*; +import java.util.*; public class DB { - static final private String host = ""; - static final private String database = ""; - static final private String user = ""; - static final private String password = ""; @Getter static private Connection connection; + static private JSONObject getAuth() { + try { + File f = new File("./config.json"); + if (!f.exists()) { + FileWriter fw = new FileWriter(f); + fw.write( + new JSONObject( + Map.ofEntries( + Map.entry("host", ""), + Map.entry("database", ""), + Map.entry("user", ""), + Map.entry("password", "") + ) + ).toJSONString() + ); + fw.close(); + } + return (JSONObject) new JSONParser().parse(new FileReader(f)); + } catch (ParseException | IOException e) { + e.printStackTrace(); + return null; + } + } + static public boolean connect() { try { if (connection == null || connection.isClosed()) { - connection = DriverManager.getConnection("jdbc:mariadb://"+host+"/"+database+"?user="+user+"&password="+password); + JSONObject auth = getAuth(); + if (auth != null) + connection = DriverManager.getConnection("jdbc:mariadb://"+auth.get("host")+"/"+auth.get("database")+"?user="+auth.get("user")+"&password="+auth.get("password")); return true; } } catch (SQLException e) {