removed checked calls for JDBC and added connection check in JDBC class itself

This commit is contained in:
Lukas-Heiligenbrunner 2020-02-28 16:06:04 +01:00
parent aa023aeb95
commit 022ae044ab
5 changed files with 71 additions and 70 deletions

View File

@ -1,4 +1,7 @@
package com.wasteinformationserver.db; package com.wasteinformationserver.db;
import com.wasteinformationserver.basicutils.Log;
import java.io.IOException; import java.io.IOException;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -53,14 +56,15 @@ public class JDBC {
* @return JDBC object of this * @return JDBC object of this
* @throws IOException * @throws IOException
*/ */
public static JDBC getInstance() throws IOException { public static JDBC getInstance() {
if (loggedin) { if (!loggedin) {
return JDBC; try {
} else {
logintodb(usernamec, passwordc, dbnamec, ipc, portc); logintodb(usernamec, passwordc, dbnamec, ipc, portc);
return JDBC; } catch (IOException e) {
Log.Log.error("no connetion to db - retrying in 5min");
} }
}
return JDBC;
} }
private static void logintodb(String username, String password, String dbname, String ip, int port) throws IOException { private static void logintodb(String username, String password, String dbname, String ip, int port) throws IOException {
@ -76,6 +80,7 @@ public class JDBC {
loggedin = true; loggedin = true;
} catch (SQLException e) { } catch (SQLException e) {
throw new IOException("No connection to database"); throw new IOException("No connection to database");
// todo reconnect every 5mins or something
} }
} }
@ -108,4 +113,8 @@ public class JDBC {
return stmt.executeUpdate(); return stmt.executeUpdate();
} }
public boolean isConnected() {
return loggedin;
}
} }

View File

