TimescaleDbHandler.java 2.5 KB
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
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();
}
}
}
}