1
0
This repository has been archived on 2024-01-25. You can view files and clone it, but cannot push or open issues or pull requests.
MinecraftElectricalAge/src/main/java/ch/hevs/isi/db/DatabaseConnector.java

87 lines
2.6 KiB
Java
Raw Normal View History

package ch.hevs.isi.db;
import ch.hevs.isi.core.DataPoint;
import ch.hevs.isi.core.DataPointListener;
2023-05-17 14:13:27 +02:00
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
2023-05-15 09:43:50 +02:00
public class DatabaseConnector implements DataPointListener {
2023-05-17 14:13:27 +02:00
Properties properties = new Properties();
String default_token = System.getenv("SECRET_TOKEN");
String default_url;
String default_org;
String default_bucket;
String fullURL;
URL myURL;
HttpURLConnection con;
private static DatabaseConnector mySelf = null;
private DatabaseConnector (){
2023-05-17 14:13:27 +02:00
try (InputStream input = new FileInputStream("src/config.properties")) {
properties.load(input);
} catch (Exception e) {
e.printStackTrace();
}
default_url = properties.getProperty("URL");
default_org = properties.getProperty("ORG");
default_bucket = properties.getProperty("BUCKET");
}
public static DatabaseConnector getMySelf(){
if (mySelf == null){
mySelf = new DatabaseConnector();
}
return mySelf;
}
public void initialize(String url){
2023-05-17 14:13:27 +02:00
String org = default_org;
String bucket = default_bucket;
fullURL = url + "/api/v2/write?org=" + org + "&bucket=" + bucket;
System.out.println(fullURL);
try{
myURL = new URL(fullURL);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void pushToDatabase(DataPoint dp){
2023-05-17 14:13:27 +02:00
String data = "measurement " + dp.toString();
try {
HttpURLConnection con = (HttpURLConnection) myURL.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Authorization", "Token " + default_token);
con.setRequestProperty("Content-Type", "application/json");
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(data);
writer.flush();
int respondCode = con.getResponseCode();
System.out.println(dp.toString() + " -> Database. Code: " + respondCode);
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onNewValue(DataPoint dp) {
pushToDatabase(dp);
}
}