cleaned project structure
This commit is contained in:
105
src/java/com/wasteinformationserver/Date.java
Normal file
105
src/java/com/wasteinformationserver/Date.java
Normal file
@ -0,0 +1,105 @@
|
||||
package com.wasteinformationserver;
|
||||
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.text.DateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Scanner;
|
||||
|
||||
public class Date {
|
||||
private int index = 0;
|
||||
ArrayList<String> list = new ArrayList<>();
|
||||
ArrayList<String> listnew = new ArrayList<>();
|
||||
public String nextDate;
|
||||
|
||||
|
||||
public void getdata() {
|
||||
|
||||
GregorianCalendar now = new GregorianCalendar();
|
||||
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
|
||||
String datum = df.format(now.getTime());
|
||||
|
||||
URL url = null;
|
||||
try {
|
||||
url = new URL("https://www.steyr.at/system/web/kalender.aspx?vdatum="+datum+"&bdatum=19.10.2019&typ=&typid=0&typids=225781950&detailonr=0&menuonr=225781812");
|
||||
Scanner scanner = new Scanner(new InputStreamReader(url.openStream()));
|
||||
|
||||
int n = 0;
|
||||
while (scanner.hasNext()) {
|
||||
String temp = scanner.next();
|
||||
addList(temp);
|
||||
}
|
||||
|
||||
} catch (MalformedURLException e) {
|
||||
e.printStackTrace();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
Filter();
|
||||
}
|
||||
|
||||
private void addList(String temp) {
|
||||
list.add(index, temp);
|
||||
}
|
||||
|
||||
public void printList() {
|
||||
for (int n = 0; n < list.size(); n++) {
|
||||
Log.debug(list.get(n));
|
||||
}
|
||||
}
|
||||
|
||||
public void printListnew() {
|
||||
for (int n = 0; n < listnew.size(); n++) {
|
||||
Log.debug(listnew.get(n));
|
||||
}
|
||||
}
|
||||
|
||||
private void Filter() {
|
||||
String temp = "href=\"/system/web/kalender.aspx?detailonr=225781954-6&menuonr=225781812\">Hausabfall";
|
||||
int counter = 0;
|
||||
|
||||
for (int n = 0; n < list.size(); n++) {
|
||||
if (list.get(n).equals(temp)) {
|
||||
counter++;
|
||||
|
||||
if (counter == 4) {
|
||||
|
||||
int zaehler = 0;
|
||||
|
||||
for (int v = n; v < list.size(); v++) {
|
||||
listnew.add(zaehler, list.get(v));
|
||||
zaehler++;
|
||||
}
|
||||
|
||||
/* String string = "004-034556";
|
||||
String[] parts = string.split("-");
|
||||
String part1 = parts[0]; // 004
|
||||
String part2 = parts[1]; // 034556*/
|
||||
|
||||
splitter();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void splitter()
|
||||
{
|
||||
String temp="</ul><h2>";
|
||||
|
||||
for (int n=0; n<listnew.size();n++)
|
||||
{
|
||||
|
||||
if(listnew.get(n).equals(temp))
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
123
src/java/com/wasteinformationserver/basicutils/Log.java
Normal file
123
src/java/com/wasteinformationserver/basicutils/Log.java
Normal file
@ -0,0 +1,123 @@
|
||||
package com.wasteinformationserver.basicutils;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
|
||||
public class Log {
|
||||
|
||||
private static final String ANSI_RESET = "\u001B[0m";
|
||||
private static final String ANSI_BLACK = "\u001B[30m";
|
||||
private static final String ANSI_RED = "\u001B[31m";
|
||||
private static final String ANSI_GREEN = "\u001B[32m";
|
||||
private static final String ANSI_YELLOW = "\u001B[33m";
|
||||
private static final String ANSI_BLUE = "\u001B[34m";
|
||||
private static final String ANSI_PURPLE = "\u001B[35m";
|
||||
private static final String ANSI_CYAN = "\u001B[36m";
|
||||
private static final String ANSI_WHITE = "\u001B[37m";
|
||||
|
||||
public static final int CRITICAL_ERROR = 6;
|
||||
public static final int ERROR = 5;
|
||||
public static final int WARNING = 4;
|
||||
public static final int INFO = 3;
|
||||
public static final int MESSAGE = 2;
|
||||
public static final int DEBUG = 1;
|
||||
|
||||
private static int Loglevel = 0;
|
||||
|
||||
private static ArrayList<String> colors = new ArrayList<String>(Arrays.asList("", "DEBUG", "MESSAGE", "INFO", "WARNING", "ERROR", "CRITICAL_ERROR"));
|
||||
|
||||
public static void criticalerror(Object msg) {
|
||||
if (Loglevel <= CRITICAL_ERROR)
|
||||
log(msg, CRITICAL_ERROR);
|
||||
}
|
||||
|
||||
public static void error(Object msg) {
|
||||
if (Loglevel <= ERROR)
|
||||
log(msg, ERROR);
|
||||
}
|
||||
|
||||
public static void warning(Object msg) {
|
||||
if (Loglevel <= WARNING)
|
||||
log(msg, WARNING);
|
||||
}
|
||||
|
||||
public static void info(Object msg) {
|
||||
if (Loglevel <= INFO)
|
||||
log(msg, INFO);
|
||||
}
|
||||
|
||||
public static void message(Object msg) {
|
||||
if (Loglevel <= MESSAGE)
|
||||
log(msg, MESSAGE);
|
||||
}
|
||||
|
||||
public static void debug(Object msg) {
|
||||
if (Loglevel <= DEBUG)
|
||||
log(msg, DEBUG);
|
||||
}
|
||||
|
||||
|
||||
public static void log(Object msg, int level) {
|
||||
boolean iswindows = System.getProperty("os.name").contains("Windows");
|
||||
StringBuilder builder = new StringBuilder();
|
||||
if (!iswindows) {
|
||||
switch (level) {
|
||||
case INFO:
|
||||
builder.append(ANSI_CYAN);
|
||||
break;
|
||||
case WARNING:
|
||||
builder.append(ANSI_YELLOW);
|
||||
break;
|
||||
case ERROR:
|
||||
builder.append(ANSI_RED);
|
||||
break;
|
||||
case CRITICAL_ERROR:
|
||||
builder.append(ANSI_RED);
|
||||
break;
|
||||
case MESSAGE:
|
||||
builder.append(ANSI_WHITE);
|
||||
break;
|
||||
case DEBUG:
|
||||
builder.append(ANSI_BLUE);
|
||||
break;
|
||||
}
|
||||
|
||||
}
|
||||
builder.append("[");
|
||||
builder.append(calcDate(System.currentTimeMillis()));
|
||||
builder.append("]");
|
||||
|
||||
builder.append(" [");
|
||||
builder.append(new Exception().getStackTrace()[2].getClassName());
|
||||
builder.append("]");
|
||||
|
||||
builder.append(" [");
|
||||
builder.append(colors.get(level));
|
||||
builder.append("]");
|
||||
|
||||
if (!iswindows) {
|
||||
builder.append(ANSI_WHITE);
|
||||
}
|
||||
|
||||
builder.append(" - ");
|
||||
builder.append(msg.toString());
|
||||
|
||||
if (!iswindows) {
|
||||
builder.append(ANSI_RESET);
|
||||
}
|
||||
System.out.println(builder.toString());
|
||||
}
|
||||
|
||||
private static String calcDate(long millisecs) {
|
||||
SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
Date resultdate = new Date(millisecs);
|
||||
return date_format.format(resultdate);
|
||||
}
|
||||
|
||||
public static void setLevel(int level) {
|
||||
Loglevel = level;
|
||||
}
|
||||
|
||||
}
|
90
src/java/com/wasteinformationserver/db/Database.java
Executable file
90
src/java/com/wasteinformationserver/db/Database.java
Executable file
@ -0,0 +1,90 @@
|
||||
package com.wasteinformationserver.db;
|
||||
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
|
||||
import javax.swing.table.DefaultTableModel;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Vector;
|
||||
|
||||
public abstract class
|
||||
Database {
|
||||
|
||||
protected String user;
|
||||
protected String password;
|
||||
|
||||
protected String host;
|
||||
protected int port;
|
||||
|
||||
protected String dbName;
|
||||
|
||||
public Database(String user, String password, String host, int port, String dbName) {
|
||||
this.user = user;
|
||||
this.password = password;
|
||||
this.host = host;
|
||||
this.port = port;
|
||||
this.dbName = dbName;
|
||||
}
|
||||
|
||||
public abstract Connection getConnection() throws SQLException;
|
||||
|
||||
public static void logToConsole(ResultSet res) {
|
||||
try {
|
||||
|
||||
ResultSetMetaData rsmd = res.getMetaData();
|
||||
|
||||
while (res.next()) {
|
||||
String row = "";
|
||||
|
||||
for (int i = 1; i <= rsmd.getColumnCount(); ++i) {
|
||||
if (row.length() > 0) {
|
||||
row += ", ";
|
||||
}
|
||||
|
||||
if (res.getObject(i) != null) {
|
||||
row +=
|
||||
rsmd.getColumnName(i) +
|
||||
": " +
|
||||
res.getObject(i).toString();
|
||||
}
|
||||
}
|
||||
|
||||
Log.debug(row);
|
||||
}
|
||||
|
||||
} catch (SQLException e) {
|
||||
}
|
||||
}
|
||||
|
||||
public static DefaultTableModel logToTable(ResultSet res) {
|
||||
try {
|
||||
ResultSetMetaData rsmd = res.getMetaData();
|
||||
Vector<String> columnNames = new Vector<>();
|
||||
int columnCount = rsmd.getColumnCount();
|
||||
|
||||
for (int i = 1; i <= columnCount; ++i) {
|
||||
columnNames.add(rsmd.getColumnName(i));
|
||||
}
|
||||
|
||||
Vector<Vector<Object>> data = new Vector<>();
|
||||
|
||||
while (res.next()) {
|
||||
Vector<Object> row = new Vector();
|
||||
|
||||
for (int i = 1; i <= columnCount; ++i) {
|
||||
row.add(res.getObject(i));
|
||||
}
|
||||
|
||||
data.add(row);
|
||||
}
|
||||
|
||||
return new DefaultTableModel(data, columnNames);
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
81
src/java/com/wasteinformationserver/db/JDCB.java
Normal file
81
src/java/com/wasteinformationserver/db/JDCB.java
Normal file
@ -0,0 +1,81 @@
|
||||
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 {
|
||||
static Connection conn;
|
||||
|
||||
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,
|
||||
ip,
|
||||
port,
|
||||
dbname);
|
||||
|
||||
try {
|
||||
conn = db.getConnection();
|
||||
loggedin = true;
|
||||
} catch (SQLException e) {
|
||||
throw new IOException("No connection to database");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public ResultSet executeQuery(String sql) {
|
||||
try {
|
||||
PreparedStatement stmt = conn.prepareStatement(sql);
|
||||
return stmt.executeQuery();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public int executeUpdate(String sql) {
|
||||
try {
|
||||
PreparedStatement stmt = conn.prepareStatement(sql);
|
||||
|
||||
return stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
29
src/java/com/wasteinformationserver/db/MySQLConnector.java
Executable file
29
src/java/com/wasteinformationserver/db/MySQLConnector.java
Executable file
@ -0,0 +1,29 @@
|
||||
package com.wasteinformationserver.db;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class MySQLConnector extends Database {
|
||||
|
||||
static {
|
||||
try {
|
||||
Class.forName("com.mysql.jdbc.Driver").newInstance();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public MySQLConnector(String user, String password, String host, int port, String dbName) {
|
||||
super(user, password, host, port, dbName);
|
||||
}
|
||||
|
||||
public Connection getConnection() throws SQLException {
|
||||
DriverManager.setLoginTimeout(1); // TODO: 30.11.19 set higher maybe
|
||||
return DriverManager.getConnection(
|
||||
"jdbc:mysql://" + host + ":" + port + "/" + dbName + "?useSSL=false",
|
||||
user,
|
||||
password);
|
||||
}
|
||||
|
||||
}
|
37
src/java/com/wasteinformationserver/db/PostgreSQLConnector.java
Executable file
37
src/java/com/wasteinformationserver/db/PostgreSQLConnector.java
Executable file
@ -0,0 +1,37 @@
|
||||
package com.wasteinformationserver.db;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.SQLException;
|
||||
|
||||
public class PostgreSQLConnector extends Database {
|
||||
|
||||
static {
|
||||
try {
|
||||
Class.forName("org.postgresql.Driver").newInstance();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public PostgreSQLConnector(String user, String password, String host, int port, String dbName) {
|
||||
super(user, password, host, port, dbName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Connection getConnection() {
|
||||
Connection con = null;
|
||||
|
||||
try {
|
||||
con = DriverManager.getConnection(
|
||||
"jdbc:postgresql://" + host + ":" + port + "/" + dbName,
|
||||
user,
|
||||
password);
|
||||
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return con;
|
||||
}
|
||||
}
|
54
src/java/com/wasteinformationserver/main.java
Normal file
54
src/java/com/wasteinformationserver/main.java
Normal file
@ -0,0 +1,54 @@
|
||||
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) {
|
||||
|
||||
Log.setLevel(Log.DEBUG);
|
||||
|
||||
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(200);
|
||||
Log.warning("Shutting down ...");
|
||||
|
||||
//shutdown routine
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}));
|
||||
|
||||
//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();
|
||||
|
||||
|
||||
//startup mqtt service
|
||||
Log.message("starting mqtt service");
|
||||
try{
|
||||
mqtt m = new mqtt();
|
||||
m.notifymessage();
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
4
src/java/com/wasteinformationserver/mqtt/Database.java
Normal file
4
src/java/com/wasteinformationserver/mqtt/Database.java
Normal file
@ -0,0 +1,4 @@
|
||||
package com.wasteinformationserver.mqtt;
|
||||
|
||||
public class Database {
|
||||
}
|
127
src/java/com/wasteinformationserver/mqtt/mqtt.java
Normal file
127
src/java/com/wasteinformationserver/mqtt/mqtt.java
Normal file
@ -0,0 +1,127 @@
|
||||
package com.wasteinformationserver.mqtt;
|
||||
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
import com.wasteinformationserver.db.JDCB;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
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;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
|
||||
public class mqtt {
|
||||
MqttClient client = null;
|
||||
|
||||
public mqtt() {
|
||||
|
||||
}
|
||||
|
||||
public void notifymessage() {
|
||||
|
||||
try {
|
||||
client = new MqttClient("tcp://192.168.65.15:1883", "JavaSample");
|
||||
MqttConnectOptions connOpts = new MqttConnectOptions();
|
||||
connOpts.setCleanSession(true);
|
||||
client.connect(connOpts);
|
||||
|
||||
} catch (MqttException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
mqttreceiver mr = new mqttreceiver(client);
|
||||
mr.addMessageReceivedListener(new ActionListener() {
|
||||
@Override
|
||||
public void actionPerformed(ActionEvent e) {
|
||||
String temp = e.getActionCommand();
|
||||
|
||||
String[] split = temp.split(",");
|
||||
getDatabasedata("SELECT pickupdates.pickupdate FROM pickupdates WHERE pickupdates.citywastezoneid=(SELECT cities.zone FROM cities WHERE cities.name='" + split[1] + "' AND cities.wastetype='" + split[2] + "' AND cities.zone=" + split[3] + ")", split[2], Integer.parseInt(split[0]));
|
||||
}
|
||||
});
|
||||
mr.getmessage();
|
||||
}
|
||||
|
||||
public void getDatabasedata(String message, String wastetyp, int clientidentify) {
|
||||
|
||||
Log.debug(message);
|
||||
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()) {
|
||||
int abholtag = 0;
|
||||
transmitmessageAbfallart(clientidentify + "," + wastetyp + "," + abholtag);
|
||||
} else {
|
||||
while (result.next()) {
|
||||
String temptime = String.valueOf(result.getString("pickupdate"));
|
||||
|
||||
GregorianCalendar now = new GregorianCalendar();
|
||||
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
|
||||
String date = df.format(now.getTime());
|
||||
String[] parts = temptime.split("-");
|
||||
String tempyear = parts[0];
|
||||
String[] yearsplit = tempyear.split("0");
|
||||
String tempyearnew = yearsplit[1];
|
||||
String newDate = parts[2] + "." + parts[1] + ".20" + tempyearnew;
|
||||
String[] partstwo = date.split(" ");
|
||||
String Datetomorrow=nexDayDate();
|
||||
|
||||
|
||||
int abholtag;
|
||||
if (partstwo[0].contains(newDate)||partstwo[0].contains(Datetomorrow)) {
|
||||
abholtag = 1;
|
||||
transmitmessageAbfallart(clientidentify + "," + wastetyp + "," + abholtag);
|
||||
}else {
|
||||
abholtag=0;
|
||||
transmitmessageAbfallart(clientidentify + "," + wastetyp + "," + abholtag);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
System.out.println("Exception");
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void transmitmessageAbfallart(String temp) {
|
||||
|
||||
mqtttransmitter mt = new mqtttransmitter(client);
|
||||
Log.debug(temp);
|
||||
mt.sendmessage(temp);
|
||||
}
|
||||
|
||||
private String nexDayDate() {
|
||||
|
||||
final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
|
||||
Date currentDate = new Date();
|
||||
|
||||
Calendar c = Calendar.getInstance();
|
||||
c.setTime(currentDate);
|
||||
c.add(Calendar.DATE, 1);
|
||||
Date currentDatePlusOne = c.getTime();
|
||||
|
||||
String temp=dateFormat.format(currentDatePlusOne);
|
||||
String split[]=temp.split("/");
|
||||
String newDate=split[2]+"."+split[1]+"."+split[0];
|
||||
return newDate;
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
65
src/java/com/wasteinformationserver/mqtt/mqttreceiver.java
Normal file
65
src/java/com/wasteinformationserver/mqtt/mqttreceiver.java
Normal file
@ -0,0 +1,65 @@
|
||||
package com.wasteinformationserver.mqtt;
|
||||
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
|
||||
import org.eclipse.paho.client.mqttv3.MqttCallback;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
|
||||
import java.awt.event.ActionEvent;
|
||||
import java.awt.event.ActionListener;
|
||||
import java.util.ArrayList;
|
||||
|
||||
public class mqttreceiver {
|
||||
|
||||
private MqttClient client;
|
||||
public ArrayList<ActionListener> mylisteners = new ArrayList<>();
|
||||
public String message;
|
||||
|
||||
public mqttreceiver(MqttClient mqtt) {
|
||||
this.client = mqtt;
|
||||
}
|
||||
|
||||
public String getmessage() {
|
||||
|
||||
try {
|
||||
client.setCallback(new MqttCallback() {
|
||||
@Override
|
||||
public void connectionLost(Throwable throwable) {
|
||||
Log.error("connection lost");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
|
||||
message =new String(mqttMessage.getPayload());
|
||||
notifylisteners(message);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
|
||||
|
||||
}
|
||||
});
|
||||
client.subscribe("TopicIn");
|
||||
Log.debug("subscribed topic");
|
||||
} catch (MqttException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return message;
|
||||
}
|
||||
|
||||
|
||||
private void notifylisteners(String message) {
|
||||
for (ActionListener ac : mylisteners) {
|
||||
ac.actionPerformed(new ActionEvent(this, 0, message));
|
||||
}
|
||||
}
|
||||
|
||||
public void addMessageReceivedListener(ActionListener l) {
|
||||
mylisteners.add(l);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -0,0 +1,42 @@
|
||||
package com.wasteinformationserver.mqtt;
|
||||
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
import org.eclipse.paho.client.mqttv3.MqttClient;
|
||||
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
|
||||
import org.eclipse.paho.client.mqttv3.MqttException;
|
||||
import org.eclipse.paho.client.mqttv3.MqttMessage;
|
||||
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
|
||||
|
||||
|
||||
public class mqtttransmitter {
|
||||
MqttClient client;
|
||||
|
||||
public mqtttransmitter(MqttClient client) {
|
||||
this.client=client;
|
||||
}
|
||||
|
||||
public void sendmessage(String temp) {
|
||||
String topic = "TopicOut";
|
||||
String content = temp;
|
||||
int qos = 2;
|
||||
MemoryPersistence persistence = new MemoryPersistence();
|
||||
|
||||
try {
|
||||
Log.debug("Connected");
|
||||
Log.debug("Publishing message: " + content);
|
||||
MqttMessage message = new MqttMessage(content.getBytes());
|
||||
message.setQos(qos);
|
||||
client.publish(topic, message);
|
||||
Log.debug("Message published");
|
||||
|
||||
|
||||
} catch (MqttException me) {
|
||||
Log.debug("reason " + me.getReasonCode());
|
||||
Log.debug("msg " + me.getMessage());
|
||||
Log.debug("loc " + me.getLocalizedMessage());
|
||||
Log.debug("cause " + me.getCause());
|
||||
Log.debug("excep " + me);
|
||||
me.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
19
src/java/com/wasteinformationserver/website/HttpTools.java
Normal file
19
src/java/com/wasteinformationserver/website/HttpTools.java
Normal file
@ -0,0 +1,19 @@
|
||||
package com.wasteinformationserver.website;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
public class HttpTools {
|
||||
public static String StringToMD5(String value) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
byte[] messageDigest = md.digest(value.getBytes());
|
||||
BigInteger no = new BigInteger(1, messageDigest);
|
||||
return no.toString(16);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
e.printStackTrace();
|
||||
return "";
|
||||
}
|
||||
}
|
||||
}
|
76
src/java/com/wasteinformationserver/website/MainPage.java
Normal file
76
src/java/com/wasteinformationserver/website/MainPage.java
Normal file
@ -0,0 +1,76 @@
|
||||
// Dear programmer:
|
||||
// When I wrote this code, only god and
|
||||
// I knew how it worked.
|
||||
// Now, only god knows it!
|
||||
//
|
||||
// Therefore, if you are trying to optimize
|
||||
// this routine and it fails (most surely),
|
||||
// please increase this counter as a
|
||||
// warning for the next person:
|
||||
//
|
||||
// total hours wasted here = 254
|
||||
//
|
||||
|
||||
package com.wasteinformationserver.website;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
import com.wasteinformationserver.website.datarequests.login.LoginState;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
public class MainPage implements HttpHandler {
|
||||
@Override
|
||||
public void handle(HttpExchange t) throws IOException {
|
||||
String path = t.getRequestURI().getPath();
|
||||
|
||||
if (path.equals("/")){
|
||||
path += "index.html";
|
||||
}
|
||||
|
||||
Log.debug("looking for: " + path);
|
||||
|
||||
if (path.contains(".html")){
|
||||
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");
|
||||
sendPage("/index.html",t);
|
||||
}
|
||||
}else { //only detect login state on html pages
|
||||
sendPage(path, t);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendPage(String path, HttpExchange t) throws IOException {
|
||||
InputStream fs = getClass().getResourceAsStream("/wwwroot"+path);
|
||||
|
||||
if (fs== null && path.substring(path.length() - 4).equals("html")) {
|
||||
Log.warning("wrong page sending 404");
|
||||
sendPage("/404Error.html",t);
|
||||
} else if(fs== null){
|
||||
|
||||
}else {
|
||||
// Object exists and is a file: accept with response code 200.
|
||||
String mime = "text/html";
|
||||
if (path.substring(path.length() - 3).equals(".js")) mime = "application/javascript";
|
||||
if (path.substring(path.length() - 3).equals("css")) mime = "text/css";
|
||||
|
||||
Headers h = t.getResponseHeaders();
|
||||
h.set("Content-Type", mime);
|
||||
t.sendResponseHeaders(200, 0);
|
||||
|
||||
OutputStream os = t.getResponseBody();
|
||||
|
||||
final byte[] buffer = new byte[0x10000];
|
||||
int count;
|
||||
while ((count = fs.read(buffer)) >= 0) {
|
||||
os.write(buffer, 0, count);
|
||||
}
|
||||
fs.close();
|
||||
os.close();
|
||||
}
|
||||
}
|
||||
}
|
36
src/java/com/wasteinformationserver/website/Webserver.java
Normal file
36
src/java/com/wasteinformationserver/website/Webserver.java
Normal file
@ -0,0 +1,36 @@
|
||||
package com.wasteinformationserver.website;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
import com.wasteinformationserver.website.datarequests.login.CheckLoginState;
|
||||
import com.wasteinformationserver.website.datarequests.DataRequest;
|
||||
import com.wasteinformationserver.website.datarequests.login.LoginRequest;
|
||||
import com.wasteinformationserver.website.datarequests.RegisterRequest;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.InetSocketAddress;
|
||||
|
||||
|
||||
public class Webserver {
|
||||
public void startserver() {
|
||||
Log.info("starting Webserver");
|
||||
HttpServer server = null;
|
||||
try {
|
||||
server = HttpServer.create(new InetSocketAddress(8000), 0);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
server.createContext("/", new MainPage());
|
||||
|
||||
server.createContext("/senddata/loginget", new LoginRequest());
|
||||
server.createContext("/senddata/registerpost",new RegisterRequest());
|
||||
server.createContext("/senddata/checkloginstate",new CheckLoginState());
|
||||
server.createContext("/senddata/wastedata",new DataRequest());
|
||||
|
||||
server.setExecutor(null); // creates a default executor
|
||||
server.start();
|
||||
Log.info("Server available at http://127.0.0.1:8000 now");
|
||||
|
||||
}
|
||||
}
|
@ -0,0 +1,46 @@
|
||||
package com.wasteinformationserver.website.basicrequest;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.util.HashMap;
|
||||
|
||||
public abstract class GetRequest implements HttpHandler {
|
||||
@Override
|
||||
public void handle(HttpExchange httpExchange) throws IOException {
|
||||
if (httpExchange.getRequestMethod().equals("GET")) {
|
||||
String query = httpExchange.getRequestURI().getQuery();
|
||||
|
||||
HashMap<String, String> params = new HashMap<>();
|
||||
|
||||
String[] res = query.split("&");
|
||||
for (String str : res) {
|
||||
String[] values = str.split("=");
|
||||
params.put(values[0], values[1]);
|
||||
|
||||
}
|
||||
|
||||
String response = myrequest(params);
|
||||
|
||||
|
||||
Headers h = httpExchange.getResponseHeaders();
|
||||
h.set("Content-Type", "application/json");
|
||||
httpExchange.sendResponseHeaders(200, 0);
|
||||
|
||||
OutputStream os = httpExchange.getResponseBody();
|
||||
os.write(response.getBytes());
|
||||
os.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param params received get params from com.wasteinformationserver.website
|
||||
* @return json reply to com.wasteinformationserver.website
|
||||
*/
|
||||
public abstract String myrequest(HashMap<String, String> params);
|
||||
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.wasteinformationserver.website.basicrequest;
|
||||
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpHandler;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.util.HashMap;
|
||||
|
||||
public abstract class PostRequest implements HttpHandler {
|
||||
|
||||
@Override
|
||||
public void handle(HttpExchange httpExchange) throws IOException {
|
||||
if (httpExchange.getRequestMethod().equals("POST")) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
InputStream ios = httpExchange.getRequestBody();
|
||||
int i;
|
||||
while ((i = ios.read()) != -1) {
|
||||
sb.append((char) i);
|
||||
}
|
||||
String query = sb.toString();
|
||||
|
||||
HashMap<String, String> params = new HashMap<>();
|
||||
|
||||
String[] res = query.split("&");
|
||||
for (String str : res) {
|
||||
String[] values = str.split("=");
|
||||
params.put(values[0], values[1]);
|
||||
}
|
||||
|
||||
String response = request(params);
|
||||
|
||||
|
||||
Headers h = httpExchange.getResponseHeaders();
|
||||
h.set("Content-Type", "application/json");
|
||||
httpExchange.sendResponseHeaders(200, 0);
|
||||
|
||||
OutputStream os = httpExchange.getResponseBody();
|
||||
os.write(response.getBytes());
|
||||
os.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param params received get params from com.wasteinformationserver.website
|
||||
* @return json reply to com.wasteinformationserver.website
|
||||
*/
|
||||
public abstract String request(HashMap<String, String> params);
|
||||
|
||||
}
|
@ -0,0 +1,103 @@
|
||||
package com.wasteinformationserver.website.datarequests;
|
||||
|
||||
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;
|
||||
|
||||
public class DataRequest extends PostRequest {
|
||||
@Override
|
||||
public String request(HashMap<String, String> 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
|
||||
|
||||
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;
|
||||
try {
|
||||
if (set != null) {
|
||||
set.last(); // moves cursor to the last row
|
||||
size = set.getRow(); // get row id
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
if (size == 0) {
|
||||
//doesnt exist
|
||||
System.out.println("doesnt exist");
|
||||
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) {
|
||||
sb.append("\"status\" : \"inserted\"}");
|
||||
} else {
|
||||
sb.append("\"status\" : \"inserterror\"");
|
||||
}
|
||||
|
||||
} else if (size > 1) {
|
||||
Log.warning("more than one entry in db!!!");
|
||||
result = "\"status\" : \"exists\"";
|
||||
} else {
|
||||
//already exists
|
||||
System.out.println("already exists");
|
||||
result = "\"status\" : \"exists\"";
|
||||
}
|
||||
|
||||
sb.append(",\"query\":\"ok\"");
|
||||
sb.append("}");
|
||||
|
||||
Log.debug(result);
|
||||
break;
|
||||
case "getAllCities":
|
||||
StringBuilder builder = new StringBuilder();
|
||||
|
||||
ResultSet sett = jdcb.executeQuery("select * from cities");
|
||||
Log.debug(sett.toString());
|
||||
builder.append("{\"data\":[");
|
||||
try {
|
||||
while (sett.next()) {
|
||||
builder.append("{\"cityname\":\"" + sett.getString("name") + "\"");
|
||||
builder.append(",\"wastetype\":\"" + sett.getString("wastetype") + "\"");
|
||||
builder.append(",\"id\":\"" + sett.getString("id") + "\"");
|
||||
builder.append(",\"zone\":\"" + sett.getString("zone") + "\"}");
|
||||
if (!sett.isLast()) {
|
||||
builder.append(",");
|
||||
}
|
||||
|
||||
// System.out.println(sett.getString("name"));
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
builder.append("]}");
|
||||
result = builder.toString();
|
||||
Log.debug(result);
|
||||
break;
|
||||
case "deletecity":
|
||||
//DELETE FROM `cities` WHERE `id`=0
|
||||
|
||||
Log.debug(params.get("id"));
|
||||
int status= jdcb.executeUpdate("DELETE FROM `cities` WHERE `id`='" + params.get("id")+"'");
|
||||
Log.debug(status);
|
||||
|
||||
break;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
@ -0,0 +1,30 @@
|
||||
package com.wasteinformationserver.website.datarequests;
|
||||
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
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 {
|
||||
@Override
|
||||
public String request(HashMap<String, String> params) {
|
||||
Log.debug(params.toString());
|
||||
|
||||
String passhash = HttpTools.StringToMD5(params.get("password"));
|
||||
|
||||
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
|
||||
return "{\"accept\": true}";
|
||||
}
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package com.wasteinformationserver.website.datarequests.login;
|
||||
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
import com.wasteinformationserver.website.basicrequest.PostRequest;
|
||||
|
||||
import java.util.HashMap;
|
||||
|
||||
public class CheckLoginState extends PostRequest {
|
||||
@Override
|
||||
public String request(HashMap<String, String> params) {
|
||||
Log.message("checking login state");
|
||||
if ((params.get("action")).equals("getloginstate")){
|
||||
if (LoginState.getObject().isLoggedIn()){
|
||||
return "{\"loggedin\":true, \"username\":\""+LoginState.getObject().getUsername()+"\"}";
|
||||
}else {
|
||||
return "{\"loggedin\":false}";
|
||||
}
|
||||
}else if ((params.get("action")).equals("logout")){
|
||||
Log.debug("logging out");
|
||||
LoginState.getObject().logOut();
|
||||
return "{\"loggedin\":false}";
|
||||
}
|
||||
return "{\"loggedin\":false}";
|
||||
}
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package com.wasteinformationserver.website.datarequests.login;
|
||||
|
||||
import com.wasteinformationserver.basicutils.Log;
|
||||
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;
|
||||
|
||||
public class LoginRequest extends PostRequest {
|
||||
@Override
|
||||
public String request(HashMap<String, String> params) {
|
||||
|
||||
Log.message("new login request");
|
||||
|
||||
String password = params.get("password");
|
||||
String username = params.get("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 {
|
||||
s.last();
|
||||
if (s.getRow() == 1) {
|
||||
//success
|
||||
if (HttpTools.StringToMD5(password).equals(s.getString("password"))) {
|
||||
Log.debug("login success");
|
||||
LoginState.getObject().logIn();
|
||||
LoginState.getObject().setAccountData(username,"","","");
|
||||
response = "{\"accept\": true}";
|
||||
} else {
|
||||
Log.debug("wrong password");
|
||||
}
|
||||
} else if (s.getRow() == 0) {
|
||||
//user not found
|
||||
Log.debug("user not found");
|
||||
} else {
|
||||
//internal error two users with same name...?
|
||||
}
|
||||
Log.debug("rowcount: " + s.getRow());
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return response;
|
||||
}
|
||||
}
|
@ -0,0 +1,53 @@
|
||||
package com.wasteinformationserver.website.datarequests.login;
|
||||
|
||||
public class LoginState {
|
||||
private LoginState() {}
|
||||
|
||||
private static LoginState mythis=new LoginState();
|
||||
|
||||
public static LoginState getObject(){
|
||||
return mythis;
|
||||
}
|
||||
|
||||
private String username;
|
||||
private String firstname;
|
||||
private String lastname;
|
||||
private String email;
|
||||
|
||||
boolean loggedin = false;
|
||||
|
||||
public void logIn(){
|
||||
loggedin=true;
|
||||
}
|
||||
|
||||
public void logOut(){
|
||||
loggedin=false;
|
||||
}
|
||||
|
||||
public void setAccountData(String username, String firstname, String lastname, String email){
|
||||
this.username=username;
|
||||
this.firstname=firstname;
|
||||
this.lastname=lastname;
|
||||
this.email=email;
|
||||
}
|
||||
|
||||
public boolean isLoggedIn(){
|
||||
return loggedin;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public String getFirstname() {
|
||||
return firstname;
|
||||
}
|
||||
|
||||
public String getLastname() {
|
||||
return lastname;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user