From c9e3414b29c2cbf3ec410cc6109ed54d174a437d Mon Sep 17 00:00:00 2001 From: lukas-heiligenbrunner Date: Sun, 1 Dec 2019 10:58:43 +0100 Subject: [PATCH] * JDBC class is singleton and login to db only on startup * db error alert on login --- .idea/misc.xml | 2 +- resources/wwwroot/index.html | 2 + resources/wwwroot/js/dashboard.js | 68 +++++++++++-------- resources/wwwroot/js/index.js | 10 +++ src/com/wasteinformationserver/db/JDCB.java | 41 +++++++++-- .../db/MySQLConnector.java | 9 +-- src/com/wasteinformationserver/main.java | 18 ++++- src/com/wasteinformationserver/mqtt/mqtt.java | 9 ++- .../website/MainPage.java | 4 +- .../website/Webserver.java | 2 +- .../website/datarequests/DataRequest.java | 30 +++++--- .../website/datarequests/RegisterRequest.java | 9 ++- .../datarequests/login/LoginRequest.java | 12 +++- .../datarequests/login/LoginState.java | 2 +- 14 files changed, 163 insertions(+), 55 deletions(-) diff --git a/.idea/misc.xml b/.idea/misc.xml index 8b90687..9c9de6e 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,6 +1,6 @@ - + \ No newline at end of file diff --git a/resources/wwwroot/index.html b/resources/wwwroot/index.html index 78ed2ba..969a759 100644 --- a/resources/wwwroot/index.html +++ b/resources/wwwroot/index.html @@ -24,6 +24,8 @@ + +
diff --git a/resources/wwwroot/js/dashboard.js b/resources/wwwroot/js/dashboard.js index 039d445..47c7a48 100644 --- a/resources/wwwroot/js/dashboard.js +++ b/resources/wwwroot/js/dashboard.js @@ -14,35 +14,49 @@ $(document).ready(function () { function reloadtable() { $.post('/senddata/wastedata', 'action=getAllCities', function (data) { console.log(data); - $('#location-table-data').html(""); - for (var i = 0; i < data.data.length; i++) { - $('#location-table-data').append("" + - "" + data.data[i].cityname + "" + - "" + data.data[i].zone + "" + - "" + data.data[i].wastetype + "" + - "" + "" + "" + - ""); - $(".delbtn").click(function (event) { - var id = event.target.getAttribute("dataid"); - console.log("clicked btn data " + id); - $.post('/senddata/wastedata', 'action=deletecity&id=' + id, function (data) { - console.log(data); - reloadtable(); + if (data.query == "ok") { + $('#location-table-data').html(""); + for (var i = 0; i < data.data.length; i++) { + $('#location-table-data').append("" + + "" + data.data[i].cityname + "" + + "" + data.data[i].zone + "" + + "" + data.data[i].wastetype + "" + + "" + "" + "" + + ""); + $(".delbtn").click(function (event) { + var id = event.target.getAttribute("dataid"); + console.log("clicked btn data " + id); + $.post('/senddata/wastedata', 'action=deletecity&id=' + id, function (data) { + console.log(data); + reloadtable(); + }); }); - }); - } - //todo entweda 1 od 2 - // $("#example2").reload(); - table = $("#example2").DataTable(); + } + //todo entweda 1 od 2 + // $("#example2").reload(); + table = $("#example2").DataTable(); + + // $('#example1').DataTable({ + // "paging": true, + // "lengthChange": false, + // "searching": false, + // "ordering": true, + // "info": true, + // "autoWidth": false, + // }); + } else if (data.query == "nodbconn") { + Swal.fire({ + type: "error", + title: 'No connection to Database', + html: 'Setup DB here --> click.', + }).then((result) => { + console.log('Popup closed. ') + + }); + } else { + console.log("Error: " + data.query); + } - // $('#example1').DataTable({ - // "paging": true, - // "lengthChange": false, - // "searching": false, - // "ordering": true, - // "info": true, - // "autoWidth": false, - // }); }, 'json'); } diff --git a/resources/wwwroot/js/index.js b/resources/wwwroot/js/index.js index 172423e..6cd1a42 100644 --- a/resources/wwwroot/js/index.js +++ b/resources/wwwroot/js/index.js @@ -8,6 +8,16 @@ $(document).ready(function () { $.post('/senddata/loginget', 'username=' + username + '&password=' + password, function (data) { console.log(data); + if (data.status == "nodbconn"){ + Swal.fire({ + type: "error", + title: 'No connection to Database', + html: 'Setup DB here --> click.', + }).then((result) => { + console.log('Popup closed. ') + + }); + } if (data.accept == true) { console.log("successfully logged in!"); document.cookie = "username=" + username; diff --git a/src/com/wasteinformationserver/db/JDCB.java b/src/com/wasteinformationserver/db/JDCB.java index 2d7766d..25ecd82 100644 --- a/src/com/wasteinformationserver/db/JDCB.java +++ b/src/com/wasteinformationserver/db/JDCB.java @@ -2,26 +2,59 @@ package com.wasteinformationserver.db; import com.wasteinformationserver.basicutils.Log; +import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JDCB { - Connection conn; + static Connection conn; - public JDCB(String username, String password, String dbname) { + static JDCB jdcb; + static boolean loggedin = false; + + static String usernamec; + static String passwordc; + static String dbnamec; + static String ipc; + static int portc; + + public static void init(String username, String password, String dbname, String ip, int port) throws IOException { + usernamec = username; + passwordc = password; + dbnamec = dbname; + jdcb = new JDCB(username,password,dbname,ip,port); + } + + private JDCB(String username, String password, String dbname, String ip, int port) throws IOException { + logintodb(username,password,dbname,ip, port); + } + + public static JDCB getInstance() throws IOException { + if (loggedin){ + return jdcb; + }else { + logintodb(usernamec,passwordc,dbnamec,ipc,portc); + return jdcb; + } + + } + + public static void logintodb(String username, String password, String dbname, String ip, int port) throws IOException { Database db = new MySQLConnector( username, password, - "192.168.65.15", - 3306, + ip, + port, dbname); try { conn = db.getConnection(); + loggedin = true; } catch (SQLException e) { Log.error("no connection to Database!"); + throw new IOException("No connection to database"); } } diff --git a/src/com/wasteinformationserver/db/MySQLConnector.java b/src/com/wasteinformationserver/db/MySQLConnector.java index cc68023..8a84cbb 100755 --- a/src/com/wasteinformationserver/db/MySQLConnector.java +++ b/src/com/wasteinformationserver/db/MySQLConnector.java @@ -19,10 +19,11 @@ public class MySQLConnector extends Database { } public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - "jdbc:mysql://" + host + ":" + port + "/" + dbName + "?useSSL=false", - user, - password); + DriverManager.setLoginTimeout(1); // TODO: 30.11.19 set higher maybe + return DriverManager.getConnection( + "jdbc:mysql://" + host + ":" + port + "/" + dbName + "?useSSL=false", + user, + password); } } diff --git a/src/com/wasteinformationserver/main.java b/src/com/wasteinformationserver/main.java index b6b3a94..342361c 100644 --- a/src/com/wasteinformationserver/main.java +++ b/src/com/wasteinformationserver/main.java @@ -1,9 +1,12 @@ package com.wasteinformationserver; import com.wasteinformationserver.basicutils.Log; +import com.wasteinformationserver.db.JDCB; import com.wasteinformationserver.mqtt.*; import com.wasteinformationserver.website.Webserver; +import java.io.IOException; + public class main { public static void main(String[] args) { @@ -20,11 +23,24 @@ public class main { } })); + //initial connect to db + Log.message("initial login to db"); + new Thread(() -> { + try { + JDCB.init("users", "kOpaIJUjkgb9ur6S", "wasteinformation","192.168.65.15",3306); + } catch (IOException e) { + //e.printStackTrace(); + Log.error("no connection to db"); + } + }).start(); + + //startup web server Thread mythread = new Thread(() -> new Webserver().startserver()); mythread.start(); - Log.message("thread started"); + //startup mqtt service + Log.message("starting mqtt service"); try{ mqtt m = new mqtt(); m.notifymessage(); diff --git a/src/com/wasteinformationserver/mqtt/mqtt.java b/src/com/wasteinformationserver/mqtt/mqtt.java index d335100..8253fe2 100644 --- a/src/com/wasteinformationserver/mqtt/mqtt.java +++ b/src/com/wasteinformationserver/mqtt/mqtt.java @@ -8,6 +8,7 @@ import org.eclipse.paho.client.mqttv3.MqttException; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; +import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; @@ -51,7 +52,13 @@ public class mqtt { public void getDatabasedata(String message, String wastetyp, int clientidentify) { Log.debug(message); - JDCB Database = new JDCB("placeuser", "eaL956R6yFItQVBl", "wasteinformation"); + JDCB Database = null; + try { + Database = JDCB.getInstance(); + } catch (IOException e) { + //e.printStackTrace(); + } + //new JDCB("placeuser", "eaL956R6yFItQVBl", "wasteinformation"); ResultSet result = Database.executeQuery(message); try { if (!result.isBeforeFirst()) { diff --git a/src/com/wasteinformationserver/website/MainPage.java b/src/com/wasteinformationserver/website/MainPage.java index b21bf11..832e39b 100644 --- a/src/com/wasteinformationserver/website/MainPage.java +++ b/src/com/wasteinformationserver/website/MainPage.java @@ -30,10 +30,10 @@ public class MainPage implements HttpHandler { path += "index.html"; } - Log.message("looking for: " + path); + Log.debug("looking for: " + path); if (path.contains(".html")){ - if (LoginState.getObject().isLoggedIn()){ + if (LoginState.getObject().isLoggedIn() || path.equals("/register.html")){ //pass only register page sendPage(path, t); }else { Log.warning("user not logged in --> redirecting to login page"); diff --git a/src/com/wasteinformationserver/website/Webserver.java b/src/com/wasteinformationserver/website/Webserver.java index 60282c6..c67c1dd 100644 --- a/src/com/wasteinformationserver/website/Webserver.java +++ b/src/com/wasteinformationserver/website/Webserver.java @@ -13,7 +13,7 @@ import java.net.InetSocketAddress; public class Webserver { public void startserver() { - Log.info("starting server"); + Log.info("starting Webserver"); HttpServer server = null; try { server = HttpServer.create(new InetSocketAddress(8000), 0); diff --git a/src/com/wasteinformationserver/website/datarequests/DataRequest.java b/src/com/wasteinformationserver/website/datarequests/DataRequest.java index b2603b8..ebff8b8 100644 --- a/src/com/wasteinformationserver/website/datarequests/DataRequest.java +++ b/src/com/wasteinformationserver/website/datarequests/DataRequest.java @@ -5,6 +5,7 @@ import com.wasteinformationserver.basicutils.Log; import com.wasteinformationserver.db.JDCB; import com.wasteinformationserver.website.basicrequest.PostRequest; +import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; @@ -13,14 +14,21 @@ public class DataRequest extends PostRequest { @Override public String request(HashMap params) { String result = ""; + JDCB jdcb; + try { + jdcb = JDCB.getInstance(); + } catch (IOException e) { + Log.error("no connection to db"); + return "{\"query\" : \"nodbconn\"}"; + } switch (params.get("action")) { case "newCity": + StringBuilder sb = new StringBuilder(); + sb.append("{"); Log.debug(params.toString()); // check if wastezone and wasteregion already exists - JDCB jdcb = new JDCB("users", "kOpaIJUjkgb9ur6S", "wasteinformation"); - Log.debug(params.get("cityname") + params.get("wastetype") + params.get("wastezone")); ResultSet set = jdcb.executeQuery("select * from `cities` where `name`='" + params.get("cityname") + "' AND `wastetype`='" + params.get("wastetype") + "' AND `zone`='" + params.get("wastezone") + "'"); int size = 0; @@ -38,31 +46,33 @@ public class DataRequest extends PostRequest { int status = jdcb.executeUpdate("INSERT INTO `cities`(`userid`, `name`, `wastetype`, `zone`) VALUES ('0','" + params.get("cityname") + "','" + params.get("wastetype") + "','" + params.get("wastezone") + "');"); System.out.println(status); if (status == 1) { - result = "{\"status\" : \"inserted\"}"; + sb.append("\"status\" : \"inserted\"}"); } else { - result = "{\"status\" : \"inserterror\"}"; + sb.append("\"status\" : \"inserterror\""); } } else if (size > 1) { Log.warning("more than one entry in db!!!"); - result = "{\"status\" : \"exists\"}"; + result = "\"status\" : \"exists\""; } else { //already exists System.out.println("already exists"); - result = "{\"status\" : \"exists\"}"; + result = "\"status\" : \"exists\""; } + sb.append(",\"query\":\"ok\""); + sb.append("}"); + Log.debug(result); break; case "getAllCities": // TODO: 15.11.19 database call to get all data and store it as json. - JDCB jdcbc = new JDCB("users", "kOpaIJUjkgb9ur6S", "wasteinformation"); Gson gson = new Gson(); StringBuilder builder = new StringBuilder(); - ResultSet sett = jdcbc.executeQuery("select * from cities"); + ResultSet sett = jdcb.executeQuery("select * from cities"); Log.debug(sett.toString()); builder.append("{\"data\":["); try { @@ -87,10 +97,8 @@ public class DataRequest extends PostRequest { case "deletecity": //DELETE FROM `cities` WHERE `id`=0 - JDCB jdcbcc = new JDCB("users", "kOpaIJUjkgb9ur6S", "wasteinformation"); - Log.debug(params.get("id")); - int status= jdcbcc.executeUpdate("DELETE FROM `cities` WHERE `id`='" + params.get("id")+"'"); + int status= jdcb.executeUpdate("DELETE FROM `cities` WHERE `id`='" + params.get("id")+"'"); Log.debug(status); break; diff --git a/src/com/wasteinformationserver/website/datarequests/RegisterRequest.java b/src/com/wasteinformationserver/website/datarequests/RegisterRequest.java index 51aec93..3ca4090 100644 --- a/src/com/wasteinformationserver/website/datarequests/RegisterRequest.java +++ b/src/com/wasteinformationserver/website/datarequests/RegisterRequest.java @@ -5,6 +5,7 @@ import com.wasteinformationserver.db.JDCB; import com.wasteinformationserver.website.HttpTools; import com.wasteinformationserver.website.basicrequest.PostRequest; +import java.io.IOException; import java.util.HashMap; public class RegisterRequest extends PostRequest { @@ -14,7 +15,13 @@ public class RegisterRequest extends PostRequest { String passhash = HttpTools.StringToMD5(params.get("password")); - JDCB myjd = new JDCB("users", "kOpaIJUjkgb9ur6S", "wasteinformation"); + JDCB myjd = null; + try { + myjd = JDCB.getInstance(); + } catch (IOException e) { + e.printStackTrace(); + } + //new JDCB("users", "kOpaIJUjkgb9ur6S", "wasteinformation"); int s = myjd.executeUpdate("INSERT INTO `user` (`username`, `firstName`, `secondName`, `password`, `email`, `logindate`) VALUES ('"+params.get("username")+"', '"+params.get("firstname")+"', '"+params.get("lastname")+"', '"+passhash+"', '"+params.get("email")+"', current_timestamp());"); // TODO: 27.09.19 detect if register process was successful and reply right json diff --git a/src/com/wasteinformationserver/website/datarequests/login/LoginRequest.java b/src/com/wasteinformationserver/website/datarequests/login/LoginRequest.java index 696de57..5709322 100644 --- a/src/com/wasteinformationserver/website/datarequests/login/LoginRequest.java +++ b/src/com/wasteinformationserver/website/datarequests/login/LoginRequest.java @@ -5,6 +5,7 @@ import com.wasteinformationserver.db.JDCB; import com.wasteinformationserver.website.HttpTools; import com.wasteinformationserver.website.basicrequest.PostRequest; +import java.io.IOException; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; @@ -18,7 +19,16 @@ public class LoginRequest extends PostRequest { String password = params.get("password"); String username = params.get("username"); - ResultSet s = new JDCB("users", "kOpaIJUjkgb9ur6S", "wasteinformation").executeQuery("select * from user where username ='" + username + "'"); + JDCB jdcb; + try { + jdcb = JDCB.getInstance(); + } catch (IOException e) { + Log.error("no connection to db"); + return "{\"status\" : \"nodbconn\"}"; + } + + ResultSet s = jdcb.executeQuery("select * from user where username ='" + username + "'");; + //new JDCB("users", "kOpaIJUjkgb9ur6S", "wasteinformation").executeQuery("select * from user where username ='" + username + "'"); Log.debug("successfully logged in to db"); String response = "{\"accept\": false}"; try { diff --git a/src/com/wasteinformationserver/website/datarequests/login/LoginState.java b/src/com/wasteinformationserver/website/datarequests/login/LoginState.java index 2e7b4da..34ae214 100644 --- a/src/com/wasteinformationserver/website/datarequests/login/LoginState.java +++ b/src/com/wasteinformationserver/website/datarequests/login/LoginState.java @@ -14,7 +14,7 @@ public class LoginState { String lastname; String email; - boolean loggedin = false; + boolean loggedin = true; //todo set back!!! public void logIn(){ loggedin=true;