package edu.auth.od_pcap_mcod.report;
import edu.auth.od_pcap_mcod.model.Data;
import java.sql.Statement;
import java.time.Instant;
import java.util.Properties;
import java.sql.Connection;
import java.sql.DriverManager;
public class TimescaleDbHandler implements IReporter {
private Connection conn;
private String reportTable;
TimescaleDbHandler(String host, int port, String username, String password, Boolean ssl, String dbName, String tableName) {
Properties props = new Properties();
props.put("jdbc.url", "jdbc:postgresql://"+host+":"+port+"/"+dbName);
props.put("user", username);
props.put("password", password);
props.put("ssl", ssl);
reportTable = tableName;
try {
conn = DriverManager.getConnection(props.getProperty("jdbc.url"), props);
createTable();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void reportOutlier(Data outlier, String label) {
Statement statement = null;
try {
statement = conn.createStatement();
statement.executeUpdate("INSERT INTO "+reportTable+ "(asset_id,value,incident_date,timeframe,created_on) VALUES ('"+label+"', "+outlier.getValues()[0]+", '"+outlier.getActualTime()+"', '0', '"+ Instant.now()+"')");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
private void createTable() {
String sqlCreate = "CREATE TABLE IF NOT EXISTS " + reportTable
+ " (uuid serial PRIMARY KEY,"
+ " asset_id VARCHAR (100) NOT NULL,"
+ " value REAL NOT NULL,"
+ " incident_date TIMESTAMP NOT NULL,"
+ " timeframe VARCHAR (355) NOT NULL,"
+ " created_on TIMESTAMP NOT NULL)";
Statement stmt = null;
try {
stmt = conn.createStatement();
stmt.execute(sqlCreate);
} catch (Exception throwables) {
throwables.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e){
e.printStackTrace();
}
}
}
}