diff --git a/.github/workflows/build-docker.yml b/.github/workflows/build-docker.yml
new file mode 100644
index 0000000..ee530bb
--- /dev/null
+++ b/.github/workflows/build-docker.yml
@@ -0,0 +1,22 @@
+name: Docker Build Test
+
+on:
+ push:
+ branches-ignore:
+ - main
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout Repository
+ uses: actions/checkout@v4
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Build Docker image
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: ./Dockerfile
diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml
deleted file mode 100644
index 16b4c5a..0000000
--- a/.github/workflows/maven-publish.yml
+++ /dev/null
@@ -1,46 +0,0 @@
-# This workflow will build a package using Maven and then publish it to GitHub packages when a release is created
-# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#apache-maven-with-a-settings-path
-
-name: Maven Package
-
-on:
- release:
- types: [created]
-
-jobs:
- container-job:
- environment: production
- runs-on: ubuntu-latest
- permissions:
- contents: read
- packages: write
- services:
- postgres_db:
- image: postgres
- env:
- POSTGRES_USER: postgres
- POSTGRES_PASSWORD: postgres
- POSTGRES_DB: postgres
- ports:
- - 5432:5432
- # needed because the postgres container does not provide a healthcheck
- options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
-
- steps:
- - uses: actions/checkout@v3
- - name: Set up Docker Buildx
- id: buildx
- uses: docker/setup-buildx-action@v2
-
- - name: Login to DockerHub
- uses: docker/login-action@v2
- with:
- username: ${{ secrets.DOCKERHUB_USERNAME }}
- password: ${{ secrets.DOCKERHUB_TOKEN }}
-
- - name: Docker Build and Push to DockerHub
- uses: docker/build-push-action@v3
- with:
- context: .
- push: true
- tags: lrprojects/sensor-spring-web:latest
diff --git a/.github/workflows/publish-docker.yml b/.github/workflows/publish-docker.yml
new file mode 100644
index 0000000..ec49db1
--- /dev/null
+++ b/.github/workflows/publish-docker.yml
@@ -0,0 +1,40 @@
+name: Docker Build
+
+on:
+ push:
+ branches:
+ - main
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout Repository
+ uses: actions/checkout@v4
+
+ - name: Install xmlstarlet
+ run: sudo apt-get install -y xmlstarlet
+
+ - name: Extract version from pom.xml
+ id: extract_version
+ run: |
+ VERSION=$(xmlstarlet sel -t -v "/_:project/_:version" pom.xml)
+ echo "VERSION=$VERSION"
+ echo "::set-output name=version::$VERSION"
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Login to DockerHub
+ uses: docker/login-action@v3
+ with:
+ username: ${{ secrets.DOCKERHUB_USERNAME }}
+ password: ${{ secrets.DOCKERHUB_PASSWORD }}
+
+ - name: Build and Push Docker image
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: ./Dockerfile
+ push: true
+ tags: lrprojects/tempserver:${{ steps.extract_version.outputs.version }}
diff --git a/Dockerfile b/Dockerfile
index 0f70fa7..dffe1cd 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,14 +1,14 @@
#Maven Build
FROM maven:3.8.3-openjdk-17-slim AS builder
-COPY pom.xml /app/
-COPY src /app/src
-ENV DB_USER=postgres
-ENV DB_PASSWORD=postgres
-ENV DATASOURCE_URL=jdbc:postgresql://127.0.0.1:5432/postgres
-RUN --mount=type=cache,target=/root/.m2 mvn -f /app/pom.xml clean package -DskipTests
+COPY pom.xml /tmp/pom.xml
+WORKDIR /tmp
+RUN mvn -B -f /tmp/pom.xml dependency:resolve
+COPY src /tmp/src
+RUN mvn clean install
#Run
FROM openjdk:17-jdk-slim
-COPY --from=builder /app/target/SpringServer-1.jar app.jar
+WORKDIR /app
+COPY --from=build /tmp/target/*jar /app/app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..950d917
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,43 @@
+services:
+ temp-server:
+ container_name: temp-server
+ build: .
+ restart: unless-stopped
+ ports:
+ - 8081:8081
+ env_file:
+ - ./.env
+ environment:
+ DB_HOST: db
+ EMAIL: lr.dev.projects@gmail.com
+
+ # ---- Edit to change default: ----
+ # PORT: 8081
+
+ # ---- From .env file: -------
+ # POSTGRES_PASSWORD
+ # POSTGRES_USER
+ # POSTGRES_DB
+ # EMAIL_PASSWORD
+ # SECRET
+ depends_on:
+ - db
+ networks:
+ - net
+ db:
+ image: postgres:16
+ restart: unless-stopped
+ container_name: stick-it-db
+ ports:
+ - 5433:5432
+ volumes:
+ - ./postgres-data:/var/lib/postgresql/data
+ - ./backup:/backup
+ env_file:
+ - ./.env
+ networks:
+ - net
+
+networks:
+ net:
+ name: "stick-it-network"
\ No newline at end of file
diff --git a/openapi/methods/categories.yaml b/openapi/methods/categories.yaml
new file mode 100644
index 0000000..67c3c5e
--- /dev/null
+++ b/openapi/methods/categories.yaml
@@ -0,0 +1,52 @@
+get:
+ summary: Get all sensor categories
+ operationId: getAllSensorCategories
+ tags:
+ - Sensor Categories
+ responses:
+ '200':
+ description: A list of sensor categories
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '../schemas/categoryDto.yaml'
+put:
+ summary: Update a sensor category
+ operationId: updateSensorCategory
+ tags:
+ - Sensor Categories
+ requestBody:
+ description: The sensor category to update
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/categoryDto.yaml'
+ responses:
+ '200':
+ description: The updated sensor category
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/categoryDto.yaml'
+post:
+ summary: Create a new sensor category
+ operationId: createSensorCategory
+ tags:
+ - Sensor Categories
+ requestBody:
+ description: The sensor category to create
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/categoryDto.yaml'
+ responses:
+ '200':
+ description: The created sensor category
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/categoryDto.yaml'
\ No newline at end of file
diff --git a/openapi/methods/categoriesById.yaml b/openapi/methods/categoriesById.yaml
new file mode 100644
index 0000000..478a544
--- /dev/null
+++ b/openapi/methods/categoriesById.yaml
@@ -0,0 +1,36 @@
+get:
+ summary: Get a sensor category by ID
+ operationId: getSensorCategoryById
+ tags:
+ - Sensor Categories
+ parameters:
+ - name: categoryId
+ in: path
+ required: true
+ description: The ID of the sensor category to retrieve
+ schema:
+ type: integer
+ format: int64
+ responses:
+ '200':
+ description: The sensor category with the specified ID
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/categoryDto.yaml'
+delete:
+ summary: Delete a sensor category by ID
+ operationId: deleteSensorCategory
+ tags:
+ - Sensor Categories
+ parameters:
+ - name: categoryId
+ in: path
+ required: true
+ description: The ID of the sensor category to delete
+ schema:
+ type: integer
+ format: int64
+ responses:
+ '204':
+ description: No content, category deleted successfully
\ No newline at end of file
diff --git a/openapi/methods/sensorTypes.yaml b/openapi/methods/sensorTypes.yaml
new file mode 100644
index 0000000..91efe27
--- /dev/null
+++ b/openapi/methods/sensorTypes.yaml
@@ -0,0 +1,33 @@
+get:
+ summary: Get all sensor types
+ operationId: getSensorTypes
+ tags:
+ - Sensor Types
+ responses:
+ '200':
+ description: A list of sensor types
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '../schemas/typeDto.yaml'
+post:
+ summary: Create a new sensor type
+ operationId: postSensorType
+ tags:
+ - Sensor Types
+ requestBody:
+ description: The sensor type to create
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/typeDto.yaml'
+ responses:
+ '200':
+ description: The created sensor type
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/typeDto.yaml'
diff --git a/openapi/methods/sensorTypesById.yaml b/openapi/methods/sensorTypesById.yaml
new file mode 100644
index 0000000..914efb8
--- /dev/null
+++ b/openapi/methods/sensorTypesById.yaml
@@ -0,0 +1,43 @@
+get:
+ summary: Get a sensor type by ID
+ operationId: getSensorTypeById
+ tags:
+ - Sensor Types
+ parameters:
+ - $ref: '../parameters/id.yaml'
+ responses:
+ '200':
+ description: The sensor type with the specified ID
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/typeDto.yaml'
+put:
+ summary: Update a sensor type
+ operationId: putSensorType
+ tags:
+ - Sensor Types
+ requestBody:
+ description: The sensor type to update
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/typeDto.yaml'
+ responses:
+ '200':
+ description: The updated sensor type
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/typeDto.yaml'
+delete:
+ summary: Delete a sensor type by ID
+ operationId: deleteSensorType
+ tags:
+ - Sensor Types
+ parameters:
+ - $ref: '../parameters/sensorTypeId.yaml'
+ responses:
+ '204':
+ description: No content, sensor type deleted successfully
diff --git a/openapi/methods/sensors.yaml b/openapi/methods/sensors.yaml
new file mode 100644
index 0000000..2cfe6f4
--- /dev/null
+++ b/openapi/methods/sensors.yaml
@@ -0,0 +1,34 @@
+get:
+ summary: Get all sensors
+ operationId: getSensors
+ tags:
+ - Sensors
+ responses:
+ '200':
+ description: A list of sensors
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '../schemas/sensorDto.yaml'
+
+post:
+ summary: Create a new sensor
+ operationId: postSensor
+ tags:
+ - Sensors
+ requestBody:
+ description: The sensor to create
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/sensorDto.yaml'
+ responses:
+ '200':
+ description: The created sensor
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/sensorDto.yaml'
diff --git a/openapi/methods/sensorsById.yaml b/openapi/methods/sensorsById.yaml
new file mode 100644
index 0000000..e1a2e24
--- /dev/null
+++ b/openapi/methods/sensorsById.yaml
@@ -0,0 +1,43 @@
+get:
+ summary: Get a sensor by ID
+ operationId: getSensorById
+ tags:
+ - Sensors
+ parameters:
+ - $ref: '../parameters/sensorId.yaml'
+ responses:
+ '200':
+ description: The sensor with the specified ID
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/sensorDto.yaml'
+put:
+ summary: Update a sensor
+ operationId: putSensor
+ tags:
+ - Sensors
+ requestBody:
+ description: The sensor to update
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/sensorDto.yaml'
+ responses:
+ '200':
+ description: The updated sensor
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/sensorDto.yaml'
+delete:
+ summary: Delete a sensor by ID
+ operationId: deleteSensor
+ tags:
+ - Sensors
+ parameters:
+ - $ref: '../parameters/sensorId.yaml'
+ responses:
+ '204':
+ description: No content, sensor deleted successfully
diff --git a/openapi/methods/sensorsEntryById.yaml b/openapi/methods/sensorsEntryById.yaml
new file mode 100644
index 0000000..2409551
--- /dev/null
+++ b/openapi/methods/sensorsEntryById.yaml
@@ -0,0 +1,48 @@
+get:
+ summary: Get entries for a sensor
+ operationId: getEntries
+ tags:
+ - Sensor Entries
+ parameters:
+ - $ref: '../parameters/sensorId.yaml'
+ - $ref: '../parameters/date1.yaml'
+ - $ref: '../parameters/date2.yaml'
+ - $ref: '../parameters/limit.yaml'
+ responses:
+ '200':
+ description: A list of sensor entries
+ content:
+ application/json:
+ schema:
+ type: array
+ items:
+ $ref: '../schemas/entryDto.yaml'
+post:
+ summary: Create a new entry for a sensor
+ operationId: postEntry
+ tags:
+ - Sensor Entries
+ parameters:
+ - $ref: '../parameters/sensorId.yaml'
+ requestBody:
+ description: The entry to create
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../schemas/entryDto.yaml'
+ responses:
+ '200':
+ description: The entry was created successfully
+delete:
+ summary: Delete entries for a sensor
+ operationId: deleteEntry
+ tags:
+ - Sensor Entries
+ parameters:
+ - $ref: '../parameters/sensorId.yaml'
+ - $ref: '../parameters/date1.yaml'
+ - $ref: '../parameters/date2.yaml'
+ responses:
+ '204':
+ description: No content, entries deleted successfully
diff --git a/openapi/methods/sensorsGraph.yaml b/openapi/methods/sensorsGraph.yaml
new file mode 100644
index 0000000..9846409
--- /dev/null
+++ b/openapi/methods/sensorsGraph.yaml
@@ -0,0 +1,19 @@
+get:
+ summary: Get data for displaying a graph
+ operationId: getDisplayGraph
+ tags:
+ - Display
+ parameters:
+ - $ref: '../parameters/sensorId.yaml'
+ - $ref: '../parameters/date1.yaml'
+ - $ref: '../parameters/date2.yaml'
+ - $ref: '../parameters/interval.yaml'
+ responses:
+ '200':
+ description: Data for displaying a graph
+ content:
+ application/json:
+ schema:
+ type: object
+ additionalProperties:
+ type: any
diff --git a/openapi/openapi.yaml b/openapi/openapi.yaml
new file mode 100644
index 0000000..401ed69
--- /dev/null
+++ b/openapi/openapi.yaml
@@ -0,0 +1,24 @@
+openapi: 3.0.3
+info:
+ title: Title
+ description: Title
+ version: 1.0.0
+servers:
+ - url: 'http'
+paths:
+ /rest/v1/categories/:
+ $ref: './methods/categories.yaml'
+ /rest/v1/categories/{categoryId}:
+ $ref: './methods/categoriesById.yaml'
+ /rest/v1/sensors/{sensorId}:
+ $ref: './methods/sensorsEntryById.yaml'
+ /rest/v1/sensors:
+ $ref: './methods/sensors.yaml'
+ /rest/v1/sensors/{sensorId}/entry:
+ $ref: './methods/sensorsById.yaml'
+ /rest/v1/sensors/{sensorId}/graph:
+ $ref: './methods/sensorsGraph.yaml'
+ /rest/v1/types:
+ $ref: './methods/sensorTypes.yaml'
+ /rest/v1/types/{typeId}:
+ $ref: './methods/sensorTypesById.yaml'
\ No newline at end of file
diff --git a/openapi/parameters/date1.yaml b/openapi/parameters/date1.yaml
new file mode 100644
index 0000000..2d55264
--- /dev/null
+++ b/openapi/parameters/date1.yaml
@@ -0,0 +1,7 @@
+name: date1
+in: query
+required: false
+description: The start date (timestamp) for filtering entries
+schema:
+ type: integer
+ format: int64
diff --git a/openapi/parameters/date2.yaml b/openapi/parameters/date2.yaml
new file mode 100644
index 0000000..9b09001
--- /dev/null
+++ b/openapi/parameters/date2.yaml
@@ -0,0 +1,7 @@
+name: date2
+in: query
+required: false
+description: The end date (timestamp) for filtering entries
+schema:
+ type: integer
+ format: int64
diff --git a/openapi/parameters/id.yaml b/openapi/parameters/id.yaml
new file mode 100644
index 0000000..82519de
--- /dev/null
+++ b/openapi/parameters/id.yaml
@@ -0,0 +1,7 @@
+name: id
+in: path
+required: true
+description: The ID of the sensor type
+schema:
+ type: integer
+ format: int64
diff --git a/openapi/parameters/interval.yaml b/openapi/parameters/interval.yaml
new file mode 100644
index 0000000..05c08c3
--- /dev/null
+++ b/openapi/parameters/interval.yaml
@@ -0,0 +1,6 @@
+name: interval
+in: query
+required: true
+description: The interval for the graph data
+schema:
+ type: integer
diff --git a/openapi/parameters/limit.yaml b/openapi/parameters/limit.yaml
new file mode 100644
index 0000000..bd53f57
--- /dev/null
+++ b/openapi/parameters/limit.yaml
@@ -0,0 +1,6 @@
+name: limit
+in: query
+required: false
+description: The maximum number of entries to return
+schema:
+ type: integer
diff --git a/openapi/parameters/sensorId.yaml b/openapi/parameters/sensorId.yaml
new file mode 100644
index 0000000..a95fdef
--- /dev/null
+++ b/openapi/parameters/sensorId.yaml
@@ -0,0 +1,6 @@
+name: sensorId
+in: path
+required: true
+description: The ID of the sensor
+schema:
+ type: string
diff --git a/openapi/parameters/sensorTypeId.yaml b/openapi/parameters/sensorTypeId.yaml
new file mode 100644
index 0000000..69cd2b3
--- /dev/null
+++ b/openapi/parameters/sensorTypeId.yaml
@@ -0,0 +1,7 @@
+name: sensorTypeId
+in: path
+required: true
+description: The ID of the sensor type
+schema:
+ type: integer
+ format: int64
diff --git a/openapi/schemas/categoryDto.yaml b/openapi/schemas/categoryDto.yaml
new file mode 100644
index 0000000..49b46cd
--- /dev/null
+++ b/openapi/schemas/categoryDto.yaml
@@ -0,0 +1,12 @@
+type: object
+properties:
+ id:
+ type: integer
+ format: int64
+ description: The ID of the sensor category
+ name:
+ type: string
+ description: The name of the sensor category
+ description:
+ type: string
+ description: The description of the sensor category
\ No newline at end of file
diff --git a/openapi/schemas/entryDto.yaml b/openapi/schemas/entryDto.yaml
new file mode 100644
index 0000000..c64796d
--- /dev/null
+++ b/openapi/schemas/entryDto.yaml
@@ -0,0 +1,17 @@
+type: object
+properties:
+ id:
+ type: integer
+ format: int64
+ description: The ID of the entry
+ sensorId:
+ type: string
+ description: The ID of the sensor
+ timestamp:
+ type: string
+ format: date-time
+ description: The timestamp of the entry
+ value:
+ type: number
+ format: double
+ description: The value of the entry
diff --git a/openapi/schemas/sensorDto.yaml b/openapi/schemas/sensorDto.yaml
new file mode 100644
index 0000000..fc5bcb1
--- /dev/null
+++ b/openapi/schemas/sensorDto.yaml
@@ -0,0 +1,13 @@
+type: object
+properties:
+ sensorId:
+ type: string
+ description: The ID of the sensor
+ sensorType:
+ type: string
+ nullable: true
+ description: The type of the sensor
+ sensorNick:
+ type: string
+ nullable: true
+ description: The nickname of the sensor
\ No newline at end of file
diff --git a/openapi/schemas/typeDto.yaml b/openapi/schemas/typeDto.yaml
new file mode 100644
index 0000000..eefa6b9
--- /dev/null
+++ b/openapi/schemas/typeDto.yaml
@@ -0,0 +1,13 @@
+type: object
+properties:
+ id:
+ type: integer
+ format: int64
+ description: The ID of the sensor type
+ typeName:
+ type: string
+ description: The name of the sensor type
+ description:
+ type: string
+ description: A description of the sensor type
+ # Add other properties as needed
diff --git a/pom.xml b/pom.xml
index 787830c..33b3ec2 100644
--- a/pom.xml
+++ b/pom.xml
@@ -5,20 +5,21 @@
org.springframework.boot
spring-boot-starter-parent
- 2.6.3
+ 3.3.2
jar
- com.example
- SpringServer
- 1
- SpringServer
+ de.lrprojects
+ tempserver
+ 1.0.0-SNAPSHOT
+ TempServer
Sensor Webserver with Spring
17
17
17
-
+ 2.0.0
+
org.springframework.boot
@@ -29,41 +30,75 @@
spring-boot-starter-web
-
- org.springframework.boot
- spring-boot-devtools
- runtime
- true
-
-
org.springframework.boot
spring-boot-starter-test
test
-
- org.springframework.boot
- spring-boot-starter-data-jpa
-
-
- org.postgresql
- postgresql
-
-
- org.springframework.boot
- spring-boot-starter-jdbc
-
-
- com.h2database
- h2
-
-
- com.jcraft
- jsch
- 0.1.55
-
-
+
+ com.influxdb
+ influxdb-client-java
+ 7.1.0
+
+
+ org.jetbrains.kotlin
+ kotlin-stdlib-jdk8
+ ${kotlin.version}
+
+
+ org.jetbrains.kotlin
+ kotlin-test
+ ${kotlin.version}
+ test
+
+
+ org.springdoc
+ springdoc-openapi-starter-webmvc-ui
+ 2.6.0
+
+
+ org.springframework.boot
+ spring-boot-starter-thymeleaf
+ 3.3.1
+
+
+ org.thymeleaf
+ thymeleaf-spring5
+ 3.1.2.RELEASE
+
+
+ org.openapitools
+ jackson-databind-nullable
+ 0.2.6
+
+
+ com.fasterxml.jackson.module
+ jackson-module-kotlin
+ 2.17.2
+
+
+ org.jetbrains.kotlin
+ kotlin-jps-plugin
+ 1.9.24
+
+
+ org.jetbrains
+ annotations
+ 24.1.0
+ compile
+
+
+ org.springframework.boot
+ spring-boot-starter-data-jpa
+ 3.3.2
+
+
+ org.postgresql
+ postgresql
+ runtime
+
+
@@ -75,15 +110,80 @@
true
-
- org.apache.maven.plugins
- maven-compiler-plugin
-
-
- 14
-
-
-
+
+ org.jetbrains.kotlin
+ kotlin-maven-plugin
+ ${kotlin.version}
+
+
+ compile
+ compile
+
+ compile
+
+
+
+
+
+
+
+
+
+
+ test-compile
+ test-compile
+
+ test-compile
+
+
+
+
+ ${maven.compiler.target}
+
+
+
+ org.jetbrains.kotlin
+ kotlin-maven-allopen
+ ${kotlin.version}
+
+
+ org.jetbrains.kotlin
+ kotlin-maven-noarg
+ ${kotlin.version}
+
+
+
+
+ org.openapitools
+ openapi-generator-maven-plugin
+ 7.7.0
+
+
+
+ generate
+
+
+ true
+
+ ${project.basedir}/openapi/openapi.yaml
+
+ spring
+ ${groupId}.${artifactId}.api
+ ${groupId}.${artifactId}.model
+
+ ApiUtil.java
+
+
+ true
+ false
+ true
+ true
+
+
+
+
+
+
diff --git a/src/main/java/com/example/SpringServer/Controller/RestControllerCategories.java b/src/main/java/com/example/SpringServer/Controller/RestControllerCategories.java
deleted file mode 100644
index e36270f..0000000
--- a/src/main/java/com/example/SpringServer/Controller/RestControllerCategories.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package com.example.SpringServer.Controller;
-
-import com.example.SpringServer.Entities.Category;
-import com.example.SpringServer.Entities.JDBC;
-import com.example.SpringServer.repository.CategoryRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.context.event.ApplicationReadyEvent;
-import org.springframework.context.event.EventListener;
-import org.springframework.web.bind.annotation.*;
-
-import java.util.ArrayList;
-
-@RestController
-public class RestControllerCategories {
-
- @Autowired
- CategoryRepository categoryRepository;
-
- JDBC jdbc = new JDBC();
-
- //TODO add a default category?
- /*@EventListener(ApplicationReadyEvent.class)
- public void setupCategory() {
- if (categoryRepository.findByCategoryId(0L) == null) {
- Category defaultCategory = new Category();
- categoryRepository.save(defaultCategory);
- jdbc.updateCategory( 0L, defaultCategory.getId());
- }
- }*/
-
- //working
- @GetMapping(value = "/sensors/categories/")
- public ArrayList getSensorCategoryId () {
- return (ArrayList) categoryRepository.findAll();
- }
-
- @GetMapping(value = "/sensors/categories/{id}")
- public Category getSensorCategoryIdById (@PathVariable("id") Long id) {
- return categoryRepository.findByCategoryId(id);
- }
-
- //working
- @PutMapping("/sensors/categories/")
- public Category putSensor(@RequestBody Category category) {
- if (category.getId() == 0) {
- throw new IllegalArgumentException("Not allowed to alter default category");
- }
- return categoryRepository.save(categoryRepository.updateCategory(category));
- }
-
- //working
- @PostMapping("/sensors/categories/")
- public Category postSensor(@RequestBody Category category) {
- if (category.getId() == 0) {
- category.setId((long) -1);
- }
- return categoryRepository.save(category);
- }
-
- //working
- //TODO Cascading delete into Id table
- @DeleteMapping("/sensors/categories/{sensorCategoryId}")
- public void deleteSensor(@PathVariable("sensorCategoryId") Long sensorCategoryId) {
- categoryRepository.deleteCategory(sensorCategoryId);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/Controller/RestControllerEntries.java b/src/main/java/com/example/SpringServer/Controller/RestControllerEntries.java
deleted file mode 100644
index 211943e..0000000
--- a/src/main/java/com/example/SpringServer/Controller/RestControllerEntries.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.example.SpringServer.Controller;
-
-import com.example.SpringServer.Entities.Entry;
-import com.example.SpringServer.Entities.JDBC;
-import org.springframework.web.bind.annotation.*;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Map;
-
-@RestController
-public class RestControllerEntries {
- JDBC jdbc = new JDBC();
-
- //working with no params
- @GetMapping("/sensors/{sensorId}")
- public ArrayList getEntries(@PathVariable("sensorId") String sensorId, @RequestParam(required = false) Long date1, @RequestParam(required = false) Long date2, @RequestParam(required = false) Integer limit) {
- ArrayList rt;
- Timestamp time2 = (date2 == null ? null : new Timestamp(date2));
- Timestamp time1 = (date1 == null ? null : new Timestamp(date1));
- try {
- if (time1 == null && time2 == null) {
- rt = jdbc.selectAllEntries(sensorId);
- } else if (time1 != null && time2 != null) {
- rt = jdbc.selectEntriesBetween(sensorId, time1, time2);
- } else if (time1 != null) {
- rt = jdbc.selectEntriesDate1(sensorId, time1);
- } else {
- if (limit != null) {
- rt = jdbc.selectFirst(sensorId, time2, limit);
- } else {
- rt = jdbc.selectEntriesDate2(sensorId, time2);
- }
-
- }
- return rt;
- }catch (Exception e) {
- System.out.println(e);
- return new ArrayList<>();
- }
- }
-
- //working
- @PostMapping("sensors/post/{sensorId}/")
- public void postEntry(@PathVariable("sensorId") String sensorId, @RequestBody Entry entry) {
- jdbc.insertEntry(entry, sensorId);
- }
-
- //working with no params
- @DeleteMapping("sensors/delete/{sensorId}")
- public void deleteEntry (@PathVariable("sensorId") String sensorId, @RequestParam(required = false) Long date1, @RequestParam(required = false) Long date2) {
- Timestamp time2 = (date2 == null ? null : new Timestamp(date2));
- Timestamp time1 = (date1 == null ? null : new Timestamp(date1));
- if (date1 == null && date2 == null) {
- jdbc.deleteAllEntryTable(sensorId);
- } else if (date1 != null && date2 != null) {
- jdbc.deleteEntryBetweenTable(sensorId, time1, time2);
- } else if (date1 != null) {
- jdbc.deleteEntryDate1(sensorId, time1);
- } else {
- jdbc.deleteEntryDate2(sensorId, time2);
- }
- }
-
- @GetMapping("display/graph")
- public Map getDisplayGraph(@RequestParam String sensor_id, @RequestParam Long date1, @RequestParam Long date2, @RequestParam int interval) {
- Timestamp time2 = (date2 == null ? null : new Timestamp(date2));
- Timestamp time1 = (date1 == null ? null : new Timestamp(date1));
- return jdbc.getDisplayData(sensor_id, interval, time1, time2);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/Controller/RestControllerSensors.java b/src/main/java/com/example/SpringServer/Controller/RestControllerSensors.java
deleted file mode 100644
index 3a6d1d2..0000000
--- a/src/main/java/com/example/SpringServer/Controller/RestControllerSensors.java
+++ /dev/null
@@ -1,86 +0,0 @@
-package com.example.SpringServer.Controller;
-
-import com.example.SpringServer.Entities.Category;
-import com.example.SpringServer.Entities.Id;
-import com.example.SpringServer.Entities.JDBC;
-import com.example.SpringServer.repository.CategoryRepository;
-import com.example.SpringServer.repository.SensorRepository;
-import com.example.SpringServer.repository.TypeRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
-
-import java.util.*;
-
-
-@RestController
-public class RestControllerSensors {
-
- @Autowired
- SensorRepository sensorRepo;
-
- @Autowired
- CategoryRepository categoryRepository;
-
- @Autowired
- TypeRepository typeRepo;
-
- JDBC jdbc = new JDBC();
-
- //working
- @GetMapping("/sensors/id")
- public ArrayList getSensors() {
- return (ArrayList) sensorRepo.findAll();
- }
-
- //working
- @GetMapping(value = "/sensors/id/{sensorId}")
- public Id getSensorById (@PathVariable("sensorId") String sensorId) {
- return sensorRepo.findById(sensorId);
- }
-
- //working
- @GetMapping(value = "/sensors/id/{sensorId}/sensor_nick")
- public Map getSensorNickById (@PathVariable("sensorId") String sensorId) {
- Map map = new HashMap<>();
- map.put("sensor_nick", sensorRepo.findSensorNickById(sensorId));
- return map;
- }
-
- //working
- @GetMapping(value = "/sensors/id/{sensorId}/sensor_type")
- public Map getSensorTypeIdById (@PathVariable("sensorId") String sensorId) {
- Map map = new HashMap<>();
- map.put("sensor_type", sensorRepo.findSensorTypeById(sensorId));
- return map;
- }
-
- //working
- @PutMapping("/sensors/id/")
- public Id putSensor(@RequestBody Id sensor) {
- return sensorRepo.save(sensorRepo.updateSensor(sensor));
- }
-
- //working
- @PostMapping("/sensors/id/")
- public Id postSensor(@RequestBody Id sensor) {
- if (sensor.getSensorType() == null) {
- sensor.setSensorType(typeRepo.findByTypeId(0L));
- }
- //TODO add the default category on create
- /*
- if (sensor.getCategories().size() == 0) {
- sensor.addCategory(categoryRepository.findByCategoryId(0L));
- System.out.println(sensor.getCategories());
- }*/
- Id id = sensorRepo.save(sensor);
- jdbc.createEntryTable(sensor.getSensorId());
- return id;
- }
-
- //working
- @DeleteMapping("/sensors/id/{sensorId}")
- public void deleteSensor(@PathVariable("sensorId") String sensorId) {
- jdbc.dropTable(sensorId);
- sensorRepo.deleteSensor(sensorId);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/Controller/RestControllerTypes.java b/src/main/java/com/example/SpringServer/Controller/RestControllerTypes.java
deleted file mode 100644
index 8e5c559..0000000
--- a/src/main/java/com/example/SpringServer/Controller/RestControllerTypes.java
+++ /dev/null
@@ -1,68 +0,0 @@
-package com.example.SpringServer.Controller;
-
-import com.example.SpringServer.Entities.Id;
-import com.example.SpringServer.Entities.JDBC;
-import com.example.SpringServer.Entities.Type;
-import com.example.SpringServer.repository.TypeRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.context.event.ApplicationReadyEvent;
-import org.springframework.context.event.EventListener;
-import org.springframework.web.bind.annotation.*;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
-@RestController
-public class RestControllerTypes {
-
- @Autowired
- TypeRepository typeRepository;
-
- JDBC jdbc = new JDBC();
-
- @EventListener(ApplicationReadyEvent.class)
- public void setupType() {
- if (typeRepository.findByTypeId(0L) == null) {
- Type defaultType = new Type();
- typeRepository.save(defaultType);
- jdbc.updateType( 0L, defaultType.getId());
- }
- }
-
- //working
- @GetMapping(value = "/sensors/types/")
- public ArrayList getSensorTypeId () {
- return (ArrayList) typeRepository.findAll();
- }
-
- @GetMapping(value = "/sensors/types/{id}")
- public Type getSensorTypeIdById (@PathVariable("id") Long id) {
- return typeRepository.findByTypeId(id);
- }
-
- //working
- @PutMapping("/sensors/types/")
- public Type putSensor(@RequestBody Type type) {
- if (type.getId() == 0) {
- throw new IllegalArgumentException();
- }
- return typeRepository.save(typeRepository.updateType(type));
- }
-
- //working
- @PostMapping("/sensors/types/")
- public Type postSensor(@RequestBody Type type) {
- if (type.getId() == 0) {
- type.setId((long) -1);
- }
- return typeRepository.save(type);
- }
-
- //working
- //TODO Cascading delete into Id table
- @DeleteMapping("/sensors/types/{sensorTypeId}")
- public void deleteSensor(@PathVariable("sensorTypeId") Long sensorTypeId) {
- typeRepository.deleteType(sensorTypeId);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/Controller/ViewController.java b/src/main/java/com/example/SpringServer/Controller/ViewController.java
deleted file mode 100644
index 3071200..0000000
--- a/src/main/java/com/example/SpringServer/Controller/ViewController.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.example.SpringServer.Controller;
-
-import com.example.SpringServer.Entities.Category;
-import com.example.SpringServer.Entities.Id;
-import com.example.SpringServer.Entities.Type;
-import com.example.SpringServer.repository.CategoryRepository;
-import com.example.SpringServer.repository.SensorRepository;
-import com.example.SpringServer.repository.TypeRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Controller;
-import org.springframework.ui.Model;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RequestParam;
-
-import java.util.ArrayList;
-
-@Controller
-public class ViewController {
-
- @Autowired
- CategoryRepository categoryRepository;
-
- @Autowired
- SensorRepository sensorRepo;
-
- @Autowired
- TypeRepository typeRepo;
-
- @GetMapping("/")
- public String index (Model model) {
- ArrayList sensors = (ArrayList) sensorRepo.findAll();
- model.addAttribute("sensors",sensors);
- return "index";
- }
-
- @GetMapping("/display")
- public String display (@RequestParam String sensor_id, Model model) {
- ArrayList sensors = (ArrayList) sensorRepo.findAll();
- Id sensor = sensorRepo.findById(sensor_id);
- model.addAttribute("sensors",sensors);
- model.addAttribute("thisSensor", sensor);
- return "display";
- }
-
- @GetMapping("/config/local-sensors")
- public String configLocalSensors(Model model) {
- ArrayList sensors = (ArrayList) sensorRepo.findAll();
- model.addAttribute("sensors", sensors);
- return "config-local-sensors";
- }
-
- @GetMapping("/config/sensor-types")
- public String configSensorTypes(Model model) {
- ArrayList types = (ArrayList) typeRepo.findAll();
- ArrayList sensors = (ArrayList) sensorRepo.findAll();
- model.addAttribute("types", types);
- model.addAttribute("sensors", sensors);
- return "config-sensor-types";
- }
-
- @GetMapping("/config/sensor-categories")
- public String configSensorCategories(Model model) {
- ArrayList types = (ArrayList) categoryRepository.findAll();
- ArrayList sensors = (ArrayList) sensorRepo.findAll();
- model.addAttribute("categories", types);
- model.addAttribute("sensors", sensors);
- return "config-sensor-categories";
- }
-
-}
diff --git a/src/main/java/com/example/SpringServer/Entities/Category.java b/src/main/java/com/example/SpringServer/Entities/Category.java
deleted file mode 100644
index 2c22b49..0000000
--- a/src/main/java/com/example/SpringServer/Entities/Category.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package com.example.SpringServer.Entities;
-
-
-import javax.persistence.Id;
-import javax.persistence.*;
-import java.util.HashSet;
-import java.util.Set;
-
-@Entity
-public class Category {
- @JoinColumn(name = "category_id")
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
-
- @Column(name = "sensor_category", nullable = false)
- private String sensorCategory = "All Sensors";
-
- @ManyToMany(mappedBy="categories")
- private Set ids = new HashSet<>();
-
- public Long getId() {
- return id;
- }
-
- public String getSensorCategory() {return sensorCategory;}
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public void setSensorCategory(String sensorCategory) {
- this.sensorCategory = sensorCategory;
- }
-
- @Override
- public String toString() {
- return "id: "+ id + " name:" + sensorCategory;
- }
-
-}
diff --git a/src/main/java/com/example/SpringServer/Entities/Entry.java b/src/main/java/com/example/SpringServer/Entities/Entry.java
deleted file mode 100644
index 25a1c0f..0000000
--- a/src/main/java/com/example/SpringServer/Entities/Entry.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package com.example.SpringServer.Entities;
-
-import java.sql.Timestamp;
-
-public class Entry {
-
- public Entry(Long row_id, double entryValue, Timestamp date) {
- this.row_id = row_id;
- this.entryValue = entryValue;
- this.date = date;
- }
-
- private Long row_id;
- private double entryValue;
- private Timestamp date;
-
- public void setRow_id(Long row_id) {
- this.row_id = row_id;
- }
-
- public Long getRow_id() {
- return row_id;
- }
-
- public double getEntryValue() {
- return entryValue;
- }
-
- public void setEntryValue(double entryValue) {
- this.entryValue = entryValue;
- }
-
- public Timestamp getDate() {
- return date;
- }
-
- public void setDate(Timestamp date) {
- this.date = date;
- }
-
- @Override
- public String toString(){
- return entryValue + " unit";
- }
-}
diff --git a/src/main/java/com/example/SpringServer/Entities/Id.java b/src/main/java/com/example/SpringServer/Entities/Id.java
deleted file mode 100644
index 520a128..0000000
--- a/src/main/java/com/example/SpringServer/Entities/Id.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package com.example.SpringServer.Entities;
-import javax.persistence.*;
-import java.util.HashSet;
-import java.util.Set;
-
-@Entity
-public class Id {
-
- @Column(name = "sensor_id", unique = true)
- private String sensorId;
-
- @Column(name = "sensor_nick", nullable = false)
- private String sensorNick;
-
- @OneToOne
- @JoinColumn(name = "sensor_type_id")
- private Type sensorType;
-
- @ManyToMany
- @JoinTable(
- name = "Id_Category",
- joinColumns = { @JoinColumn(name = "id") },
- inverseJoinColumns = { @JoinColumn(name = "category_id") }
- )
- private Set categories = new HashSet<>();
-
- @javax.persistence.Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
-
- public void setSensorId(String sensorId) {
- this.sensorId = sensorId;
- }
-
- public String getSensorId() {
- return sensorId;
- }
-
- public String getSensorNick() {
- return sensorNick;
- }
-
- public void setSensorNick(String sensorNick) {
- this.sensorNick = sensorNick;
- }
-
- public Type getSensorType() {
- return sensorType;
- }
-
- public void setSensorType(Type sensorType) {
- this.sensorType = sensorType;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Set getCategories() {
- return categories;
- }
-
- public void setCategories(Set sensorCategory) {
- this.categories = sensorCategory;
- }
-
- public void addCategory(Category category) {
- this.categories.add(category);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/Entities/JDBC.java b/src/main/java/com/example/SpringServer/Entities/JDBC.java
deleted file mode 100644
index bbd9fe4..0000000
--- a/src/main/java/com/example/SpringServer/Entities/JDBC.java
+++ /dev/null
@@ -1,233 +0,0 @@
-package com.example.SpringServer.Entities;
-
-import com.example.SpringServer.repository.TypeRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.context.event.ApplicationReadyEvent;
-import org.springframework.context.annotation.Lazy;
-import org.springframework.context.event.EventListener;
-
-import java.sql.*;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-
-public class JDBC {
-
- private final SQL SQL_STRINGS = new SQL();
- private Connection conn;
-
- @Autowired
- @Lazy
- TypeRepository typeRepository;
-
- public JDBC() {
-
- try {
- Properties p = new Properties();
- p.load(getClass().getResourceAsStream("/application.properties"));
-
- Class.forName("org.postgresql.Driver");
-
- Properties props = new Properties();
- props.put("user", System.getenv("DB_USER"));
- props.put("password", System.getenv("DB_PASSWORD"));
-
- conn = DriverManager.getConnection(System.getenv("DATASOURCE_URL") , props);
- } catch (Exception e) {
- System.out.println(e);
- }
- }
-
- private ArrayList selectEntries(Object[] params, String sql) throws SQLException {
- PreparedStatement stmt = conn.prepareStatement(this.setTableName(sql, (String) params[0]));
- this.prepareStatement(stmt, params);
- ResultSet rs = stmt.executeQuery();
- ArrayList entries = new ArrayList<>();
- while (rs.next()) {
- Entry entry = new Entry(rs.getLong("row_id"), rs.getDouble("value"), rs.getTimestamp("date"));
- entries.add(entry);
- }
- rs.close();
- stmt.close();
- return entries;
- }
-
-
-
- public ArrayList selectAllEntries(String sensor) throws SQLException {
- ArrayList entries = selectEntries(new Object[] {"backup_" + sensor}, SQL_STRINGS.selectAllEntry());
- entries.addAll(selectEntries(new Object[] {"s" + sensor}, SQL_STRINGS.selectAllEntry()));
- return entries;
- }
-
- public ArrayList selectEntriesBetween(String sensor, Timestamp date1, Timestamp date2) throws SQLException {
- ArrayList entries = selectEntries(new Object[] {"backup_" + sensor, date1, date2}, SQL_STRINGS.selectEntryBetween());
- entries.addAll(selectEntries(new Object[] {"s" + sensor, date1, date2}, SQL_STRINGS.selectEntryBetween()));
- return entries;
- }
-
- public ArrayList selectEntriesDate1(String sensor, Timestamp date1) throws SQLException {
- ArrayList entries = selectEntries(new Object[] {"backup_" + sensor, date1}, SQL_STRINGS.selectEntryDate1());
- entries.addAll(selectEntries(new Object[] {"s" + sensor, date1}, SQL_STRINGS.selectEntryDate1()));
- return entries;
- }
-
- public ArrayList selectEntriesDate2(String sensor, Timestamp date2) throws SQLException {
- ArrayList entries = selectEntries(new Object[] {"backup_" + sensor, date2}, SQL_STRINGS.selectEntryDate2());
- entries.addAll(selectEntries(new Object[] {"s" + sensor, date2}, SQL_STRINGS.selectEntryDate2()));
- return entries;
- }
-
- public ArrayList selectFirst(String sensor, Timestamp date2, Integer limit) throws SQLException {
- return selectEntries(new Object[] {"s" + sensor, date2}, SQL_STRINGS.selectFirst(limit));
- }
-
- public void insertEntry(Entry entry, String sensor) {
- if (entry.getDate() == null) {
- java.util.Date utilDate = new java.util.Date();
- entry.setDate(new Timestamp(utilDate.getTime()));
- }
- try {
- this.update(SQL_STRINGS.insertEntry(), new Object[]{"s" + sensor, entry.getDate(), entry.getEntryValue()});
- } catch(SQLException e) {
- System.out.println(e);
- }
- }
-
- public void insertEntryBatch(ArrayList entries, String sensor) {
- try {
- PreparedStatement stmt = conn.prepareStatement(this.setTableName(SQL_STRINGS.insertEntry(), "backup_" + sensor));
- for (Entry entry : entries) {
- this.prepareStatement(stmt, new Object[]{"backup_" + sensor, entry.getDate(), entry.getEntryValue()});
- stmt.addBatch();
- stmt.clearParameters();
- }
- stmt.executeBatch();
- stmt.close();
- } catch (SQLException e) {
- System.out.println(e);
- }
- }
-
- public void createEntryTable(String sensor) {
- try {
- this.update(SQL_STRINGS.createEntryTable(), new Object[]{"s" + sensor});
- this.update(SQL_STRINGS.createEntryTable(), new Object[]{"backup_" + sensor});
- } catch(SQLException e) {
- System.out.println(e);
- }
- }
-
- public void deleteAllEntryTable(String sensor) {
- try {
- this.update(SQL_STRINGS.deleteAllEntry(), new Object[] {"s" + sensor});
- this.update(SQL_STRINGS.deleteAllEntry(), new Object[] {"backup_" + sensor});
- } catch(SQLException ignored) {}
- }
-
- public void deleteEntryBetweenTable(String sensor, Timestamp date1, Timestamp date2) {
- try {
- this.update(SQL_STRINGS.deleteEntryBetween(), new Object[] {"s" + sensor, date1, date2});
- this.update(SQL_STRINGS.deleteEntryBetween(), new Object[] {"backup_" + sensor, date1, date2});
- } catch(SQLException ignored) {}
- }
-
- public void deleteEntryDate1(String sensor, Timestamp date1) {
- try {
- this.update(SQL_STRINGS.deleteEntryDate1(), new Object[] {"s" + sensor, date1});
- this.update(SQL_STRINGS.deleteEntryDate1(), new Object[] {"backup_" + sensor, date1});
- } catch(SQLException e) {
- System.out.println(e);
- }
- }
-
- public void deleteEntryDate2(String sensor, Timestamp date2) {
- try {
- this.update(SQL_STRINGS.deleteEntryDate2(), new Object[] {"s" + sensor, date2});
- this.update(SQL_STRINGS.deleteEntryDate2(), new Object[] {"backup_" + sensor, date2});
- } catch(SQLException ignored) {}
- }
-
- public void dropTable(String sensor) {
- try {
- this.update(SQL_STRINGS.deleteEntryTable(), new Object[] {"s" + sensor});
- this.update(SQL_STRINGS.deleteEntryTable(), new Object[] {"backup_" + sensor});
- } catch(SQLException e) {
- System.out.println(e);
- }
- }
- private void prepareStatement(PreparedStatement stmt, Object[] objs) throws SQLException {
- int count = 0;
- for (Object obj : objs) {
- if (count > 0) {
- if (obj instanceof String) {
- stmt.setString(count, (String) obj);
- } else if (obj instanceof Integer) {
- stmt.setInt(count, (Integer) obj);
- } else if (obj instanceof Double) {
- stmt.setDouble(count, (Double) obj);
- }else if (obj instanceof Long) {
- stmt.setLong(count, (Long) obj);
- } else if (obj instanceof java.sql.Timestamp) {
- stmt.setTimestamp(count, (java.sql.Timestamp) obj);
- }
- }
- count++;
- }
- }
-
- public void updateType(Long idOld, Long idNew) {
- try {
- this.update(SQL_STRINGS.updateById(), new Object[] {"type", idOld, idNew});
- }catch (SQLException e) {
- System.out.println(e.toString());
- }
- }
-
- public void updateCategory(Long idOld, Long idNew) {
- try {
- this.update(SQL_STRINGS.updateById(), new Object[] {"category", idOld, idNew});
- }catch (SQLException e) {
- System.out.println(e.toString());
- }
- }
-
- private void update(String sqlQuery, Object[] objs) throws SQLException {
- PreparedStatement stmt = conn.prepareStatement(this.setTableName(sqlQuery, (String) objs[0]));
- this.prepareStatement(stmt, objs);
- stmt.executeUpdate();
- stmt.close();
- }
-
- public Map getDisplayData(String sensor, int interval, Timestamp date1, Timestamp date2) {
- try {
- return formatForGraph(selectEntries(new Object[] {"s" + sensor,interval, interval, interval, interval, date1, date2}, SQL_STRINGS.selectDisplay()));
- } catch (SQLException e) {
- System.out.println(e);
- return new HashMap<>();
- }
- }
-
- private Map formatForGraph(ArrayList entries) {
- double[] values = new double[entries.size()];
- Timestamp[] dates = new Timestamp[entries.size()];
- for (int i = 0; i < entries.size(); i++) {
- values[i] = entries.get(i).getEntryValue();
- dates[i] = entries.get(i).getDate();
- }
- Map map = new HashMap<>();
- map.put("values", values);
- map.put("dates", dates);
- return map;
- }
-
- private void close() throws SQLException {
- conn.close();
- }
-
- private String setTableName(String sql, String tableName) {
- return sql.replace("$", tableName);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/Entities/SQL.java b/src/main/java/com/example/SpringServer/Entities/SQL.java
deleted file mode 100644
index 9e307bc..0000000
--- a/src/main/java/com/example/SpringServer/Entities/SQL.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package com.example.SpringServer.Entities;
-
-public class SQL {
-
- public String updateById() {return "UPDATE $ SET id=? WHERE id=?";}
-
- public String selectEntryBetween() {
- return "SELECT * FROM $ WHERE date <= ? AND date >= ? ORDER BY row_id DESC";
- }
-
- public String selectAllEntry() {
- return "SELECT * FROM $ ORDER BY row_id DESC";
- }
-
- public String selectEntryDate1() {
- return "SELECT * FROM $ WHERE date <= ? ORDER BY row_id DESC";
- }
-
- public String selectFirst(int limit) {return "SELECT * FROM $ WHERE date >= ? ORDER BY row_id DESC FETCH NEXT " + limit + " ROW ONLY";}
-
- public String selectEntryDate2() {
- return "SELECT * FROM $ WHERE date >= ? ORDER BY row_id DESC";
- }
-
- public String insertEntry() {
- return "INSERT INTO $ (row_id, date, value) VALUES (DEFAULT, ?,?)";
- }
-
- public String deleteEntryBetween() {
- return "DELETE FROM $ WHERE date <= ? AND date >= ?";
- }
-
- public String deleteAllEntry() {
- return "DELETE FROM $";
- }
-
- public String deleteEntryDate1() {
- return "DELETE FROM $ WHERE date <= ?";
- }
-
- public String deleteEntryDate2() {
- return "DELETE FROM $ WHERE date >= ?";
- }
-
- public String createEntryTable() {
- return "CREATE TABLE $ (row_id SERIAL PRIMARY KEY, date TIMESTAMPTZ, value NUMERIC(10,2))";
- }
-
- public String deleteEntryTable() {
- return "DROP TABLE $";
- }
-
- public String selectDisplay() {
- return "WITH a AS (select date, row_id, AVG(value) over (partition by " +
- "(round(extract(epoch from date) / ? ) * ?) " +
- "order by row_id rows between unbounded preceding and current row " +
- ") as value, row_number() over ( " +
- "partition by " +
- "(round(extract(epoch from date) / ?) * ?) " +
- "order by row_id desc " +
- "rows between unbounded preceding and current row) as row " +
- "from $ where date <= ? and date >= ?) " +
- "select date, row_id, value from a where row = 1 order by row_id";
- }
-}
diff --git a/src/main/java/com/example/SpringServer/Entities/Type.java b/src/main/java/com/example/SpringServer/Entities/Type.java
deleted file mode 100644
index 4f2c428..0000000
--- a/src/main/java/com/example/SpringServer/Entities/Type.java
+++ /dev/null
@@ -1,70 +0,0 @@
-package com.example.SpringServer.Entities;
-
-
-import javax.persistence.*;
-import javax.persistence.Id;
-
-@Entity
-public class Type {
- @JoinColumn(name = "type_id")
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
-
- @Column(name = "sensor_type", nullable = false)
- private String sensorType = "default";
-
- @Column(name = "unit", nullable = false)
- private String unit = "dUnit";
-
- @Column(name = "repetitions", nullable=false)
- private int repetitions = 10;
-
- @Column(name = "sleep_time", nullable = false)
- private int sleepTime = 10;
-
- public Long getId() {
- return id;
- }
-
- public String getUnit() {
- return unit;
- }
-
- public String getSensorType() {return sensorType;}
-
- public int getSleepTime() {
- return sleepTime;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public int getRepetitions() {
- return repetitions;
- }
-
- public void setSensorType(String sensorType) {
- this.sensorType = sensorType;
- }
-
- public void setUnit(String unit) {
- this.unit = unit;
- }
-
- @Column
- public void setRepetitions(int repetitions) {
- this.repetitions = repetitions;
- }
-
- public void setSleepTime (int sleepTime) {
- this.sleepTime = sleepTime;
- }
-
- @Override
- public String toString() {
- return "id: "+ id + " name:" + sensorType + " repetitions: " + repetitions + " unit: " + unit + " sleepTime: " +sleepTime;
- }
-
-}
diff --git a/src/main/java/com/example/SpringServer/Schedular/DailyExecution.java b/src/main/java/com/example/SpringServer/Schedular/DailyExecution.java
deleted file mode 100644
index b26ea19..0000000
--- a/src/main/java/com/example/SpringServer/Schedular/DailyExecution.java
+++ /dev/null
@@ -1,37 +0,0 @@
-package com.example.SpringServer.Schedular;
-import com.example.SpringServer.Entities.Entry;
-import com.example.SpringServer.Entities.Id;
-import com.example.SpringServer.Entities.JDBC;
-import com.example.SpringServer.repository.SensorRepository;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.scheduling.annotation.EnableScheduling;
-import org.springframework.scheduling.annotation.Scheduled;
-import org.springframework.stereotype.Component;
-
-import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.util.ArrayList;
-import java.util.Date;
-
-@Component
-@EnableScheduling
-public class DailyExecution {
-
- JDBC jdbc = new JDBC();
- private final static int DAYS = 7;
-
- @Autowired
- SensorRepository sensorRepo;
-
- @Scheduled(cron="0 0 0 * * *")
- public void moveToBackup() throws SQLException {
- ArrayList sensors = (ArrayList) sensorRepo.findAll();
- for (Id sensor : sensors) {
- ArrayList entries = jdbc.selectEntriesDate1(sensor.getSensorId(), new Timestamp(new Date().getTime() - (long)DAYS*1000*60*60*24));
- System.out.println(entries.size());
- jdbc.insertEntryBatch(entries, sensor.getSensorId());
- jdbc.deleteEntryDate1(sensor.getSensorId(), new Timestamp(new Date().getTime() - (long)DAYS*1000*60*60*24));
- }
- }
-
-}
\ No newline at end of file
diff --git a/src/main/java/com/example/SpringServer/SpringServerApplication.java b/src/main/java/com/example/SpringServer/SpringServerApplication.java
deleted file mode 100644
index 874049d..0000000
--- a/src/main/java/com/example/SpringServer/SpringServerApplication.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.example.SpringServer;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-
-@SpringBootApplication
-public class SpringServerApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SpringServerApplication.class, args);
- }
-
-}
diff --git a/src/main/java/com/example/SpringServer/repository/CategoryRepository.java b/src/main/java/com/example/SpringServer/repository/CategoryRepository.java
deleted file mode 100644
index 5bc8ece..0000000
--- a/src/main/java/com/example/SpringServer/repository/CategoryRepository.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.example.SpringServer.repository;
-
-import com.example.SpringServer.Entities.Category;
-import org.springframework.data.repository.CrudRepository;
-import org.springframework.stereotype.Repository;
-
-import javax.transaction.Transactional;
-
-@Repository
-@Transactional
-public interface CategoryRepository extends CrudRepository, CategoryRepositoryCustom {}
\ No newline at end of file
diff --git a/src/main/java/com/example/SpringServer/repository/CategoryRepositoryCustom.java b/src/main/java/com/example/SpringServer/repository/CategoryRepositoryCustom.java
deleted file mode 100644
index b1f013f..0000000
--- a/src/main/java/com/example/SpringServer/repository/CategoryRepositoryCustom.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.example.SpringServer.repository;
-
-import com.example.SpringServer.Entities.Category;
-
-public interface CategoryRepositoryCustom {
- public Category findByCategoryId(Long id);
- public Category updateCategory(Category category);
- public void deleteCategory(Long sensorCategory);
-}
diff --git a/src/main/java/com/example/SpringServer/repository/CategoryRepositoryImpl.java b/src/main/java/com/example/SpringServer/repository/CategoryRepositoryImpl.java
deleted file mode 100644
index 3e91b01..0000000
--- a/src/main/java/com/example/SpringServer/repository/CategoryRepositoryImpl.java
+++ /dev/null
@@ -1,46 +0,0 @@
-package com.example.SpringServer.repository;
-
-import com.example.SpringServer.Entities.Category;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Lazy;
-
-import java.util.ArrayList;
-import java.util.Objects;
-
-public class CategoryRepositoryImpl implements CategoryRepositoryCustom {
-
- @Autowired
- @Lazy
- CategoryRepository categoryRepository;
-
- @Override
- public Category findByCategoryId(Long id) {
- ArrayList list = (ArrayList) categoryRepository.findAll();
- for (Category category : list) {
- if (Objects.equals(category.getId(), id)) {
- return category;
- }
- }
- return null;
- }
-
- @Override
- public Category updateCategory(Category category) {
- if (category.getId() != 0) {
- Category t = this.findByCategoryId(category.getId());
- t.setSensorCategory(category.getSensorCategory());
- return t;
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- @Override
- public void deleteCategory(Long sensorCategoryId) {
- if (sensorCategoryId != 0) {
- categoryRepository.delete(this.findByCategoryId(sensorCategoryId));
- } else {
- throw new IllegalArgumentException();
- }
- }
-}
diff --git a/src/main/java/com/example/SpringServer/repository/SensorRepository.java b/src/main/java/com/example/SpringServer/repository/SensorRepository.java
deleted file mode 100644
index 8f0e380..0000000
--- a/src/main/java/com/example/SpringServer/repository/SensorRepository.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.example.SpringServer.repository;
-
-import com.example.SpringServer.Entities.Id;
-import org.springframework.data.repository.CrudRepository;
-import org.springframework.stereotype.Repository;
-
-@Repository
-public interface SensorRepository extends CrudRepository, SensorRepositoryCustom {}
-
diff --git a/src/main/java/com/example/SpringServer/repository/SensorRepositoryCustom.java b/src/main/java/com/example/SpringServer/repository/SensorRepositoryCustom.java
deleted file mode 100644
index 6266008..0000000
--- a/src/main/java/com/example/SpringServer/repository/SensorRepositoryCustom.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package com.example.SpringServer.repository;
-
-import com.example.SpringServer.Entities.Category;
-import com.example.SpringServer.Entities.Id;
-
-import java.util.ArrayList;
-import java.util.Set;
-
-public interface SensorRepositoryCustom {
- public Id findById(String sensorId);
- public String findSensorNickById(String sensorId);
- public String findSensorTypeById(String sensorId);
- public Set findSensorCategoriesById(String sensorId);
- public Id updateSensor(Id sensor);
- public void deleteSensor(String sensorId);
-}
diff --git a/src/main/java/com/example/SpringServer/repository/SensorRepositoryImpl.java b/src/main/java/com/example/SpringServer/repository/SensorRepositoryImpl.java
deleted file mode 100644
index 913b41f..0000000
--- a/src/main/java/com/example/SpringServer/repository/SensorRepositoryImpl.java
+++ /dev/null
@@ -1,60 +0,0 @@
-package com.example.SpringServer.repository;
-
-import com.example.SpringServer.Entities.Category;
-import com.example.SpringServer.Entities.Id;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Lazy;
-
-import javax.transaction.Transactional;
-import java.util.ArrayList;
-import java.util.Set;
-
-public class SensorRepositoryImpl implements SensorRepositoryCustom {
- @Autowired
- @Lazy
- SensorRepository sensorRepository;
-
- @Override
- public Id findById(String sensorId) {
- ArrayList list = (ArrayList) sensorRepository.findAll();
- for (Id id : list) {
- if (id.getSensorId().equals(sensorId)) {
- return id;
- }
- }
- return null;
- }
-
- @Override
- public String findSensorNickById(String sensorId) {
- Id id = this.findById(sensorId);
- return id == null ? null : id.getSensorNick();
- }
-
- @Override
- public String findSensorTypeById(String sensorId) {
- Id id = this.findById(sensorId);
- return id == null ? null : id.getSensorType().getSensorType();
- }
-
- @Override
- public Set findSensorCategoriesById(String sensorId) {
- Id id = this.findById(sensorId);
- return id == null ? null : id.getCategories();
- }
-
- @Override
- @Transactional
- public Id updateSensor(Id sensor) {
- Id id = this.findById(sensor.getSensorId());
- id.setSensorNick(sensor.getSensorNick());
- id.setSensorType(sensor.getSensorType());
- id.setCategories(sensor.getCategories());
- return id;
- }
-
- @Override
- public void deleteSensor(String sensorId) {
- sensorRepository.delete(this.findById(sensorId));
- }
-}
diff --git a/src/main/java/com/example/SpringServer/repository/TypeRepository.java b/src/main/java/com/example/SpringServer/repository/TypeRepository.java
deleted file mode 100644
index 7f1a705..0000000
--- a/src/main/java/com/example/SpringServer/repository/TypeRepository.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.example.SpringServer.repository;
-
-import com.example.SpringServer.Entities.Type;
-import org.springframework.data.repository.CrudRepository;
-import org.springframework.stereotype.Repository;
-
-import javax.transaction.Transactional;
-
-@Repository
-@Transactional
-public interface TypeRepository extends CrudRepository, TypeRepositoryCustom {}
\ No newline at end of file
diff --git a/src/main/java/com/example/SpringServer/repository/TypeRepositoryCustom.java b/src/main/java/com/example/SpringServer/repository/TypeRepositoryCustom.java
deleted file mode 100644
index a2f122b..0000000
--- a/src/main/java/com/example/SpringServer/repository/TypeRepositoryCustom.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.example.SpringServer.repository;
-
-import com.example.SpringServer.Entities.Id;
-import com.example.SpringServer.Entities.Type;
-
-public interface TypeRepositoryCustom {
- public Type findByTypeId(Long id);
- public Type updateType(Type type);
- public void deleteType(Long sensorType);
-}
diff --git a/src/main/java/com/example/SpringServer/repository/TypeRepositoryImpl.java b/src/main/java/com/example/SpringServer/repository/TypeRepositoryImpl.java
deleted file mode 100644
index cdff308..0000000
--- a/src/main/java/com/example/SpringServer/repository/TypeRepositoryImpl.java
+++ /dev/null
@@ -1,49 +0,0 @@
-package com.example.SpringServer.repository;
-
-import com.example.SpringServer.Entities.Type;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Lazy;
-
-import java.util.ArrayList;
-import java.util.Objects;
-
-public class TypeRepositoryImpl implements TypeRepositoryCustom {
-
- @Autowired
- @Lazy
- TypeRepository typeRepository;
-
- @Override
- public Type findByTypeId(Long id) {
- ArrayList list = (ArrayList) typeRepository.findAll();
- for (Type type : list) {
- if (Objects.equals(type.getId(), id)) {
- return type;
- }
- }
- return null;
- }
-
- @Override
- public Type updateType(Type type) {
- if (type.getId() != 0) {
- Type t = this.findByTypeId(type.getId());
- t.setUnit(type.getUnit());
- t.setRepetitions(type.getRepetitions());
- t.setSleepTime(type.getSleepTime());
- t.setSensorType(type.getSensorType());
- return t;
- } else {
- throw new IllegalArgumentException();
- }
- }
-
- @Override
- public void deleteType(Long sensorTypeId) {
- if (sensorTypeId != 0) {
- typeRepository.delete(this.findByTypeId(sensorTypeId));
- } else {
- throw new IllegalArgumentException();
- }
- }
-}
diff --git a/src/main/java/com/example/SpringServer/ssh/SshConfiguration.java b/src/main/java/com/example/SpringServer/ssh/SshConfiguration.java
deleted file mode 100644
index 3acf746..0000000
--- a/src/main/java/com/example/SpringServer/ssh/SshConfiguration.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package com.example.SpringServer.ssh;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-
-import com.example.SpringServer.updateDatabase.main.ChangeManager;
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.Session;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.context.event.ApplicationReadyEvent;
-import org.springframework.boot.web.servlet.ServletContextInitializer;
-import org.springframework.context.event.EventListener;
-import org.springframework.core.io.ResourceLoader;
-import org.springframework.stereotype.Component;
-
-import java.io.*;
-import java.util.Properties;
-
-@Component
-public class SshConfiguration implements ServletContextInitializer {
-
- ChangeManager manager;
-
- public SshConfiguration() {
- try {
- if(System.getenv("SSH_ENABLED")!=null){
- JSch jsch = new JSch();
- File file = getKeyFile();
- jsch.addIdentity(file.getAbsolutePath());
- Session session = jsch.getSession(System.getenv("SSH_F_USER"),System.getenv("SSH_F_IP"),Integer.parseInt(System.getenv("SSH_F_PORT")));
- session.setConfig("StrictHostKeyChecking", "no");
- session.connect();
- session.setPortForwardingL(System.getenv("SSH_FROM_IP"),Integer.parseInt(System.getenv("SSH_FROM_PORT")) ,System.getenv("SSH_TO_HOST") ,Integer.parseInt(System.getenv("SSH_TO_PORT")) );
- System.out.println("SSH connection successful");
- }
- manager = new ChangeManager();
-
- } catch (Exception e) {
- System.out.println("ssh settings is failed. skip!" + e);
- }
- }
- @Override
- public void onStartup(ServletContext servletContext) throws ServletException {
- }
-
- private File getKeyFile() throws FileNotFoundException {
- File file = new File("privateKey");
- String key = System.getenv("SSH_F_KEY").substring(31);
- key = key.substring(0, key.length() - 29).replaceAll(" ", "\n");
- key = "-----BEGIN RSA PRIVATE KEY-----" + key + "-----END RSA PRIVATE KEY-----";
- PrintWriter out = new PrintWriter(file.getAbsolutePath());
- out.println(key);
- out.close();
- file.deleteOnExit();
- return file;
- }
-
- @EventListener(ApplicationReadyEvent.class)
- public void pushManager(){
- manager.runPush();
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/JDBC/Column.java b/src/main/java/com/example/SpringServer/updateDatabase/JDBC/Column.java
deleted file mode 100644
index faf43e5..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/JDBC/Column.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package com.example.SpringServer.updateDatabase.JDBC;
-
-public class Column {
-
- private String columnName;
- private int type;
- private Object defaultValue;
-
- public Column (String columnName, int type, Object defaultValue) {
- this.columnName = columnName;
- this.type = type;
- this.defaultValue = defaultValue;
- }
-
- public int getType() {
- return type;
- }
- public String getColumnName() {
- return columnName;
- }
- public Object getDefaultValue() {
- return defaultValue;
- }
- public void setColumnName(String columnName) {
- this.columnName = columnName;
- }
-
- public void setType(int type) {
- this.type = type;
- }
-
- public void setDefaultValue(Object defaultValue) {
- this.defaultValue = defaultValue;
- }
-
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/JDBC/Entity.java b/src/main/java/com/example/SpringServer/updateDatabase/JDBC/Entity.java
deleted file mode 100644
index 54b5872..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/JDBC/Entity.java
+++ /dev/null
@@ -1,55 +0,0 @@
-package com.example.SpringServer.updateDatabase.JDBC;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.stream.Collectors;
-
-public class Entity {
-
- protected String tableName;
- protected List columns = new ArrayList<>();
- protected List rows = new ArrayList<>();
-
-
- public Entity(String name, List columns) {
- this.tableName = name;
- this.columns.addAll(columns);
- }
-
- public String getTableName() {
- return tableName;
- }
-
- public void setRows(List rows) {
- this.rows = rows;
- }
-
- public List getColumns() {
- return columns;
- }
-
- public List getRows() {
- return rows;
- }
-
- public Column findColumnByName(String name){
- List c = columns.stream().filter(e -> e.getColumnName().equals(name)).collect(Collectors.toList());
- if (c.size() == 1) {
- return c.get(0);
- } else {
- return null;
- }
- }
-
- public void setTableName(String tableName) {
- this.tableName = tableName;
- }
-
- public void addColumn(Column column) {
- if (findColumnByName(column.getColumnName()) == null) {
- columns.add(column);
- rows.forEach(e -> e.getData().put(column, column.getDefaultValue()));
- }
- }
-
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/JDBC/JDBC.java b/src/main/java/com/example/SpringServer/updateDatabase/JDBC/JDBC.java
deleted file mode 100644
index ba3e6c4..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/JDBC/JDBC.java
+++ /dev/null
@@ -1,212 +0,0 @@
-package com.example.SpringServer.updateDatabase.JDBC;
-
-import java.sql.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-public class JDBC {
-
- private static final String UPDATE_SQL = "INSERT INTO $ (*) VALUES (#)";
- private static final String SELECT_SQL = "SELECT * FROM $";
- private static final String DROP_TABLE_SQL = "DROP TABLE $ CASCADE";
- private static final String DELETE_SQL = "DELETE FROM $";
- private Connection conn;
- public JDBC() {
-
- try {
- Class.forName("org.postgresql.Driver");
- Properties props = new Properties();
- props.put("user", System.getenv("DB_USER"));
- props.put("password", System.getenv("DB_PASSWORD"));
-
- conn = DriverManager.getConnection(System.getenv("DATASOURCE_URL") , props);
- } catch (Exception e) {
- System.out.println(e);
- }
- }
-
- public void insertData(Entity entity) {
- try {
- PreparedStatement stmt = conn.prepareStatement(this.createInsertStatement(UPDATE_SQL, entity));
- entity.getRows().forEach(e -> addToBatch(stmt, e, entity.getColumns()));
- stmt.executeBatch();
- stmt.close();
- } catch (SQLException e) {
- System.out.println(e);
- }
- }
-
- private void addToBatch(PreparedStatement stmt, Row row, List columns) {
- try {
- this.prepareStatement(stmt, row, columns);
- stmt.addBatch();
- stmt.clearParameters();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- private void prepareStatement(PreparedStatement stmt, Row row, List columns) {
- int[] idx = { 1 };
- columns.forEach(e -> {
- try {
- this.prepare(stmt, row.getData().get(e), idx[0]++, e);
- } catch (SQLException ex) {
- ex.printStackTrace();
- }
- });
- }
-
- private void prepare(PreparedStatement stmt, Object obj, int count, Column column) throws SQLException {
- switch (column.getType()) {
- case Types.VARCHAR -> stmt.setString(count, castString(obj,column.getDefaultValue()));
- case Types.INTEGER -> stmt.setInt(count, castInt(obj, column.getDefaultValue()));
- case Types.DOUBLE -> stmt.setDouble(count, castDouble(obj, column.getDefaultValue()));
- case Types.BIGINT -> stmt.setLong(count, castLong(obj, column.getDefaultValue()));
- case Types.TIMESTAMP_WITH_TIMEZONE -> stmt.setTimestamp(count, (Timestamp) obj);
- }
- }
-
- private String castString(Object obj, Object defaultValue) {
- if (obj != null) {
- return obj.toString();
- } else {
- return defaultValue.toString();
- }
- }
-
- private Integer castInt(Object obj, Object defaultValue) {
- if (obj instanceof Integer) {
- return (Integer) obj;
- } else if (obj instanceof Double) {
- return ((Double) obj).intValue();
- } else if (obj instanceof Long) {
- return ((Long) obj).intValue();
- } else if (obj instanceof String) {
- return Integer.parseInt((String) obj);
- } else {
- return (Integer) defaultValue;
- }
- }
-
- private Double castDouble(Object obj, Object defaultValue) {
- if (obj instanceof Integer) {
- return ((Integer) obj).doubleValue();
- } else if (obj instanceof Double) {
- return (Double) obj;
- } else if (obj instanceof Long) {
- return ((Long) obj).doubleValue();
- } else if (obj instanceof String) {
- return Double.parseDouble((String) obj);
- } else {
- return (Double) defaultValue;
- }
- }
-
- private Long castLong(Object obj, Object defaultValue) {
- if (obj instanceof Integer) {
- return ((Integer) obj).longValue();
- } else if (obj instanceof Double) {
- return ((Double) obj).longValue();
- } else if (obj instanceof Long) {
- return (Long) obj;
- } else if (obj instanceof String) {
- return Long.parseLong((String) obj);
- } else {
- return (Long) defaultValue;
- }
- }
-
- private void update(String sqlQuery, Row row, String tableName, List columns) throws SQLException {
- PreparedStatement stmt = conn.prepareStatement(this.setTableName(sqlQuery, tableName));
- this.prepareStatement(stmt, row, columns);
- stmt.executeUpdate();
- stmt.close();
- }
-
- public void dropTable(String tableName) {
- try {
- update(DROP_TABLE_SQL, new Row(), tableName, new ArrayList<>());
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- public void deleteContent(String tableName) {
- try {
- update(DELETE_SQL, new Row(), tableName, new ArrayList<>());
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- public List select(Entity entity) throws SQLException {
- PreparedStatement stmt = conn.prepareStatement(this.setTableName(SELECT_SQL, entity.getTableName()));
- ResultSet rs = stmt.executeQuery();
- List rows = new ArrayList<>();
- int columnCount = rs.getMetaData().getColumnCount();
- while (rs.next()) {
- Row row = new Row();
- for (int i = 1; i <= columnCount; i++) {
- try {
- Column column = entity.findColumnByName(rs.getMetaData().getColumnName(i));
- addColumn(column, row, rs, i);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- entity.getColumns().stream()
- .filter(e -> !row.getData().containsKey(e))
- .forEach(e -> row.addColumn(e, e.getDefaultValue()));
- rows.add(row);
- System.out.println(entity.getTableName());
- System.out.println(row);
- }
- rs.close();
- stmt.close();
- return rows;
- }
-
- private void addColumn(Column column, Row row, ResultSet rs, int i) throws SQLException {
- int type = rs.getMetaData().getColumnType(i);
- switch (type) {
- case Types.VARCHAR -> row.addColumn(column, rs.getString(i));
- case Types.BIGINT -> row.addColumn(column, rs.getLong(i));
- case Types.DOUBLE -> row.addColumn(column, rs.getDouble(i));
- case Types.INTEGER -> row.addColumn(column, rs.getInt(i));
- }
- }
-
-
-
- private void close() throws SQLException {
- conn.close();
- }
-
- private String createInsertStatement(String sql, Entity entity) {
- String returnString = setTableName(sql, entity.getTableName());
- returnString = setColumnNames(returnString, entity.getColumns());
- returnString = replaceValues(returnString, entity.getColumns().size());
- return returnString;
- }
-
- private String replaceValues(String sql, int num) {
- StringBuilder string = new StringBuilder();
- for (int i = 0; i < num; i++) {
- string.append("?").append((i + 1 == num) ? "" : ",");
- }
- return sql.replace("#",string.toString());
- }
- private String setColumnNames(String sql, List columns) {
- StringBuilder string = new StringBuilder();
- columns.forEach(e -> string.append(e.getColumnName()).append(","));
- string.deleteCharAt(string.length() - 1);
- String s = string.toString();
- return sql.replace("*", s);
- }
-
- private String setTableName(String sql, String tableName) {
- return sql.replace("$", tableName);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/JDBC/Row.java b/src/main/java/com/example/SpringServer/updateDatabase/JDBC/Row.java
deleted file mode 100644
index 33c0a24..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/JDBC/Row.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.example.SpringServer.updateDatabase.JDBC;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class Row {
- Map data = new HashMap<>();
-
- public Map getData() {
- return data;
- }
-
- public void setData(Map data) {
- this.data = data;
- }
-
- public void addColumn(Column name, Object data) {
- this.data.put(name, data);
- }
-
- @Override
- public String toString() {
- StringBuilder result = new StringBuilder();
- result.append("[");
- data.keySet().forEach(d -> System.out.println(d));
- data.keySet().forEach(d -> result.append(d.getColumnName()).append(": ").append(data.get(d)).append(", "));
- result.deleteCharAt(result.length() - 1);
- result.deleteCharAt(result.length() - 1);
- result.append("]");
-
- return result.toString();
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/main/ChangeManager.java b/src/main/java/com/example/SpringServer/updateDatabase/main/ChangeManager.java
deleted file mode 100644
index 2557a70..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/main/ChangeManager.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package com.example.SpringServer.updateDatabase.main;
-
-import org.springframework.boot.context.event.ApplicationReadyEvent;
-import org.springframework.boot.web.servlet.ServletContextInitializer;
-import org.springframework.context.event.EventListener;
-import org.springframework.stereotype.Component;
-import com.example.SpringServer.updateDatabase.JDBC.Column;
-import com.example.SpringServer.updateDatabase.JDBC.Entity;
-import com.example.SpringServer.updateDatabase.versionTranslation.ChangeArtefacts.ChangeCreateColumn;
-import com.example.SpringServer.updateDatabase.versionTranslation.ChangeArtefacts.ChangeCreateEntity;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeInterface;
-
-import javax.servlet.ServletContext;
-import javax.servlet.ServletException;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.List;
-
-
-public class ChangeManager {
-
- private static final int startVersion = 1;
- private static final int endVersion = 2;
- private final List> changeHistory = new ArrayList<>();
- Version version = new Version();
-
- public ChangeManager() {
- if (System.getenv("update") != null && Boolean.parseBoolean(System.getenv("update"))) {
- addVersionChanges();
- this.runPull();
- }
- }
-
- private void addVersionChanges() {
- changeHistory.add(version1());
- changeHistory.add(version2());
- }
-
- private List version1() {
- List changes = new ArrayList<>();
- List columns = new ArrayList<>();
- //type
- columns.add(new Column( "id", Types.BIGINT, 0L));
- columns.add(new Column( "sensor_type", Types.VARCHAR, "Default"));
- columns.add(new Column( "unit", Types.VARCHAR, "dUnit"));
- columns.add(new Column( "repetitions", Types.INTEGER, 10));
- columns.add(new Column( "sleep_time", Types.INTEGER, 10));
- changes.add(new ChangeCreateEntity(new Entity("type", columns), version));
- //id
- columns.clear();
- columns.add(new Column( "id", Types.BIGINT, -1L));
- columns.add(new Column( "sensor_nick", Types.VARCHAR, "newSensor"));
- columns.add(new Column( "sensor_type_id", Types.BIGINT, 0L));
- columns.add(new Column( "sensor_id", Types.VARCHAR, null));
- changes.add(new ChangeCreateEntity(new Entity("id", columns), version));
- return changes;
- }
-
- private List version2() {
- List changes = new ArrayList<>();
- List columns = new ArrayList<>();
- //category
- columns.add(new Column( "id", Types.BIGINT, -1L));
- columns.add(new Column( "sensor_category", Types.VARCHAR, null));
- changes.add(new ChangeCreateEntity(new Entity("category", columns), version));
- //id_category
- columns.clear();
- columns.add(new Column( "id", Types.BIGINT, null));
- columns.add(new Column( "category_id", Types.BIGINT, null));
- changes.add(new ChangeCreateEntity(new Entity("id_category", columns), version));
- return changes;
- }
-
- private void runFromToVersion(int start, int end) {
- for (int i = start; i < end; i++) {
- changeHistory.get(i).forEach(ChangeInterface::runChange);
- }
- }
-
- public void runPull() {
- System.out.println("[Selecting data]");
- runFromToVersion(0, startVersion);
- version.initPull();
- System.out.println("[Delete tables]");
- version.initDelete();
- }
-
-
- public void runPush() {
- if (System.getenv("update") != null && Boolean.parseBoolean(System.getenv("update"))) {
- System.out.println("[Inserting data]");
- runFromToVersion(startVersion, endVersion);
- version.initPush();
- }
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/main/Version.java b/src/main/java/com/example/SpringServer/updateDatabase/main/Version.java
deleted file mode 100644
index 60fe34a..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/main/Version.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package com.example.SpringServer.updateDatabase.main;
-
-
-import com.example.SpringServer.updateDatabase.JDBC.Column;
-import com.example.SpringServer.updateDatabase.JDBC.Entity;
-import com.example.SpringServer.updateDatabase.JDBC.JDBC;
-import com.example.SpringServer.updateDatabase.JDBC.Row;
-
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-public class Version {
- protected List versionEntities = new ArrayList<>();
- protected JDBC jdbc = new JDBC();
-
- public void initPull() {
- versionEntities.forEach(this::addData);
- }
-
- public void initDelete() {
- versionEntities.forEach(e -> jdbc.dropTable(e.getTableName()));
- }
-
- public void initPush() {
- jdbc.deleteContent("type"); //TODO händisch
- versionEntities.forEach(e -> jdbc.insertData(e));
- }
-
- public void addEntity(Entity entity) {
- versionEntities.add(entity);
- }
-
- private void addData(Entity entity) {
- try {
- List rows = jdbc.select(entity);
- entity.setRows(rows);
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
-
- private Entity getEntityByName(String name) {
- List entities = versionEntities.stream().filter(e -> e.getTableName().equals(name)).collect(Collectors.toList());
- if (entities.size() != 1) {
- return null;
- } else {
- return entities.get(0);
- }
- }
-
- private Column getColumnByName(String entityName, String columnName) {
- Entity e = getEntityByName(entityName);
- if (e != null) {
- return e.findColumnByName(columnName);
- } else {
- return null;
- }
- }
-
- //change methods
- public void changeEntityName(String oldName, String newName) {
- Entity e = getEntityByName(oldName);
- if (e != null) {
- e.setTableName(newName);
- }
- }
- public void changeColumnName(String entityName, String oldName, String newName) {
- Column c = getColumnByName(entityName, oldName);
- if (c != null) {
- c.setColumnName(newName);
- }
- }
- public void changeColumnType(String entityName, String columnName, int newType) {
- Column c = getColumnByName(entityName, columnName);
- if (c != null) {
- c.setType(newType);
- }
- }
- public void changeColumnDefault(String entityName, String columnName, Object newDefault) {
- Column c = getColumnByName(entityName, columnName);
- if (c != null) {
- c.setDefaultValue(newDefault);
- }
- }
- public void changeAddColumn(String entityName, Column column) {
- Entity e = getEntityByName(entityName);
- if (e != null) {
- e.addColumn(column);
- }
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeColumnDefault.java b/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeColumnDefault.java
deleted file mode 100644
index 86db271..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeColumnDefault.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.example.SpringServer.updateDatabase.versionTranslation.ChangeArtefacts;
-
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeAbstract;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeInterface;
-import com.example.SpringServer.updateDatabase.main.Version;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeType;
-
-public class ChangeColumnDefault extends ChangeAbstract implements ChangeInterface {
- private final String columnName;
- private final Object newDefault;
- private final String entityName;
-
- public ChangeColumnDefault(String columnName, Object newDefault, Version version, String entityName) {
- super(ChangeType.COLUMN_DEFAULT, version);
- this.columnName = columnName;
- this.newDefault = newDefault;
- this.entityName = entityName;
- }
-
- @Override
- public void runChange() {
- version.changeColumnDefault(entityName,columnName, newDefault);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeColumnName.java b/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeColumnName.java
deleted file mode 100644
index 0341809..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeColumnName.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.example.SpringServer.updateDatabase.versionTranslation.ChangeArtefacts;
-
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeAbstract;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeInterface;
-import com.example.SpringServer.updateDatabase.main.Version;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeType;
-
-public class ChangeColumnName extends ChangeAbstract implements ChangeInterface {
- private final String oldName;
- private final String newName;
- private final String entity;
-
- public ChangeColumnName(String oldName, String newName, String entity, Version version) {
- super(ChangeType.COLUMN_NAME, version);
- this.oldName = oldName;
- this.newName = newName;
- this.entity = entity;
- }
-
- @Override
- public void runChange() {
- version.changeColumnName(entity,oldName, newName);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeColumnType.java b/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeColumnType.java
deleted file mode 100644
index 7d74151..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeColumnType.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.example.SpringServer.updateDatabase.versionTranslation.ChangeArtefacts;
-
-
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeAbstract;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeInterface;
-import com.example.SpringServer.updateDatabase.main.Version;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeType;
-
-public class ChangeColumnType extends ChangeAbstract implements ChangeInterface {
- private final String columnName;
- private final int newType;
- private final String entity;
-
- public ChangeColumnType(String columnName, int newType, String entity, Version version) {
- super(ChangeType.COLUMN_NAME, version);
- this.columnName = columnName;
- this.newType = newType;
- this.entity = entity;
- }
-
- @Override
- public void runChange() {
- version.changeColumnType(entity,columnName, newType);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeCreateColumn.java b/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeCreateColumn.java
deleted file mode 100644
index 7480716..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeCreateColumn.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package com.example.SpringServer.updateDatabase.versionTranslation.ChangeArtefacts;
-
-
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeAbstract;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeInterface;
-import com.example.SpringServer.updateDatabase.JDBC.Column;
-import com.example.SpringServer.updateDatabase.main.Version;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeType;
-
-public class ChangeCreateColumn extends ChangeAbstract implements ChangeInterface {
- private final Column column;
- private final String entity;
-
- public ChangeCreateColumn(Column column, String entity, Version version) {
- super(ChangeType.CREATE_COLUMN, version);
- this.column = column;
- this.entity = entity;
- }
-
- @Override
- public void runChange() {
- version.changeAddColumn(entity, column);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeCreateEntity.java b/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeCreateEntity.java
deleted file mode 100644
index d8ef0cc..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeCreateEntity.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.example.SpringServer.updateDatabase.versionTranslation.ChangeArtefacts;
-
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeAbstract;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeInterface;
-import com.example.SpringServer.updateDatabase.JDBC.Entity;
-import com.example.SpringServer.updateDatabase.main.Version;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeType;
-
-public class ChangeCreateEntity extends ChangeAbstract implements ChangeInterface {
- private final Entity entity;
-
- public ChangeCreateEntity(Entity entity, Version version) {
- super(ChangeType.ENTITY_NAME, version);
- this.entity = entity;
- }
-
- @Override
- public void runChange() {
- version.addEntity(entity);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeEntityName.java b/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeEntityName.java
deleted file mode 100644
index 93d55cb..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/ChangeArtefacts/ChangeEntityName.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package com.example.SpringServer.updateDatabase.versionTranslation.ChangeArtefacts;
-
-
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeAbstract;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeInterface;
-import com.example.SpringServer.updateDatabase.main.Version;
-import com.example.SpringServer.updateDatabase.versionTranslation.changeBasics.ChangeType;
-
-public class ChangeEntityName extends ChangeAbstract implements ChangeInterface {
- private final String newName;
- private final String entity;
-
- public ChangeEntityName(String newName, String entity, Version version) {
- super(ChangeType.ENTITY_NAME, version);
- this.newName = newName;
- this.entity = entity;
- }
-
- @Override
- public void runChange() {
- version.changeEntityName(entity, newName);
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/changeBasics/ChangeAbstract.java b/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/changeBasics/ChangeAbstract.java
deleted file mode 100644
index c1d9e41..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/changeBasics/ChangeAbstract.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.example.SpringServer.updateDatabase.versionTranslation.changeBasics;
-
-import com.example.SpringServer.updateDatabase.main.Version;
-
-public abstract class ChangeAbstract {
- protected final ChangeType changeType;
- protected final Version version;
-
- protected ChangeAbstract(ChangeType changeType, Version version) {
- this.changeType = changeType;
- this.version = version;
- }
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/changeBasics/ChangeInterface.java b/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/changeBasics/ChangeInterface.java
deleted file mode 100644
index 9cad4bd..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/changeBasics/ChangeInterface.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.example.SpringServer.updateDatabase.versionTranslation.changeBasics;
-
-public interface ChangeInterface {
- public void runChange();
-}
diff --git a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/changeBasics/ChangeType.java b/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/changeBasics/ChangeType.java
deleted file mode 100644
index acdc707..0000000
--- a/src/main/java/com/example/SpringServer/updateDatabase/versionTranslation/changeBasics/ChangeType.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package com.example.SpringServer.updateDatabase.versionTranslation.changeBasics;
-
-public enum ChangeType {
- CREATE_COLUMN(0), COLUMN_TYPE(1), COLUMN_NAME(2), COLUMN_DEFAULT(3), ENTITY_NAME(4);
-
- ChangeType(int i) {}
-}
diff --git a/src/main/kotlin/de/lrprojects/tempserver/Schedular/DailyExecution.kt b/src/main/kotlin/de/lrprojects/tempserver/Schedular/DailyExecution.kt
new file mode 100644
index 0000000..4736d6b
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/Schedular/DailyExecution.kt
@@ -0,0 +1,30 @@
+package de.lrprojects.tempserver.Schedular
+
+import de.lrprojects.tempserver.service.api.EntryService
+import de.lrprojects.tempserver.service.api.SensorService
+import org.springframework.scheduling.annotation.EnableScheduling
+import org.springframework.scheduling.annotation.Scheduled
+import org.springframework.stereotype.Component
+import java.sql.SQLException
+
+@Component
+@EnableScheduling
+class DailyExecution(
+ private val sensorService: SensorService,
+ private val entryService: EntryService
+) {
+
+ @Scheduled(cron = "0 0 0 * * *")
+ @Throws(SQLException::class)
+ fun moveToBackup() {
+ val sensors = sensorService.getAllSensors()
+ val date = System.currentTimeMillis() - DAYS * 24 * 60 * 60 * 1000
+ for (sensor in sensors) {
+ entryService.deleteEntries(sensor.id!!, date, null)
+ }
+ }
+
+ companion object {
+ private const val DAYS = 7
+ }
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/SpringServerApplication.kt b/src/main/kotlin/de/lrprojects/tempserver/SpringServerApplication.kt
new file mode 100644
index 0000000..fa9eb04
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/SpringServerApplication.kt
@@ -0,0 +1,10 @@
+package de.lrprojects.tempserver
+
+import org.springframework.boot.autoconfigure.SpringBootApplication
+import org.springframework.boot.runApplication
+
+@SpringBootApplication
+class TempServerApplication
+fun main(args: Array) {
+ runApplication(args = args)
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/config/InfluxDbConfiguration.kt b/src/main/kotlin/de/lrprojects/tempserver/config/InfluxDbConfiguration.kt
new file mode 100644
index 0000000..c816870
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/config/InfluxDbConfiguration.kt
@@ -0,0 +1,24 @@
+package de.lrprojects.tempserver.config
+
+import com.influxdb.client.InfluxDBClient
+import com.influxdb.client.InfluxDBClientFactory
+import org.springframework.context.annotation.Bean
+import org.springframework.context.annotation.Configuration
+
+@Configuration
+class InfluxDbConfiguration(private val influxProperties: InfluxProperties) {
+
+ @Bean
+ fun influxDBClient(): InfluxDBClient? {
+ return if (influxProperties.enabled) {
+ InfluxDBClientFactory.create(
+ influxProperties.url,
+ influxProperties.token.toCharArray(),
+ influxProperties.org,
+ influxProperties.bucket
+ )
+ } else {
+ null
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/config/InfluxProperties.kt b/src/main/kotlin/de/lrprojects/tempserver/config/InfluxProperties.kt
new file mode 100644
index 0000000..7ed65bf
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/config/InfluxProperties.kt
@@ -0,0 +1,15 @@
+package de.lrprojects.tempserver.config
+
+import org.springframework.boot.context.properties.ConfigurationProperties
+import org.springframework.context.annotation.Configuration
+
+@Configuration
+@ConfigurationProperties(prefix = "influxdb")
+class InfluxProperties {
+
+ lateinit var url: String
+ lateinit var token: String
+ lateinit var bucket: String
+ lateinit var org: String
+ var enabled: Boolean = false
+}
diff --git a/src/main/kotlin/de/lrprojects/tempserver/controller/CategoryDelegate.kt b/src/main/kotlin/de/lrprojects/tempserver/controller/CategoryDelegate.kt
new file mode 100644
index 0000000..e8d91c2
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/controller/CategoryDelegate.kt
@@ -0,0 +1,38 @@
+package de.lrprojects.tempserver.controller
+
+import de.lrprojects.tempserver.api.SensorCategoriesApiDelegate
+import de.lrprojects.tempserver.converter.toDto
+import de.lrprojects.tempserver.converter.toEntity
+import de.lrprojects.tempserver.model.CategoryDto
+import de.lrprojects.tempserver.service.api.CategoryService
+import org.springframework.http.HttpStatus
+import org.springframework.http.ResponseEntity
+import org.springframework.stereotype.Component
+
+@Component
+class CategoryDelegate(
+ private val categoryService: CategoryService
+): SensorCategoriesApiDelegate {
+
+ override fun getAllSensorCategories(): ResponseEntity> {
+ return ResponseEntity.ok(categoryService.getAllCategories().map { it.toDto() }.toMutableList())
+ }
+
+ override fun createSensorCategory(categoryDto: CategoryDto): ResponseEntity {
+ return ResponseEntity(categoryService.createCategory(categoryDto.toEntity()).toDto(), HttpStatus.CREATED)
+ }
+
+ override fun deleteSensorCategory(categoryId: Long): ResponseEntity {
+ categoryService.deleteCategory(categoryId)
+ return ResponseEntity.ok().build()
+ }
+
+ override fun getSensorCategoryById(categoryId: Long): ResponseEntity {
+ return ResponseEntity.ok(categoryService.getCategoryById(categoryId)?.toDto())
+ }
+
+ override fun updateSensorCategory(categoryDto: CategoryDto): ResponseEntity {
+ return ResponseEntity.ok(categoryService.updateCategory(categoryDto.toEntity()).toDto())
+ }
+
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/controller/EntryDelegate.kt b/src/main/kotlin/de/lrprojects/tempserver/controller/EntryDelegate.kt
new file mode 100644
index 0000000..e692478
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/controller/EntryDelegate.kt
@@ -0,0 +1,36 @@
+package de.lrprojects.tempserver.controller
+
+import de.lrprojects.tempserver.api.SensorEntriesApiDelegate
+import de.lrprojects.tempserver.converter.toDto
+import de.lrprojects.tempserver.converter.toEntity
+import de.lrprojects.tempserver.model.EntryDto
+import de.lrprojects.tempserver.service.api.EntryService
+import org.springframework.http.HttpStatus
+import org.springframework.http.ResponseEntity
+import org.springframework.stereotype.Component
+
+@Component
+class EntryDelegate(
+ private val entryService: EntryService
+): SensorEntriesApiDelegate {
+
+ override fun deleteEntry(sensorId: String, date1: Long?, date2: Long?): ResponseEntity {
+ entryService.deleteEntries(sensorId, date1, date2)
+ return ResponseEntity.ok().build()
+ }
+
+ override fun getEntries(
+ sensorId: String,
+ date1: Long?,
+ date2: Long?,
+ limit: Int?
+ ): ResponseEntity> {
+ return ResponseEntity.ok(entryService.getEntries(sensorId, date1, date2, limit).map { it.toDto() }.toMutableList())
+ }
+
+ override fun postEntry(sensorId: String, entryDto: EntryDto): ResponseEntity {
+ entryService.createEntry(sensorId, entryDto.toEntity())
+ return ResponseEntity(HttpStatus.CREATED)
+ }
+}
+
diff --git a/src/main/kotlin/de/lrprojects/tempserver/controller/SensorDelegate.kt b/src/main/kotlin/de/lrprojects/tempserver/controller/SensorDelegate.kt
new file mode 100644
index 0000000..71352dc
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/controller/SensorDelegate.kt
@@ -0,0 +1,39 @@
+package de.lrprojects.tempserver.controller
+
+import de.lrprojects.tempserver.api.SensorsApiDelegate
+import de.lrprojects.tempserver.converter.toDto
+import de.lrprojects.tempserver.converter.toEntity
+import de.lrprojects.tempserver.model.SensorDto
+import de.lrprojects.tempserver.service.api.SensorService
+import de.lrprojects.tempserver.service.api.TypeService
+import org.springframework.http.HttpStatus
+import org.springframework.http.ResponseEntity
+import org.springframework.stereotype.Component
+
+@Component
+class SensorDelegate(
+ private val sensorService: SensorService,
+ private val typeService: TypeService
+): SensorsApiDelegate {
+
+ override fun getSensors(): ResponseEntity> {
+ return ResponseEntity.ok(sensorService.getAllSensors().map { it.toDto() }.toMutableList())
+ }
+
+ override fun deleteSensor(sensorId: String): ResponseEntity {
+ sensorService.deleteSensor(sensorId)
+ return ResponseEntity.ok().build()
+ }
+
+ override fun getSensorById(sensorId: String): ResponseEntity {
+ return ResponseEntity.ok(sensorService.getSensorById(sensorId)?.toDto())
+ }
+
+ override fun postSensor(sensorDto: SensorDto): ResponseEntity {
+ return ResponseEntity(sensorService.createSensor(sensorDto.toEntity(typeService)).toDto(), HttpStatus.CREATED)
+ }
+
+ override fun putSensor(sensorDto: SensorDto): ResponseEntity {
+ return ResponseEntity.ok(sensorService.updateSensor(sensorDto.toEntity(typeService)).toDto())
+ }
+}
diff --git a/src/main/kotlin/de/lrprojects/tempserver/controller/TypeDelegate.kt b/src/main/kotlin/de/lrprojects/tempserver/controller/TypeDelegate.kt
new file mode 100644
index 0000000..6b9c677
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/controller/TypeDelegate.kt
@@ -0,0 +1,36 @@
+package de.lrprojects.tempserver.controller
+
+import de.lrprojects.tempserver.api.SensorTypesApiDelegate
+import de.lrprojects.tempserver.converter.toDto
+import de.lrprojects.tempserver.model.TypeDto
+import de.lrprojects.tempserver.service.api.TypeService
+import org.springframework.http.HttpStatus
+import org.springframework.http.ResponseEntity
+import org.springframework.stereotype.Component
+
+@Component
+class TypeDelegate(
+ private val typeService: TypeService
+): SensorTypesApiDelegate {
+
+ override fun getSensorTypes(): ResponseEntity> {
+ return ResponseEntity.ok(typeService.getAllTypes().map { it.toDto() }.toMutableList())
+ }
+
+ override fun getSensorTypeById(id: Long): ResponseEntity {
+ return ResponseEntity.ok(typeService.getTypeById(id)!!.toDto())
+ }
+
+ override fun deleteSensorType(sensorTypeId: Long?): ResponseEntity {
+ typeService.deleteType(sensorTypeId!!)
+ return ResponseEntity(HttpStatus.OK)
+ }
+
+ override fun postSensorType(typeDto: TypeDto): ResponseEntity {
+ return ResponseEntity(typeService.createType(typeDto).toDto(), HttpStatus.CREATED)
+ }
+
+ override fun putSensorType(typeDto: TypeDto?): ResponseEntity {
+ return ResponseEntity(typeService.updateType(typeDto!!).toDto(), HttpStatus.OK)
+ }
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/controller/ViewController.kt b/src/main/kotlin/de/lrprojects/tempserver/controller/ViewController.kt
new file mode 100644
index 0000000..0c5d507
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/controller/ViewController.kt
@@ -0,0 +1,66 @@
+package de.lrprojects.tempserver.controller
+
+import de.lrprojects.tempserver.service.api.CategoryService
+import de.lrprojects.tempserver.service.api.SensorService
+import de.lrprojects.tempserver.service.api.TypeService
+import org.springframework.stereotype.Controller
+import org.springframework.ui.Model
+import org.springframework.web.bind.annotation.GetMapping
+import org.springframework.web.bind.annotation.RequestParam
+
+@Controller
+class ViewController(
+ private val sensorService: SensorService,
+ private val typeService: TypeService,
+ private val categoryService: CategoryService
+) {
+
+ @GetMapping(BASE)
+ fun index(model: Model): String {
+ val sensors = sensorService.getAllSensors()
+ model.addAttribute("sensors", sensors)
+ return "index"
+ }
+
+ @GetMapping(DISPLAY)
+ fun display(@RequestParam sensor_id: String, model: Model): String {
+ val sensors = sensorService.getAllSensors()
+ val sensor = sensorService.getSensorById(sensor_id)
+ model.addAttribute("sensors", sensors)
+ model.addAttribute("thisSensor", sensor)
+ return "display"
+ }
+
+ @GetMapping(CONFIG_LOCAL_SENSORS)
+ fun configLocalSensors(model: Model): String {
+ val sensors = sensorService.getAllSensors()
+ model.addAttribute("sensors", sensors)
+ return "config-local-sensors"
+ }
+
+ @GetMapping(CONFIG_SENSOR_TYPES)
+ fun configSensorTypes(model: Model): String {
+ val types = typeService.getAllTypes()
+ val sensors = sensorService.getAllSensors()
+ model.addAttribute("types", types)
+ model.addAttribute("sensors", sensors)
+ return "config-sensor-types"
+ }
+
+ @GetMapping(CONFIG_SENSOR_CATEGORIES)
+ fun configSensorCategories(model: Model): String {
+ val categories = categoryService.getAllCategories()
+ val sensors = sensorService.getAllSensors()
+ model.addAttribute("categories", categories)
+ model.addAttribute("sensors", sensors)
+ return "config-sensor-categories"
+ }
+
+ companion object {
+ const val BASE = "/"
+ const val DISPLAY = "/display"
+ const val CONFIG_LOCAL_SENSORS = "/config/local-sensors"
+ const val CONFIG_SENSOR_TYPES = "/config/sensor-types"
+ const val CONFIG_SENSOR_CATEGORIES = "/config/sensor-categories"
+ }
+}
diff --git a/src/main/kotlin/de/lrprojects/tempserver/converter/CategoryConverter.kt b/src/main/kotlin/de/lrprojects/tempserver/converter/CategoryConverter.kt
new file mode 100644
index 0000000..ad77cdb
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/converter/CategoryConverter.kt
@@ -0,0 +1,15 @@
+package de.lrprojects.tempserver.converter
+
+import de.lrprojects.tempserver.entity.Category
+import de.lrprojects.tempserver.model.CategoryDto
+
+fun Category.toDto() = CategoryDto().also {
+ it.id = this.id
+ it.name = this.name
+ it.description = this.description
+}
+
+fun CategoryDto.toEntity() = Category(this.id).also {
+ it.name = this.name
+ it.description = this.description
+}
diff --git a/src/main/kotlin/de/lrprojects/tempserver/converter/EntryConverter.kt b/src/main/kotlin/de/lrprojects/tempserver/converter/EntryConverter.kt
new file mode 100644
index 0000000..50f8662
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/converter/EntryConverter.kt
@@ -0,0 +1,19 @@
+package de.lrprojects.tempserver.converter
+
+import de.lrprojects.tempserver.entity.Entry
+import de.lrprojects.tempserver.model.EntryDto
+import java.sql.Timestamp
+import java.time.OffsetDateTime
+import java.time.ZoneOffset
+
+fun Entry.toDto() = EntryDto().also {
+ it.sensorId = this.sensorId
+ it.value = this.value
+ it.timestamp = OffsetDateTime.of(this.timestamp!!.toLocalDateTime(), ZoneOffset.UTC)
+}
+
+fun EntryDto.toEntity() = Entry().also {
+ it.sensorId = this.sensorId
+ it.value = this.value
+ it.timestamp = Timestamp.from(this.timestamp.toInstant())
+}
diff --git a/src/main/kotlin/de/lrprojects/tempserver/converter/SensorConverter.kt b/src/main/kotlin/de/lrprojects/tempserver/converter/SensorConverter.kt
new file mode 100644
index 0000000..64f4287
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/converter/SensorConverter.kt
@@ -0,0 +1,17 @@
+package de.lrprojects.tempserver.converter
+
+import de.lrprojects.tempserver.entity.Sensor
+import de.lrprojects.tempserver.model.SensorDto
+import de.lrprojects.tempserver.service.api.TypeService
+
+fun Sensor.toDto() = SensorDto().also {
+ it.sensorId = this.id
+ it.sensorNick = this.sensorNick
+ it.sensorType = this.type?.typeName
+}
+
+fun SensorDto.toEntity(typeService: TypeService) = Sensor().also {
+ it.id = this.sensorId
+ it.sensorNick = this.sensorNick
+ it.type = typeService.getTypeByName(this.sensorType)
+}
diff --git a/src/main/kotlin/de/lrprojects/tempserver/converter/TypeConverter.kt b/src/main/kotlin/de/lrprojects/tempserver/converter/TypeConverter.kt
new file mode 100644
index 0000000..33906e8
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/converter/TypeConverter.kt
@@ -0,0 +1,17 @@
+package de.lrprojects.tempserver.converter
+
+import de.lrprojects.tempserver.entity.Type
+import de.lrprojects.tempserver.model.TypeDto
+
+
+fun Type.toDto() = TypeDto().also {
+ it.id = this.id
+ it.typeName = this.typeName
+ it.description = this.description
+}
+
+fun TypeDto.toEntity() = Type().also {
+ it.id = this.id
+ it.typeName = this.typeName
+ it.description = this.description
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/entity/Category.kt b/src/main/kotlin/de/lrprojects/tempserver/entity/Category.kt
new file mode 100644
index 0000000..a8470fb
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/entity/Category.kt
@@ -0,0 +1,13 @@
+package de.lrprojects.tempserver.entity
+
+import jakarta.persistence.Entity
+import jakarta.persistence.Id
+
+
+@Entity
+data class Category(
+ @Id
+ val id: Long? = null,
+ var name: String? = null,
+ var description: String? = null
+)
diff --git a/src/main/kotlin/de/lrprojects/tempserver/entity/Entry.kt b/src/main/kotlin/de/lrprojects/tempserver/entity/Entry.kt
new file mode 100644
index 0000000..1c20f89
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/entity/Entry.kt
@@ -0,0 +1,9 @@
+package de.lrprojects.tempserver.entity
+
+import java.sql.Timestamp
+
+data class Entry(
+ var timestamp: Timestamp? = null,
+ var value: Double? = null,
+ var sensorId: String? = null
+)
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/entity/Sensor.kt b/src/main/kotlin/de/lrprojects/tempserver/entity/Sensor.kt
new file mode 100644
index 0000000..2563107
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/entity/Sensor.kt
@@ -0,0 +1,17 @@
+package de.lrprojects.tempserver.entity
+
+import jakarta.persistence.Entity
+import jakarta.persistence.Id
+import jakarta.persistence.ManyToOne
+import jakarta.persistence.OneToMany
+
+@Entity
+data class Sensor(
+ @Id
+ var id: String? = null,
+ @ManyToOne
+ var type: Type? = null,
+ @OneToMany
+ var categories: List? = null,
+ var sensorNick: String? = null
+)
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/entity/Type.kt b/src/main/kotlin/de/lrprojects/tempserver/entity/Type.kt
new file mode 100644
index 0000000..0e769bf
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/entity/Type.kt
@@ -0,0 +1,15 @@
+package de.lrprojects.tempserver.entity
+
+import jakarta.persistence.Entity
+import jakarta.persistence.GeneratedValue
+import jakarta.persistence.GenerationType
+import jakarta.persistence.Id
+
+@Entity
+data class Type(
+ @Id
+ @GeneratedValue(strategy = GenerationType.AUTO)
+ var id: Long? = null,
+ var typeName: String? = null,
+ var description: String? = null
+)
diff --git a/src/main/kotlin/de/lrprojects/tempserver/repository/CategoryRepository.kt b/src/main/kotlin/de/lrprojects/tempserver/repository/CategoryRepository.kt
new file mode 100644
index 0000000..14015bd
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/repository/CategoryRepository.kt
@@ -0,0 +1,8 @@
+package de.lrprojects.tempserver.repository
+
+import de.lrprojects.tempserver.entity.Category
+import org.springframework.data.jpa.repository.JpaRepository
+import org.springframework.stereotype.Repository
+
+@Repository
+interface CategoryRepository : JpaRepository
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/repository/SensorRepository.kt b/src/main/kotlin/de/lrprojects/tempserver/repository/SensorRepository.kt
new file mode 100644
index 0000000..7d4e499
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/repository/SensorRepository.kt
@@ -0,0 +1,8 @@
+package de.lrprojects.tempserver.repository
+
+import de.lrprojects.tempserver.entity.Sensor
+import org.springframework.data.jpa.repository.JpaRepository
+import org.springframework.stereotype.Repository
+
+@Repository
+interface SensorRepository : JpaRepository
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/repository/TypeRepository.kt b/src/main/kotlin/de/lrprojects/tempserver/repository/TypeRepository.kt
new file mode 100644
index 0000000..dbb4802
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/repository/TypeRepository.kt
@@ -0,0 +1,11 @@
+package de.lrprojects.tempserver.repository
+
+import de.lrprojects.tempserver.entity.Type
+import org.springframework.data.jpa.repository.JpaRepository
+import org.springframework.stereotype.Repository
+
+@Repository
+interface TypeRepository : JpaRepository {
+
+ fun findByTypeName(typeName: String): Type?
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/service/api/CategoryService.kt b/src/main/kotlin/de/lrprojects/tempserver/service/api/CategoryService.kt
new file mode 100644
index 0000000..4708ad8
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/service/api/CategoryService.kt
@@ -0,0 +1,17 @@
+package de.lrprojects.tempserver.service.api
+
+import de.lrprojects.tempserver.entity.Category
+
+interface CategoryService {
+
+ fun getAllCategories(): List
+
+ fun getCategoryById(id: Long): Category?
+
+ fun createCategory(category: Category): Category
+
+ fun updateCategory(category: Category): Category
+
+ fun deleteCategory(id: Long)
+
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/service/api/EntryService.kt b/src/main/kotlin/de/lrprojects/tempserver/service/api/EntryService.kt
new file mode 100644
index 0000000..2d2983e
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/service/api/EntryService.kt
@@ -0,0 +1,13 @@
+package de.lrprojects.tempserver.service.api
+
+import de.lrprojects.tempserver.entity.Entry
+
+interface EntryService {
+
+ fun getEntries(sensorId: String, date1: Long?, date2: Long?, limit: Int?): List
+
+ fun createEntry(sensorId: String, entry: Entry)
+
+ fun deleteEntries(sensorId: String, date1: Long?, date2: Long?)
+
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/service/api/SensorService.kt b/src/main/kotlin/de/lrprojects/tempserver/service/api/SensorService.kt
new file mode 100644
index 0000000..01eeacd
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/service/api/SensorService.kt
@@ -0,0 +1,15 @@
+package de.lrprojects.tempserver.service.api
+
+import de.lrprojects.tempserver.entity.Sensor
+
+interface SensorService {
+ fun getAllSensors(): List
+
+ fun getSensorById(sensorId: String): Sensor?
+
+ fun createSensor(sensor: Sensor): Sensor
+
+ fun updateSensor(sensor: Sensor): Sensor
+
+ fun deleteSensor(sensorId: String)
+}
diff --git a/src/main/kotlin/de/lrprojects/tempserver/service/api/TypeService.kt b/src/main/kotlin/de/lrprojects/tempserver/service/api/TypeService.kt
new file mode 100644
index 0000000..43dcce7
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/service/api/TypeService.kt
@@ -0,0 +1,18 @@
+package de.lrprojects.tempserver.service.api
+
+import de.lrprojects.tempserver.entity.Type
+import de.lrprojects.tempserver.model.TypeDto
+
+interface TypeService {
+ fun getAllTypes(): List
+
+ fun getTypeById(id: Long): Type?
+
+ fun getTypeByName(name: String): Type?
+
+ fun createType(type: TypeDto): Type
+
+ fun updateType(type: TypeDto): Type
+
+ fun deleteType(id: Long)
+}
diff --git a/src/main/kotlin/de/lrprojects/tempserver/service/impl/CategoryServiceImpl.kt b/src/main/kotlin/de/lrprojects/tempserver/service/impl/CategoryServiceImpl.kt
new file mode 100644
index 0000000..631d7ae
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/service/impl/CategoryServiceImpl.kt
@@ -0,0 +1,24 @@
+package de.lrprojects.tempserver.service.impl
+
+import de.lrprojects.tempserver.entity.Category
+import de.lrprojects.tempserver.repository.CategoryRepository
+import de.lrprojects.tempserver.service.api.CategoryService
+import org.springframework.stereotype.Service
+
+@Service
+class CategoryServiceImpl(
+ private val categoryRepository: CategoryRepository
+): CategoryService {
+
+ override fun getAllCategories(): List = categoryRepository.findAll()
+
+ override fun getCategoryById(id: Long): Category? = categoryRepository.findById(id).orElse(null)
+
+ override fun createCategory(category: Category): Category = categoryRepository.save(category)
+
+ override fun updateCategory(category: Category): Category = categoryRepository.save(category)
+
+ override fun deleteCategory(id: Long) {
+ categoryRepository.deleteById(id)
+ }
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/service/impl/EntryServiceImpl.kt b/src/main/kotlin/de/lrprojects/tempserver/service/impl/EntryServiceImpl.kt
new file mode 100644
index 0000000..3263958
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/service/impl/EntryServiceImpl.kt
@@ -0,0 +1,75 @@
+package de.lrprojects.tempserver.service.impl
+
+import com.influxdb.client.InfluxDBClient
+import com.influxdb.client.domain.WritePrecision
+import com.influxdb.client.write.Point
+import de.lrprojects.tempserver.config.InfluxProperties
+import de.lrprojects.tempserver.entity.Entry
+import de.lrprojects.tempserver.service.api.EntryService
+import org.springframework.stereotype.Service
+import java.sql.Timestamp
+import java.time.Instant
+import java.time.format.DateTimeFormatter
+
+@Service
+class EntryServiceImpl(
+ private val influxDBClient: InfluxDBClient,
+ private val influxProperties: InfluxProperties
+): EntryService {
+
+ override fun getEntries(sensorId: String, date1: Long?, date2: Long?, limit: Int?): List {
+ val query = StringBuilder("from(bucket: \"${influxProperties.bucket}\") |> range(start: -1h)")
+ query.append(" |> filter(fn: (r) => r.sensorId == \"$sensorId\")")
+
+ if (date1 != null) {
+ query.append(" |> filter(fn: (r) => r._time >= ${formatTimestamp(date1)})")
+ }
+ if (date2 != null) {
+ query.append(" |> filter(fn: (r) => r._time <= ${formatTimestamp(date2)})")
+ }
+ if (limit != null) {
+ query.append(" |> limit(n: $limit)")
+ }
+
+ val fluxQuery = query.toString()
+ val queryApi = influxDBClient.queryApi
+ val tables = queryApi.query(fluxQuery)
+
+ return tables.flatMap { table ->
+ table.records.map {
+ Entry(
+ timestamp = it.time?.toEpochMilli()?.let { it1 -> Timestamp(it1) },
+ value = it.value as Double,
+ sensorId = sensorId
+ )
+ }
+ }
+ }
+
+ override fun createEntry(sensorId: String, entry: Entry) {
+ val point = Point.measurement("entry")
+ .addTag("sensorId", sensorId)
+ .addField("value", entry.value)
+ .time(entry.timestamp?.toInstant(), WritePrecision.NS)
+
+ influxDBClient.writeApiBlocking.writePoint(point)
+ }
+
+ override fun deleteEntries(sensorId: String, date1: Long?, date2: Long?) {
+ val startDate = date1?.let { formatTimestamp(it) } ?: "0"
+ val stopDate = date2?.let { formatTimestamp(it) } ?: "now()"
+
+ val deleteQuery = """
+ from(bucket: "${influxProperties.bucket}")
+ |> range(start: $startDate, stop: $stopDate)
+ |> filter(fn: (r) => r.sensorId == "$sensorId")
+ |> drop()
+ """.trimIndent()
+
+ influxDBClient.queryApi.query(deleteQuery)
+ }
+
+ private fun formatTimestamp(epochMillis: Long): String {
+ return DateTimeFormatter.ISO_INSTANT.format(Instant.ofEpochMilli(epochMillis))
+ }
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/service/impl/SensorServiceImpl.kt b/src/main/kotlin/de/lrprojects/tempserver/service/impl/SensorServiceImpl.kt
new file mode 100644
index 0000000..0983f2d
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/service/impl/SensorServiceImpl.kt
@@ -0,0 +1,26 @@
+package de.lrprojects.tempserver.service.impl
+
+import de.lrprojects.tempserver.entity.Sensor
+import de.lrprojects.tempserver.repository.SensorRepository
+import de.lrprojects.tempserver.service.api.SensorService
+import org.springframework.stereotype.Service
+
+@Service
+class SensorServiceImpl(
+ private val sensorRepository: SensorRepository,
+): SensorService {
+ override fun getAllSensors(): List = sensorRepository.findAll()
+
+ override fun getSensorById(sensorId: String): Sensor? = sensorRepository.findById(sensorId).orElse(null)
+
+ override fun createSensor(sensor: Sensor): Sensor {
+ val savedSensor = sensorRepository.save(sensor)
+ return savedSensor
+ }
+
+ override fun updateSensor(sensor: Sensor): Sensor = sensorRepository.save(sensor)
+
+ override fun deleteSensor(sensorId: String) {
+ sensorRepository.deleteById(sensorId)
+ }
+}
\ No newline at end of file
diff --git a/src/main/kotlin/de/lrprojects/tempserver/service/impl/TypeServiceImpl.kt b/src/main/kotlin/de/lrprojects/tempserver/service/impl/TypeServiceImpl.kt
new file mode 100644
index 0000000..7d0cb61
--- /dev/null
+++ b/src/main/kotlin/de/lrprojects/tempserver/service/impl/TypeServiceImpl.kt
@@ -0,0 +1,27 @@
+package de.lrprojects.tempserver.service.impl
+
+import de.lrprojects.tempserver.converter.toEntity
+import de.lrprojects.tempserver.entity.Type
+import de.lrprojects.tempserver.model.TypeDto
+import de.lrprojects.tempserver.repository.TypeRepository
+import de.lrprojects.tempserver.service.api.TypeService
+import org.springframework.stereotype.Service
+
+@Service
+class TypeServiceImpl(
+ private val typeRepository: TypeRepository
+): TypeService {
+ override fun getAllTypes(): List = typeRepository.findAll()
+
+ override fun getTypeById(id: Long): Type? = typeRepository.findById(id).orElse(null)
+
+ override fun getTypeByName(name: String): Type? = typeRepository.findByTypeName(name)
+
+ override fun createType(type: TypeDto): Type = typeRepository.save(type.toEntity())
+
+ override fun updateType(type: TypeDto): Type = typeRepository.save(type.toEntity())
+
+ override fun deleteType(id: Long) {
+ typeRepository.deleteById(id)
+ }
+}
diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties
deleted file mode 100644
index be59bfd..0000000
--- a/src/main/resources/application.properties
+++ /dev/null
@@ -1,15 +0,0 @@
-#datasource configurations
-#<---------------------- uncomment for *local* database use: --------------------->
-spring.datasource.url=${DATASOURCE_URL}
-
-spring.datasource.username=${DB_USER}
-spring.datasource.password=${DB_PASSWORD}
-spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
-# DDL generation
-spring.jpa.hibernate.ddl-auto = update
-spring.mvc.hiddenmethod.filter.enabled=true
-#heroku port
-server.port=${PORT:8080}
-
-# V1 < 08.06.2022
-# v2 : 08.06.2022
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
new file mode 100644
index 0000000..75f9591
--- /dev/null
+++ b/src/main/resources/application.yml
@@ -0,0 +1,25 @@
+server:
+ port: ${PORT:8080}
+
+spring:
+ config:
+ import: optional:file:.env[.properties]
+ jpa:
+ hibernate:
+ ddl-auto: update
+ database: postgresql
+ properties:
+ hibernate:
+ dialect: org.hibernate.dialect.PostgreSQLDialect
+ datasource:
+ url: ${DB_URL}
+ driver-class-name: org.postgresql.Driver
+ username: ${POSTGRES_USER}
+ password: ${POSTGRES_PASSWORD}
+
+influxdb:
+ url: ${INFLUXDB_URL}
+ token: ${INFLUXDB_TOKEN}
+ bucket: ${INFLUXDB_BUCKET}
+ org: ${INFLUXDB_ORG}
+ enabled: ${INFLUXDB_ENABLED}
\ No newline at end of file