* JDBC class is singleton and login to db only on startup

* db error alert on login
This commit is contained in:
lukas-heiligenbrunner 2019-12-01 10:58:43 +01:00
parent 07a4035195
commit c9e3414b29
14 changed files with 163 additions and 55 deletions

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="false" project-jdk-name="13" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_13_PREVIEW" default="false" project-jdk-name="13" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" /> <output url="file://$PROJECT_DIR$/out" />
</component> </component>
</project> </project>

View File

@ -24,6 +24,8 @@
<link rel="stylesheet" type="text/css" href="css/index.css"> <link rel="stylesheet" type="text/css" href="css/index.css">
<script type="text/javascript" src="js/index.js"></script> <script type="text/javascript" src="js/index.js"></script>
<script src="lib/AdminLTE/plugins/sweetalert2/sweetalert2.all.js"></script>
</head> </head>
<body> <body>
<div class="container"> <div class="container">

View File

@ -14,6 +14,7 @@ $(document).ready(function () {
function reloadtable() { function reloadtable() {
$.post('/senddata/wastedata', 'action=getAllCities', function (data) { $.post('/senddata/wastedata', 'action=getAllCities', function (data) {
console.log(data); console.log(data);
if (data.query == "ok") {
$('#location-table-data').html(""); $('#location-table-data').html("");
for (var i = 0; i < data.data.length; i++) { for (var i = 0; i < data.data.length; i++) {
$('#location-table-data').append("<tr>" + $('#location-table-data').append("<tr>" +
@ -43,6 +44,19 @@ $(document).ready(function () {
// "info": true, // "info": true,
// "autoWidth": false, // "autoWidth": false,
// }); // });
} else if (data.query == "nodbconn") {
Swal.fire({
type: "error",
title: 'No connection to Database',
html: 'Setup DB here --> <a href="index.html">click<a/>.',
}).then((result) => {
console.log('Popup closed. ')
});
} else {
console.log("Error: " + data.query);
}
}, 'json'); }, 'json');
} }

View File

@ -8,6 +8,16 @@ $(document).ready(function () {
$.post('/senddata/loginget', 'username=' + username + '&password=' + password, function (data) { $.post('/senddata/loginget', 'username=' + username + '&password=' + password, function (data) {
console.log(data); console.log(data);
if (data.status == "nodbconn"){
Swal.fire({
type: "error",
title: 'No connection to Database',
html: 'Setup DB here --> <a href="index.html">click<a/>.',
}).then((result) => {
console.log('Popup closed. ')
});
}
if (data.accept == true) { if (data.accept == true) {
console.log("successfully logged in!"); console.log("successfully logged in!");
document.cookie = "username=" + username; document.cookie = "username=" + username;

View File

@ -2,26 +2,59 @@ package com.wasteinformationserver.db;
import com.wasteinformationserver.basicutils.Log; import com.wasteinformationserver.basicutils.Log;
import java.io.IOException;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
public class JDCB { 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( Database db = new MySQLConnector(
username, username,
password, password,
"192.168.65.15", ip,
3306, port,
dbname); dbname);
try { try {
conn = db.getConnection(); conn = db.getConnection();
loggedin = true;
} catch (SQLException e) { } catch (SQLException e) {
Log.error("no connection to Database!"); Log.error("no connection to Database!");
throw new IOException("No connection to database");
} }
} }

View File

@ -19,6 +19,7 @@ public class MySQLConnector extends Database {
} }
public Connection getConnection() throws SQLException { public Connection getConnection() throws SQLException {
DriverManager.setLoginTimeout(1); // TODO: 30.11.19 set higher maybe
return DriverManager.getConnection( return DriverManager.getConnection(
"jdbc:mysql://" + host + ":" + port + "/" + dbName + "?useSSL=false", "jdbc:mysql://" + host + ":" + port + "/" + dbName + "?useSSL=false",
user, user,

View File

@ -1,9 +1,12 @@
package com.wasteinformationserver; package com.wasteinformationserver;
import com.wasteinformationserver.basicutils.Log; import com.wasteinformationserver.basicutils.Log;
import com.wasteinformationserver.db.JDCB;
import com.wasteinformationserver.mqtt.*; import com.wasteinformationserver.mqtt.*;
import com.wasteinformationserver.website.Webserver; import com.wasteinformationserver.website.Webserver;
import java.io.IOException;
public class main { public class main {
public static void main(String[] args) { 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()); Thread mythread = new Thread(() -> new Webserver().startserver());
mythread.start(); mythread.start();
Log.message("thread started");
//startup mqtt service
Log.message("starting mqtt service");
try{ try{
mqtt m = new mqtt(); mqtt m = new mqtt();
m.notifymessage(); m.notifymessage();

View File

@ -8,6 +8,7 @@ import org.eclipse.paho.client.mqttv3.MqttException;
import java.awt.event.ActionEvent; import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.text.DateFormat; import java.text.DateFormat;
@ -51,7 +52,13 @@ public class mqtt {
public void getDatabasedata(String message, String wastetyp, int clientidentify) { public void getDatabasedata(String message, String wastetyp, int clientidentify) {
Log.debug(message); 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); ResultSet result = Database.executeQuery(message);
try { try {
if (!result.isBeforeFirst()) { if (!result.isBeforeFirst()) {

View File

@ -30,10 +30,10 @@ public class MainPage implements HttpHandler {
path += "index.html"; path += "index.html";
} }
Log.message("looking for: " + path); Log.debug("looking for: " + path);
if (path.contains(".html")){ if (path.contains(".html")){
if (LoginState.getObject().isLoggedIn()){ if (LoginState.getObject().isLoggedIn() || path.equals("/register.html")){ //pass only register page
sendPage(path, t); sendPage(path, t);
}else { }else {
Log.warning("user not logged in --> redirecting to login page"); Log.warning("user not logged in --> redirecting to login page");

View File

@ -13,7 +13,7 @@ import java.net.InetSocketAddress;
public class Webserver { public class Webserver {
public void startserver() { public void startserver() {
Log.info("starting server"); Log.info("starting Webserver");
HttpServer server = null; HttpServer server = null;
try { try {
server = HttpServer.create(new InetSocketAddress(8000), 0); server = HttpServer.create(new InetSocketAddress(8000), 0);

View File

@ -5,6 +5,7 @@ import com.wasteinformationserver.basicutils.Log;
import com.wasteinformationserver.db.JDCB; import com.wasteinformationserver.db.JDCB;
import com.wasteinformationserver.website.basicrequest.PostRequest; import com.wasteinformationserver.website.basicrequest.PostRequest;
import java.io.IOException;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
@ -13,14 +14,21 @@ public class DataRequest extends PostRequest {
@Override @Override
public String request(HashMap<String, String> params) { public String request(HashMap<String, String> params) {
String result = ""; String result = "";
JDCB jdcb;
try {
jdcb = JDCB.getInstance();
} catch (IOException e) {
Log.error("no connection to db");
return "{\"query\" : \"nodbconn\"}";
}
switch (params.get("action")) { switch (params.get("action")) {
case "newCity": case "newCity":
StringBuilder sb = new StringBuilder();
sb.append("{");
Log.debug(params.toString()); Log.debug(params.toString());
// check if wastezone and wasteregion already exists // 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")); 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") + "'"); 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; 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") + "');"); 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); System.out.println(status);
if (status == 1) { if (status == 1) {
result = "{\"status\" : \"inserted\"}"; sb.append("\"status\" : \"inserted\"}");
} else { } else {
result = "{\"status\" : \"inserterror\"}"; sb.append("\"status\" : \"inserterror\"");
} }
} else if (size > 1) { } else if (size > 1) {
Log.warning("more than one entry in db!!!"); Log.warning("more than one entry in db!!!");
result = "{\"status\" : \"exists\"}"; result = "\"status\" : \"exists\"";
} else { } else {
//already exists //already exists
System.out.println("already exists"); System.out.println("already exists");
result = "{\"status\" : \"exists\"}"; result = "\"status\" : \"exists\"";
} }
sb.append(",\"query\":\"ok\"");
sb.append("}");
Log.debug(result); Log.debug(result);
break; break;
case "getAllCities": case "getAllCities":
// TODO: 15.11.19 database call to get all data and store it as json. // 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(); Gson gson = new Gson();
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
ResultSet sett = jdcbc.executeQuery("select * from cities"); ResultSet sett = jdcb.executeQuery("select * from cities");
Log.debug(sett.toString()); Log.debug(sett.toString());
builder.append("{\"data\":["); builder.append("{\"data\":[");
try { try {
@ -87,10 +97,8 @@ public class DataRequest extends PostRequest {
case "deletecity": case "deletecity":
//DELETE FROM `cities` WHERE `id`=0 //DELETE FROM `cities` WHERE `id`=0
JDCB jdcbcc = new JDCB("users", "kOpaIJUjkgb9ur6S", "wasteinformation");
Log.debug(params.get("id")); 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); Log.debug(status);
break; break;

View File

@ -5,6 +5,7 @@ import com.wasteinformationserver.db.JDCB;
import com.wasteinformationserver.website.HttpTools; import com.wasteinformationserver.website.HttpTools;
import com.wasteinformationserver.website.basicrequest.PostRequest; import com.wasteinformationserver.website.basicrequest.PostRequest;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
public class RegisterRequest extends PostRequest { public class RegisterRequest extends PostRequest {
@ -14,7 +15,13 @@ public class RegisterRequest extends PostRequest {
String passhash = HttpTools.StringToMD5(params.get("password")); 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());"); 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 // TODO: 27.09.19 detect if register process was successful and reply right json

View File

@ -5,6 +5,7 @@ import com.wasteinformationserver.db.JDCB;
import com.wasteinformationserver.website.HttpTools; import com.wasteinformationserver.website.HttpTools;
import com.wasteinformationserver.website.basicrequest.PostRequest; import com.wasteinformationserver.website.basicrequest.PostRequest;
import java.io.IOException;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
@ -18,7 +19,16 @@ public class LoginRequest extends PostRequest {
String password = params.get("password"); String password = params.get("password");
String username = params.get("username"); 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"); Log.debug("successfully logged in to db");
String response = "{\"accept\": false}"; String response = "{\"accept\": false}";
try { try {

View File

@ -14,7 +14,7 @@ public class LoginState {
String lastname; String lastname;
String email; String email;
boolean loggedin = false; boolean loggedin = true; //todo set back!!!
public void logIn(){ public void logIn(){
loggedin=true; loggedin=true;