changed folder structure

This commit is contained in:
2019-10-03 08:42:09 +02:00
parent 889cdef86b
commit 4e4ecb5dc6
18 changed files with 48 additions and 46 deletions

View File

@ -0,0 +1,85 @@
package com.wasteinformationserver;
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); // 14.04.2012
String datum = df.format(now.getTime());
URL url = null;
try {
url = new URL("https://www.steyr.at/system/web/kalender.aspx?vdatum=" + datum + "&bdatum=12.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 < listnew.size(); n++) {
System.out.println(listnew.get(n));
}
}
private void Filter() {
String temp = "href=\"/system/web/kalender.aspx?detailonr=225781954-6&amp;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
for (int q = 0; q < listnew.size(); q++) {
}
}
}
}
}
}

View File

@ -0,0 +1,102 @@
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 ArrayList<String> colors= new ArrayList<String>(Arrays.asList("","DEBUG","MESSAGE","INFO","WARNING","ERROR","CRITICAL_ERROR"));
public static void criticalerror(String msg){
log(msg,CRITICAL_ERROR);
}
public static void error(String msg){
log(msg,ERROR);
}
public static void warning(String msg){
log(msg,WARNING);
}
public static void info(String msg){
log(msg,INFO);
}
public static void message(String msg){
log(msg,MESSAGE);
}
public static void debug(String msg){
log(msg,DEBUG);
}
public static void log(String msg, int level){
StringBuilder builder = new StringBuilder();
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("]");
builder.append(ANSI_WHITE);
builder.append(" - ");
builder.append(msg);
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);
}
}

View File

@ -0,0 +1,87 @@
package com.wasteinformationserver.db;
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();
}
}
System.out.println(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;
}
}

View File

@ -0,0 +1,28 @@
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 {
return DriverManager.getConnection(
"jdbc:mysql://" + host + ":" + port + "/" + dbName + "?useSSL=false",
user,
password);
}
}

View File

@ -0,0 +1,48 @@
package com.wasteinformationserver.db;
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();
}
}
public abstract String request(HashMap<String, String> params);
}

View 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;
}
}

View File

@ -0,0 +1,53 @@
package com.wasteinformationserver.db;
import com.wasteinformationserver.basicutils.Log;
import com.wasteinformationserver.db.Database;
import com.wasteinformationserver.db.MySQLConnector;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class jdcb {
Connection conn;
public jdcb(String username, String password, String dbName) {
Database db = new MySQLConnector(
username,
password,
"192.168.65.15",
3306,
dbName);
try {
conn = db.getConnection();
} catch (SQLException e) {
Log.error("no connection to Database! DB Server not started...?");
}
}
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;
}
}

View File

@ -0,0 +1,33 @@
package com.wasteinformationserver;
import com.wasteinformationserver.basicutils.Log;
import com.wasteinformationserver.website.Webserver;
public class main {
public static void main(String[] args) {
/*
com.wasteinformationserver.Date D=new com.wasteinformationserver.Date();
D.getdata();
D.printList();
*/
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
Thread.sleep(200);
Log.warning("Shutting down ...");
//shutdown routine
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
Thread mythread = new Thread(() -> new Webserver().startserver());
mythread.start();
Log.message("thread started");
}
}

View File

@ -0,0 +1,42 @@
package com.wasteinformationserver;
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 mqtt {
public mqtt() {
String topic = "MQTT Examples";
String content = "Message from MqttPublishSample";
int qos = 2;
String broker = "tcp://iot.eclipse.org:1883";
String clientId = "JavaSample";
MemoryPersistence persistence = new MemoryPersistence();
try {
MqttClient sampleClient = new MqttClient(broker, clientId, persistence);
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
System.out.println("Connecting to broker: "+broker);
sampleClient.connect(connOpts);
System.out.println("Connected");
System.out.println("Publishing message: "+content);
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
sampleClient.publish(topic, message);
System.out.println("Message published");
sampleClient.disconnect();
System.out.println("Disconnected");
System.exit(0);
} catch(MqttException me) {
System.out.println("reason "+me.getReasonCode());
System.out.println("msg "+me.getMessage());
System.out.println("loc "+me.getLocalizedMessage());
System.out.println("cause "+me.getCause());
System.out.println("excep "+me);
me.printStackTrace();
}
}
}