@ -20,9 +20,9 @@ import java.util.*
* @author Gregor Dutzler * @author Gregor Dutzler
*/ */
class MqttService(serverurl: String, port: String) { class MqttService(serverurl: String, port: String) {
private var client: MqttClient? = null private val serveruri: String = "tcp://$serverurl:$port"
private val serveruri: String private var client: MqttClient = MqttClient(serveruri, "JavaSample42")
private var db: JDBC? = null private var db: JDBC = JDBC.getInstance()
/** /**
* init mqtt service * init mqtt service
@ -32,8 +32,7 @@ class MqttService(serverurl: String, port: String) {
* @param port mqtt server port * @param port mqtt server port
*/ */
init { init {
serveruri = "tcp://$serverurl:$port" connectToDb()
connect()
} }
/** /**
@ -44,26 +43,27 @@ class MqttService(serverurl: String, port: String) {
client = MqttClient(serveruri, "JavaSample42") client = MqttClient(serveruri, "JavaSample42")
val connOpts = MqttConnectOptions() val connOpts = MqttConnectOptions()
connOpts.isCleanSession = true connOpts.isCleanSession = true
client!!.connect(connOpts) client.connect(connOpts)
client!!.setCallback(object : MqttCallback { client.setCallback(object : MqttCallback {
override fun connectionLost(throwable: Throwable) { override fun connectionLost(throwable: Throwable) {
error("connection lost") error("connection lost")
connect() connectToDb()
} }
override fun messageArrived(s: String, mqttMessage: MqttMessage) { override fun messageArrived(s: String, mqttMessage: MqttMessage) {
val deviceid = String(mqttMessage.payload) val deviceid = String(mqttMessage.payload)
message("received Request from PCB") message("received Request from PCB")
val res = db!!.executeQuery("SELECT * from devices WHERE DeviceID=$deviceid") val res = db.executeQuery("SELECT * from devices WHERE DeviceID=$deviceid")
try { try {
res.last() res.last()
if (res.row != 0) { //existing device if (res.row != 0) { //existing device
res.first() res.first()
val devicecities = db!!.executeQuery("SELECT * from device_city WHERE DeviceID='$deviceid'") val devicecities = db.executeQuery("SELECT * from device_city WHERE DeviceID='$deviceid'")
devicecities.last() devicecities.last()
if (devicecities.row == 0) { //not configured if (devicecities.row == 0) { //not configured
tramsmitMessage("$deviceid,-1") tramsmitMessage("$deviceid,-1")
} else { }
else {
devicecities.first() devicecities.first()
devicecities.previous() devicecities.previous()
@ -72,8 +72,9 @@ class MqttService(serverurl: String, port: String) {
checkDatabase(cityid, deviceid.toInt()) checkDatabase(cityid, deviceid.toInt())
} }
} }
} else { //new device }
db!!.executeUpdate("INSERT INTO devices (DeviceID) VALUES ($deviceid)") else { //new device
db.executeUpdate("INSERT INTO devices (DeviceID) VALUES ($deviceid)")
info("new device registered to server") info("new device registered to server")
tramsmitMessage("$deviceid,-1") tramsmitMessage("$deviceid,-1")
} }
@ -84,7 +85,7 @@ class MqttService(serverurl: String, port: String) {
override fun deliveryComplete(iMqttDeliveryToken: IMqttDeliveryToken) {} override fun deliveryComplete(iMqttDeliveryToken: IMqttDeliveryToken) {}
}) })
client!!.subscribe("TopicIn") client.subscribe("TopicIn")
} catch (e: MqttException) { } catch (e: MqttException) {
error("Connection to the Broker failed") error("Connection to the Broker failed")
} }
@ -92,24 +93,26 @@ class MqttService(serverurl: String, port: String) {
private fun checkDatabase(citywastezoneid: Int, deviceid: Int) { private fun checkDatabase(citywastezoneid: Int, deviceid: Int) {
var wastetype = -1 var wastetype = -1
val set2 = db!!.executeQuery("SELECT * FROM cities WHERE `id`='$citywastezoneid'") val set2 = db.executeQuery("SELECT * FROM cities WHERE `id`='$citywastezoneid'")
try { try {
set2.last() set2.last()
if (set2.row != 1) { //error if (set2.row != 1) { //error
} else { }
else {
val typ = set2.getString("wastetype") val typ = set2.getString("wastetype")
wastetype = getIntTyp(typ) wastetype = getIntTyp(typ)
} }
} catch (e: SQLException) { } catch (e: SQLException) {
e.printStackTrace() e.printStackTrace()
} }
val result = db!!.executeQuery("SELECT pickupdates.pickupdate FROM pickupdates WHERE pickupdates.citywastezoneid=$citywastezoneid") val result = db.executeQuery("SELECT pickupdates.pickupdate FROM pickupdates WHERE pickupdates.citywastezoneid=$citywastezoneid")
try { try {
result.last() result.last()
if (result.row == 0) { //if not found in db --> send zero if (result.row == 0) { //if not found in db --> send zero
debug("not found in db") debug("not found in db")
tramsmitMessage("$deviceid,$wastetype,0") tramsmitMessage("$deviceid,$wastetype,0")
} else { }
else {
debug(result.getString("pickupdate")) debug(result.getString("pickupdate"))
result.first() result.first()
do { do {
@ -138,41 +141,33 @@ class MqttService(serverurl: String, port: String) {
val message = MqttMessage(temp.toByteArray()) val message = MqttMessage(temp.toByteArray())
message.qos = 2 message.qos = 2
try { try {
client!!.publish("TopicOut", message) client.publish("TopicOut", message)
} catch (e: MqttException) { } catch (e: MqttException) {
e.printStackTrace() e.printStackTrace()
} }
} }
private fun getTyp(number: Int): String? { private fun getTyp(number: Int): String? {
if (number == 1) { return when (number) {
return "Plastic" 1 -> "Plastic"
} else if (number == 2) { 2 -> "Metal"
return "Metal" 3 -> "Residual waste"
} else if (number == 3) { 4 -> "Biowaste"
return "Residual waste" else -> null
} else if (number == 4) {
return "Biowaste"
} }
return null
} }
private fun getIntTyp(temp: String): Int { private fun getIntTyp(temp: String): Int {
var number = 0 return when (temp) {
when (temp) { "Plastic" -> 1
"Plastic" -> number = 1 "Metal" -> 2
"Metal" -> number = 2 "Residual waste" -> 3
"Residual waste" -> number = 3 "Biowaste" -> 4
"Biowaste" -> number = 4 else -> 0
} }
return number
} }
private fun connect() { private fun connectToDb() {
try {
db = JDBC.getInstance() db = JDBC.getInstance()
} catch (e: IOException) {
error("no connetion to db")
}
} }
} }

View File

@ -6,7 +6,6 @@ import com.wasteinformationserver.basicutils.Log.Log.error
import com.wasteinformationserver.basicutils.Log.Log.warning import com.wasteinformationserver.basicutils.Log.Log.warning
import com.wasteinformationserver.db.JDBC import com.wasteinformationserver.db.JDBC
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.sql.SQLIntegrityConstraintViolationException import java.sql.SQLIntegrityConstraintViolationException
@ -18,12 +17,12 @@ class DataRequest : PostRequest() {
val sb = StringBuilder() val sb = StringBuilder()
var set: ResultSet? var set: ResultSet?
var status = -1 var status = -1
val jdbc: JDBC = try { val jdbc: JDBC = JDBC.getInstance()
JDBC.getInstance() if (!jdbc.isConnected) {
} catch (e: IOException) {
error("no connection to db") error("no connection to db")
return "{\"query\" : \"nodbconn\"}" return "{\"query\" : \"nodbconn\"}"
} }
when (params["action"]) { when (params["action"]) {
"newCity" -> { "newCity" -> {
sb.append("{") sb.append("{")

View File

@ -4,21 +4,20 @@ import com.wasteinformationserver.basicutils.Log.Log.debug
import com.wasteinformationserver.basicutils.Log.Log.error import com.wasteinformationserver.basicutils.Log.Log.error
import com.wasteinformationserver.db.JDBC import com.wasteinformationserver.db.JDBC
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.* import java.util.*
class DeviceRequest : PostRequest() { class DeviceRequest : PostRequest() {
override fun request(params: HashMap<String, String>): String { override fun request(params: HashMap<String, String>): String {
var jdbc: JDBC? = null val jdbc = JDBC.getInstance()
try { if (!jdbc.isConnected) {
jdbc = JDBC.getInstance() error("no connection to db")
} catch (e: IOException) { return "{\"query\" : \"nodbconn\"}"
e.printStackTrace()
} }
val sb = StringBuilder() val sb = StringBuilder()
var deviceset: ResultSet val deviceset: ResultSet
when (params["action"]) { when (params["action"]) {
"getdevices" -> { "getdevices" -> {
deviceset = jdbc!!.executeQuery("SELECT * FROM `devices") deviceset = jdbc!!.executeQuery("SELECT * FROM `devices")
@ -135,7 +134,7 @@ class DeviceRequest : PostRequest() {
} }
"deleteDevice" -> { "deleteDevice" -> {
try { try {
jdbc!!.executeUpdate("DELETE FROM devices WHERE `DeviceID`='" + params["id"] + "'") jdbc.executeUpdate("DELETE FROM devices WHERE `DeviceID`='" + params["id"] + "'")
jdbc.executeUpdate("DELETE FROM device_city WHERE `DeviceID`='" + params["id"] + "'") jdbc.executeUpdate("DELETE FROM device_city WHERE `DeviceID`='" + params["id"] + "'")
} catch (e: SQLException) { } catch (e: SQLException) {
e.printStackTrace() e.printStackTrace()
@ -145,7 +144,7 @@ class DeviceRequest : PostRequest() {
"addtodb" -> { "addtodb" -> {
var cityid = -1 var cityid = -1
try { try {
val device = jdbc!!.executeQuery("SELECT * FROM cities WHERE name='" + params["cityname"] + "' AND wastetype='" + params["wastetype"] + "' AND zone='" + params["zonename"] + "'") val device = jdbc.executeQuery("SELECT * FROM cities WHERE name='" + params["cityname"] + "' AND wastetype='" + params["wastetype"] + "' AND zone='" + params["zonename"] + "'")
device.first() device.first()
cityid = device.getInt("id") cityid = device.getInt("id")
jdbc.executeUpdate("INSERT INTO `device_city` (`DeviceID`, `CityID`) VALUES ('" + params["deviceid"] + "', '" + cityid + "');") jdbc.executeUpdate("INSERT INTO `device_city` (`DeviceID`, `CityID`) VALUES ('" + params["deviceid"] + "', '" + cityid + "');")
@ -156,11 +155,11 @@ class DeviceRequest : PostRequest() {
} }
"getheader" -> { "getheader" -> {
try { try {
var numberset = jdbc!!.executeQuery("SELECT * FROM devices") var numberset = jdbc.executeQuery("SELECT * FROM devices")
numberset.last() numberset.last()
val devicenr = numberset.row val devicenr = numberset.row
numberset = jdbc!!.executeQuery("SELECT * FROM devices WHERE CityID=-1") numberset = jdbc.executeQuery("SELECT * FROM devices WHERE CityID=-1")
numberset.last() numberset.last()
val unconfigureddevices = numberset.row val unconfigureddevices = numberset.row

View File

@ -4,7 +4,6 @@ import com.wasteinformationserver.basicutils.Log;
import com.wasteinformationserver.db.JDBC; import com.wasteinformationserver.db.JDBC;
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 +12,14 @@ public class NewDateRequest extends PostRequest {
@Override @Override
public String request(HashMap<String, String> params) { public String request(HashMap<String, String> params) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
JDBC jdbc;
ResultSet set; ResultSet set;
try {
jdbc = JDBC.getInstance(); JDBC jdbc = JDBC.getInstance();
} catch (IOException e) { if (!jdbc.isConnected()) {
Log.Log.error("no connection to db"); Log.Log.error("no connection to db");
return "{\"query\" : \"nodbconn\"}"; return "{\"query\" : \"nodbconn\"}";
} }
switch (params.get("action")) { switch (params.get("action")) {
case "getCitynames": case "getCitynames":
set = jdbc.executeQuery("select * from cities"); set = jdbc.executeQuery("select * from cities");