View File

@ -0,0 +1,24 @@
package com.wasteinformationserver.website;
import com.wasteinformationserver.db.PostRequest;
import java.util.HashMap;
public class CheckLoginState extends PostRequest {
@Override
public String request(HashMap<String, String> params) {
System.out.println("checkin 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")){
System.out.println("logging out");
LoginState.getObject().logOut();
return "{\"loggedin\":false}";
}
return "{\"loggedin\":false}";
}
}

View File

@ -0,0 +1,46 @@
package com.wasteinformationserver.website;
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);
}

View 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 "";
}
}
}

View File

@ -0,0 +1,44 @@
package com.wasteinformationserver.website;
import com.wasteinformationserver.db.PostRequest;
import com.wasteinformationserver.db.jdcb;
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) {
String password = params.get("password");
String username = params.get("username");
ResultSet s = new jdcb("users", "kOpaIJUjkgb9ur6S", "wasteinformation").executeQuery("select * from user where username ='" + username + "'");
String response = "{\"accept\": false}";
try {
s.last();
if (s.getRow() == 1) {
//success
if (HttpTools.StringToMD5(password).equals(s.getString("password"))) {
System.out.println("login success");
LoginState.getObject().logIn();
LoginState.getObject().setAccountData(username,"","","");
response = "{\"accept\": true}";
} else {
System.out.println("wrong password");
}
} else if (s.getRow() == 0) {
//user not found
System.out.println("user not found");
} else {
//internal error two users with same name...?
}
System.out.println("rowcount: " + s.getRow());
} catch (SQLException e) {
e.printStackTrace();
}
return response;
}
}

View File

@ -0,0 +1,53 @@
package com.wasteinformationserver.website;
public class LoginState {
private LoginState() {}
private static LoginState mythis=new LoginState();
public static LoginState getObject(){
return mythis;
}
String username;
String firstname;
String lastname;
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;
}
}

View File

@ -0,0 +1,58 @@
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 java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
public class MainPage implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String root = "./wwwroot";
URI uri = t.getRequestURI();
String path;
if (uri.getPath().equals("/")) {
path = "/index.html";
} else {
path = uri.getPath();
}
Log.message("looking for: " + root + path);
File file = new File(root + path).getCanonicalFile();
if (!file.isFile()) {
// Object does not exist or is not a file: reject with 404 error.
String response = "404 (Not Found)\n";
t.sendResponseHeaders(404, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
} 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();
FileInputStream fs = new FileInputStream(file);
final byte[] buffer = new byte[0x10000];
int count;
while ((count = fs.read(buffer)) >= 0) {
os.write(buffer, 0, count);
}
fs.close();
os.close();
}
}
}

View File

@ -0,0 +1,21 @@
package com.wasteinformationserver.website;
import com.wasteinformationserver.db.PostRequest;
import com.wasteinformationserver.db.jdcb;
import java.util.HashMap;
public class RegisterRequest extends PostRequest {
@Override
public String request(HashMap<String, String> params) {
System.out.println(params.toString());
String passhash = HttpTools.StringToMD5(params.get("password"));
jdcb myjd = 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}";
}
}

View File

@ -0,0 +1,33 @@
package com.wasteinformationserver.website;
import com.sun.net.httpserver.HttpServer;
import com.wasteinformationserver.basicutils.Log;
import java.io.IOException;
import java.net.InetSocketAddress;
public class Webserver {
public void startserver() {
Log.info("starting server");
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.setExecutor(null); // creates a default executor
server.start();
Log.info("Server available at http://127.0.0.1:8000 now");
}
}