Compare commits

...
59 Commits
Author SHA1 Message Date
2martens 174a6cc79e Added spring doc webflux support and kotlin coroutines 2023-08-19 14:24:14 +02:00
2martens d321ed85c9 Dump commit 2023-08-19 03:29:01 +02:00
2martens 37f57f788b Do not overwrite existing collections
continuous-integration/drone Build is failing
continuous-integration/drone/promote/production Build is passing
2023-08-17 23:56:56 +02:00
2martens d5c7597a04 Add cache to minimize time for installing ansible collections
continuous-integration/drone Build is failing
2023-08-17 23:53:39 +02:00
2martens 8f31d2dd3d Move to private_ssh_key as secret
continuous-integration/drone Build is failing
2023-08-17 23:49:06 +02:00
2martens 5ff47de10a Prevent commit if nothing changed
continuous-integration/drone Build is failing
2023-08-17 23:39:39 +02:00
2martens 794a08c9b0 Only run code quality on pull request
continuous-integration/drone Build is failing
2023-08-17 23:24:41 +02:00
2martens d579004653 Don't limit to target
continuous-integration/drone/push Build was killed
continuous-integration/drone Build was killed
2023-08-17 23:22:30 +02:00
2martens e127d66a1b Remove custom trigger for building docker container
continuous-integration/drone/push Build is failing
2023-08-17 23:21:36 +02:00
2martens 21fa17e62b Added galaxy requirements
continuous-integration/drone/push Build was killed
continuous-integration/drone Build is failing
2023-08-17 23:20:14 +02:00
2martens 8381c1ba7d Use Drone semver
continuous-integration/drone/push Build is failing
2023-08-17 23:07:16 +02:00
2martens 4308130cd1 Fixed usage of image version
continuous-integration/drone/push Build is failing
continuous-integration/drone/promote/production Build is failing
2023-08-17 23:03:00 +02:00
2martens 721cdac95d Use latest ansible plugin version
continuous-integration/drone/push Build is failing
2023-08-17 22:59:49 +02:00
2martens 395fa52962 Fixed pipeline
continuous-integration/drone/push Build is failing
continuous-integration/drone/promote/production Build is failing
2023-08-17 22:50:20 +02:00
2martens 45e5c473ff Added pipeline to deploy via Ansible
continuous-integration/drone/push Build is failing
continuous-integration/drone/promote/production Build is failing
2023-08-17 21:11:44 +02:00
2martens 1c3648f0f4 Update [CI SKIP] 2023-08-17 12:51:18 +02:00
2martens 5b707728b8 Change properties [CI SKIP] 2023-08-17 02:18:08 +02:00
2martens c19c211839 Make properties refreshable
continuous-integration/drone/push Build is failing
2023-08-17 02:15:23 +02:00
2martens aace535914 Change message [CI SKIP] 2023-08-17 02:13:07 +02:00
2martens 59982ef762 Remove refresh scope from Clock
continuous-integration/drone/push Build is failing
2023-08-17 02:08:12 +02:00
2martens 56c6fef178 Remove constructor binding
continuous-integration/drone/push Build is failing
2023-08-17 02:02:19 +02:00
2martens 46b1b32708 Properties must be changeable with setters
continuous-integration/drone/push Build is failing
2023-08-17 01:52:50 +02:00
2martens 519101023c Change message [CI SKIP] 2023-08-17 01:42:01 +02:00
2martens 82b4f51390 Require configserver on prod
continuous-integration/drone/push Build is failing
2023-08-17 01:38:26 +02:00
2martens 3256939ac7 Change message [CI SKIP] 2023-08-17 01:20:17 +02:00
2martens 02e4c5318d Fix bootstrap servers on prod
continuous-integration/drone/push Build is failing
2023-08-17 01:14:03 +02:00
2martens f06abd2838 Add application name
continuous-integration/drone/push Build is failing
2023-08-17 01:12:38 +02:00
2martens f0297f2d2c Changed prod message [CI SKIP] 2023-08-17 01:10:11 +02:00
2martens ec23bd4d32 Connect with kafka using bootstrap servers
continuous-integration/drone/push Build is failing
2023-08-17 00:53:05 +02:00
2martens bab1892673 Added kafka server config
continuous-integration/drone/push Build is failing
2023-08-17 00:42:53 +02:00
2martens 247fe83caa Changed config [CI SKIP] 2023-08-17 00:36:27 +02:00
2martens 5fe6165373 Remove property reload service
continuous-integration/drone/push Build is failing
2023-08-17 00:35:50 +02:00
2martens 64a8f17e6e Change greeting on dev [CI SKIP] 2023-08-17 00:04:56 +02:00
2martens 5eff527c48 Enable config server locally
continuous-integration/drone/push Build is failing
2023-08-17 00:02:57 +02:00
2martens 642713e14c Fixed rest health indicator 2023-08-17 00:02:45 +02:00
2martens ff8b205124 Add Kafka dependency 2023-08-16 23:08:49 +02:00
2martens 8c5f925e36 Change greeting message [CI SKIP] 2023-08-16 22:39:24 +02:00
2martens fe5cd41749 Specify metadata in jar task (likely used by Jib)
continuous-integration/drone/push Build is failing
2023-08-16 22:31:05 +02:00
2martens 3a25e33f3f Prevent NPE 2023-08-16 22:30:50 +02:00
2martens ec625fb7b5 Use service properties to check successful change
continuous-integration/drone/push Build is failing
2023-08-16 22:21:53 +02:00
2martens c8e4474175 Remove configserver import from general configuration
continuous-integration/drone/push Build is failing
2023-08-16 22:09:50 +02:00
2martens 499c85ae49 Load configserver only in production and move refreshable prod properties to wahlrecht-prod
continuous-integration/drone/push Build is failing
2023-08-16 22:08:50 +02:00
2martens e88d98efc1 Dummy change
continuous-integration/drone/push Build is failing
2023-08-16 21:56:57 +02:00
2martens 8d545aa7fb Moved refreshable configuration to config sub-directory
continuous-integration/drone/push Build is failing
2023-08-16 21:54:42 +02:00
2martens a04094bc60 Move configserver import to bootstrap.yaml
continuous-integration/drone/push Build is failing
2023-08-16 21:09:15 +02:00
2martens 7d68612e57 Adjusted path to configserver
continuous-integration/drone/push Build is failing
2023-08-16 20:17:57 +02:00
2martens 64295db0e7 Added environments for http requests
continuous-integration/drone/push Build is failing
2023-08-16 20:08:54 +02:00
2martens 6dcd302ab7 OPTIONS method does not have to be allowed 2023-08-16 20:08:01 +02:00
2martens e50e769e22 Added production domain as allowed origin
continuous-integration/drone/push Build is failing
2023-08-16 12:52:17 +02:00
2martens b7c85e2368 Reversed code format 2023-08-16 01:00:48 +02:00
2martens a60289fc49 Added production server to OpenAPI
continuous-integration/drone/push Build is failing
2023-08-16 01:00:16 +02:00
2martens 9c4feee043 Use 127.0.0.1 as address
continuous-integration/drone/push Build is failing
2023-08-16 00:25:15 +02:00
2martens 1a50b40eaf Load log4j2.xml from resources
continuous-integration/drone/push Build is failing
2023-08-15 23:50:42 +02:00
2martens 3c7464a0cf Fix mainClassName
continuous-integration/drone/push Build is failing
2023-08-15 22:37:45 +02:00
2martens 2fe84fec45 Exclude env.sh script
continuous-integration/drone/push Build is failing
2023-08-15 09:28:32 +02:00
2martens bc1f85865c Enable bootJar 2023-08-15 09:28:18 +02:00
2martens 17bde7aa42 Fix config import property 2023-08-15 09:21:22 +02:00
2martens 9d21dfe032 Added scripts to help with nebula releases 2023-08-15 08:25:46 +02:00
2martens e463f0b7a8 Removed not required toString 2023-08-15 08:24:02 +02:00
48 changed files with 694 additions and 555 deletions
+77 -7
View File
@@ -30,7 +30,6 @@ volumes:
trigger: trigger:
event: event:
include: include:
- push
- pull_request - pull_request
- custom - custom
@@ -51,7 +50,7 @@ steps:
image: alpine/git image: alpine/git
environment: environment:
SSH_KEY: SSH_KEY:
from_secret: ssh_key from_secret: private_ssh_key
commands: commands:
- mkdir $HOME/.ssh - mkdir $HOME/.ssh
- echo "$SSH_KEY" > $HOME/.ssh/id_ed25519 - echo "$SSH_KEY" > $HOME/.ssh/id_ed25519
@@ -69,7 +68,7 @@ steps:
PASSWORD: PASSWORD:
from_secret: docker_password from_secret: docker_password
SSH_KEY: SSH_KEY:
from_secret: ssh_key from_secret: private_ssh_key
volumes: volumes:
- name: cache - name: cache
path: /home/gradle/.gradle path: /home/gradle/.gradle
@@ -88,10 +87,81 @@ volumes:
path: /var/lib/drone/cache/.gradle path: /var/lib/drone/cache/.gradle
trigger: trigger:
branches:
- main
event: event:
include: include:
- push - tag
- custom
---
kind: pipeline
name: deploy image
type: docker
platform:
os: linux
arch: arm64
clone:
disable: true
steps:
- name: clone
image: alpine/git
environment:
SSH_KEY:
from_secret: private_ssh_key
commands:
- mkdir $HOME/.ssh
- echo "$SSH_KEY" > $HOME/.ssh/id_ed25519
- chmod 600 $HOME/.ssh/id_ed25519
- touch $HOME/.ssh/known_hosts
- chmod 600 $HOME/.ssh/known_hosts
- ssh-keyscan -H git.2martens.de > $HOME/.ssh/known_hosts 2>/dev/null
- git clone ssh://giteajim@git.2martens.de:22/2martens/cloud-configuration.git .
- git checkout main
- name: modify deployed image
image: alpine
commands:
- sed -i -r "s/(wahlrecht_image_version:).*/\1\ ${DRONE_SEMVER}/" ansible/inventories/host_vars/api-server/public.yaml
- name: save modified variable file
image: alpine/git
environment:
SSH_KEY:
from_secret: private_ssh_key
commands:
- mkdir $HOME/.ssh
- echo "$SSH_KEY" > $HOME/.ssh/id_ed25519
- chmod 600 $HOME/.ssh/id_ed25519
- touch $HOME/.ssh/known_hosts
- chmod 600 $HOME/.ssh/known_hosts
- ssh-keyscan -H git.2martens.de > $HOME/.ssh/known_hosts 2>/dev/null
- git add ansible/inventories/host_vars/api-server/public.yaml
- git diff-index --quiet HEAD || git commit -m "[Drone] Changed wahlrecht_image_version to ${DRONE_SEMVER}"
- git push origin main
- name: deploy image
image: plugins/ansible:latest
volumes:
- name: cache
path: /root/.ansible
settings:
playbook: ansible/deploy_spring.yaml
inventory: ansible/inventories/production
galaxy: ansible/requirements.yaml
galaxy_force: false
private_key:
from_secret: private_ssh_key
vault_password:
from_secret: vault_password
volumes:
- name: cache
host:
path: /var/lib/drone/cache/.ansible
trigger:
# target:
# - production
event:
include:
- promote
- rollback
- custom
+1
View File
@@ -12,6 +12,7 @@ build/
**/*.log **/*.log
**/*.hprof **/*.hprof
**/generated/** **/generated/**
env.sh
### STS ### ### STS ###
.apt_generated .apt_generated
@@ -1,6 +1,4 @@
import org.gradle.accessors.dm.LibrariesForLibs import org.gradle.accessors.dm.LibrariesForLibs
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
plugins { plugins {
jacoco jacoco
@@ -51,22 +49,6 @@ tasks.jacocoTestReport {
} }
} }
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
tasks.jar {
doFirst {
manifest {
attributes["Implementation-Title"] = rootProject.name
attributes["Implementation-Version"] = archiveVersion.get()
attributes["Implementation-Vendor"] = "Jim Martens"
attributes["Build-Timestamp"] = ZonedDateTime.now().format(formatter)
attributes["Created-By"] = "Gradle ${gradle.gradleVersion}"
attributes["Build-Jdk"] = "${providers.systemProperty("java.version").get()} (${providers.systemProperty("java.vendor").get()} ${providers.systemProperty("java.vm.version").get()})"
attributes["Build-OS"] = "${providers.systemProperty("os.name").get()} ${providers.systemProperty("os.arch").get()} ${providers.systemProperty("os.version").get()}"
}
}
}
normalization.runtimeClasspath.metaInf { normalization.runtimeClasspath.metaInf {
ignoreAttribute("Build-Timestamp") ignoreAttribute("Build-Timestamp")
} }
@@ -8,6 +8,9 @@ val libs = the<LibrariesForLibs>()
dependencies { dependencies {
implementation(libs.kotlin.logging) implementation(libs.kotlin.logging)
implementation(libs.kotlin.reactor)
implementation(libs.kotlin.coroutines)
implementation(libs.kotlin.coroutines.reactor)
implementation(kotlin("reflect")) implementation(kotlin("reflect"))
} }
@@ -13,6 +13,6 @@ tasks.register("writeVersionProperties") {
val directory = buildDir val directory = buildDir
doLast { doLast {
Files.createDirectories(directory.toPath()) Files.createDirectories(directory.toPath())
File("$buildDir/version.properties").writeText("VERSION=${project.version.toString()}\n") File("$buildDir/version.properties").writeText("VERSION=${project.version}\n")
} }
} }
@@ -9,7 +9,6 @@ val libs = the<LibrariesForLibs>()
dependencies { dependencies {
implementation(platform(libs.spring.cloud)) implementation(platform(libs.spring.cloud))
implementation(libs.bundles.spring.boot.server) implementation(libs.bundles.spring.boot.server)
implementation(libs.spring.openapi)
implementation(libs.httpclient) implementation(libs.httpclient)
implementation(libs.prometheus) implementation(libs.prometheus)
@@ -1,4 +1,7 @@
import org.gradle.accessors.dm.LibrariesForLibs import org.gradle.accessors.dm.LibrariesForLibs
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatter.ofPattern
plugins { plugins {
id("org.springframework.boot") id("org.springframework.boot")
@@ -57,27 +60,21 @@ tasks.named("buildAll") {
dependsOn("integrationTest") dependsOn("integrationTest")
} }
springBoot { val formatter: DateTimeFormatter = ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
buildInfo()
}
tasks.bootJar {
enabled = false
}
tasks.jar { tasks.jar {
enabled = true manifest {
archiveClassifier.set("") attributes["Implementation-Title"] = rootProject.name
attributes["Implementation-Version"] = archiveVersion.get()
attributes["Implementation-Vendor"] = "Jim Martens"
attributes["Build-Timestamp"] = ZonedDateTime.now().format(formatter)
attributes["Created-By"] = "Gradle ${gradle.gradleVersion}"
attributes["Build-Jdk"] = "${providers.systemProperty("java.version").get()} (${providers.systemProperty("java.vendor").get()} ${providers.systemProperty("java.vm.version").get()})"
attributes["Build-OS"] = "${providers.systemProperty("os.name").get()} ${providers.systemProperty("os.arch").get()} ${providers.systemProperty("os.version").get()}"
}
} }
tasks.bootDistZip { springBoot {
dependsOn(tasks.jar) buildInfo()
mainClass.set("de.twomartens.wahlrecht.MainApplicationKt")
} }
tasks.bootDistTar {
dependsOn(tasks.jar)
}
tasks.bootStartScripts {
dependsOn(tasks.jar)
}
+16 -4
View File
@@ -1,6 +1,7 @@
[versions] [versions]
spring-boot = "3.1.2" spring-boot = "3.1.2"
spring-doc = "2.1.0" spring-doc = "2.1.0"
spring-doc-webflux = "1.7.0"
spring-cloud = "2022.0.4" spring-cloud = "2022.0.4"
spring-grpc = "2.14.0.RELEASE" spring-grpc = "2.14.0.RELEASE"
grpc = "1.57.0" grpc = "1.57.0"
@@ -17,6 +18,8 @@ keycloak = "22.0.1"
kotlin-logging = "3.0.5" kotlin-logging = "3.0.5"
kotlin-reflect = "1.9.0" kotlin-reflect = "1.9.0"
kotlin-lombok = "1.9.0" kotlin-lombok = "1.9.0"
kotlin-reactor = "1.2.2"
kotlin-coroutines = "1.7.3"
plugin-nebula-release = "17.2.2" plugin-nebula-release = "17.2.2"
plugin-lombok = "8.0.1" plugin-lombok = "8.0.1"
plugin-gradle-versions = "0.46.0" plugin-gradle-versions = "0.46.0"
@@ -31,20 +34,24 @@ spring-boot-web = { module = "org.springframework.boot:spring-boot-starter-web"
spring-boot-log4j = { module = "org.springframework.boot:spring-boot-starter-log4j2" } spring-boot-log4j = { module = "org.springframework.boot:spring-boot-starter-log4j2" }
spring-boot-thymeleaf = { module = "org.springframework.boot:spring-boot-starter-thymeleaf" } spring-boot-thymeleaf = { module = "org.springframework.boot:spring-boot-starter-thymeleaf" }
spring-boot-mongo = { module = "org.springframework.boot:spring-boot-starter-data-mongodb" } spring-boot-mongo = { module = "org.springframework.boot:spring-boot-starter-data-mongodb" }
spring-boot-mongo-reactive = { module = "org.springframework.boot:spring-boot-starter-data-mongodb-reactive" }
spring-boot-validation = { module = "org.springframework.boot:spring-boot-starter-validation" } spring-boot-validation = { module = "org.springframework.boot:spring-boot-starter-validation" }
spring-boot-test = { module = "org.springframework.boot:spring-boot-starter-test" } spring-boot-test = { module = "org.springframework.boot:spring-boot-starter-test" }
spring-boot-security = { module = "org.springframework.boot:spring-boot-starter-security" } spring-boot-security = { module = "org.springframework.boot:spring-boot-starter-security" }
spring-boot-oauth2-resource-server = { module = "org.springframework.boot:spring-boot-starter-oauth2-resource-server" } spring-boot-oauth2-resource-server = { module = "org.springframework.boot:spring-boot-starter-oauth2-resource-server" }
spring-boot-webflux = { module = "org.springframework.boot:spring-boot-starter-webflux" }
spring-boot-config = { module = "org.springframework.boot:spring-boot-configuration-processor", version.ref = "spring-boot" } spring-boot-config = { module = "org.springframework.boot:spring-boot-configuration-processor", version.ref = "spring-boot" }
spring-cloud = { module = "org.springframework.cloud:spring-cloud-dependencies", version.ref = "spring-cloud" } spring-cloud = { module = "org.springframework.cloud:spring-cloud-dependencies", version.ref = "spring-cloud" }
spring-cloud-starter = { module = "org.springframework.cloud:spring-cloud-starter" } spring-cloud-starter = { module = "org.springframework.cloud:spring-cloud-starter" }
spring-cloud-starter-bus-kafka = { module = "org.springframework.cloud:spring-cloud-starter-bus-kafka" }
spring-cloud-starter-config = { module = "org.springframework.cloud:spring-cloud-starter-config" } spring-cloud-starter-config = { module = "org.springframework.cloud:spring-cloud-starter-config" }
spring-cloud-config-server = { module = "org.springframework.cloud:spring-cloud-config-server" } spring-cloud-config-server = { module = "org.springframework.cloud:spring-cloud-config-server" }
spring-boot-starter = { module = "org.springframework.boot:spring-boot-starter" } spring-boot-starter = { module = "org.springframework.boot:spring-boot-starter" }
spring-grpc = { module = "net.devh:grpc-spring-boot-starter", version.ref = "spring-grpc" } spring-grpc = { module = "net.devh:grpc-spring-boot-starter", version.ref = "spring-grpc" }
spring-ui = { module = "org.springdoc:springdoc-openapi-starter-webmvc-ui", version.ref = "spring-doc" } spring-ui = { module = "org.springdoc:springdoc-openapi-starter-webmvc-ui", version.ref = "spring-doc" }
spring-sec = { module = "org.springdoc:springdoc-openapi-starter-common", version.ref = "spring-doc" } spring-openapi-starter = { module = "org.springdoc:springdoc-openapi-starter-common", version.ref = "spring-doc" }
spring-openapi = { module = "org.springdoc:springdoc-openapi-starter-webmvc-api", version.ref = "spring-doc" } spring-openapi-webmvc = { module = "org.springdoc:springdoc-openapi-starter-webmvc-api", version.ref = "spring-doc" }
spring-openapi-webflux = { module = "org.springdoc:springdoc-openapi-webflux-ui", version.ref = "spring-doc-webflux" }
keycloak-core = { module = "org.keycloak:keycloak-core", version.ref = "keycloak" } keycloak-core = { module = "org.keycloak:keycloak-core", version.ref = "keycloak" }
keycloak-policy-enforcer = { module = "org.keycloak:keycloak-policy-enforcer", version.ref = "keycloak" } keycloak-policy-enforcer = { module = "org.keycloak:keycloak-policy-enforcer", version.ref = "keycloak" }
grpc-api = { module = "io.grpc:grpc-api", version.ref = "grpc" } grpc-api = { module = "io.grpc:grpc-api", version.ref = "grpc" }
@@ -77,6 +84,9 @@ mockito-inline = "org.mockito:mockito-inline:5.2.0"
mockito-junit = { module = "org.mockito:mockito-junit-jupiter", version.ref = "mockito" } mockito-junit = { module = "org.mockito:mockito-junit-jupiter", version.ref = "mockito" }
kotlin-logging = { module = "io.github.microutils:kotlin-logging-jvm", version.ref = "kotlin-logging" } kotlin-logging = { module = "io.github.microutils:kotlin-logging-jvm", version.ref = "kotlin-logging" }
kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin-reflect" } kotlin-reflect = { module = "org.jetbrains.kotlin:kotlin-reflect", version.ref = "kotlin-reflect" }
kotlin-reactor = { module = "io.projectreactor.kotlin:reactor-kotlin-extensions", version.ref = "kotlin-reactor" }
kotlin-coroutines = { module = "org.jetbrains.kotlinx:kotlin-coroutines-core", version.ref = "kotlin-coroutines" }
kotlin-coroutines-reactor = { module = "org.jetbrains.kotlinx:kotlin-coroutines-reactor", version.ref = "kotlin-coroutines" }
plugin-nebula-release = { module = "com.netflix.nebula:nebula-release-plugin", version.ref = "plugin-nebula-release" } plugin-nebula-release = { module = "com.netflix.nebula:nebula-release-plugin", version.ref = "plugin-nebula-release" }
plugin-springboot = { module = "org.springframework.boot:spring-boot-gradle-plugin", version.ref = "spring-boot" } plugin-springboot = { module = "org.springframework.boot:spring-boot-gradle-plugin", version.ref = "spring-boot" }
plugin-lombok = { module = "io.freefair.gradle:lombok-plugin", version.ref = "plugin-lombok" } plugin-lombok = { module = "io.freefair.gradle:lombok-plugin", version.ref = "plugin-lombok" }
@@ -111,12 +121,14 @@ spring-boot = [
spring-boot-server = [ spring-boot-server = [
"spring-boot-actuator", "spring-boot-actuator",
"spring-boot-log4j", "spring-boot-log4j",
"spring-boot-mongo", "spring-boot-mongo-reactive",
"spring-boot-thymeleaf", "spring-boot-thymeleaf",
"spring-boot-validation", "spring-boot-validation",
"spring-boot-web", "spring-boot-web",
"spring-boot-webflux",
"spring-cloud-starter", "spring-cloud-starter",
"spring-sec", "spring-openapi-starter",
"spring-openapi-webflux",
"spring-ui", "spring-ui",
] ]
spring-boot-security = [ spring-boot-security = [
+1 -1
View File
@@ -1,4 +1,4 @@
POST http://localhost:12000/wahlrecht/v1/calculate POST {{backend}}/wahlrecht/v1/calculate
Content-Type: application/json Content-Type: application/json
{ {
+2
View File
@@ -0,0 +1,2 @@
GET {{backend}}/wahlrecht/v1/elections
Content-Type: application/json
+8
View File
@@ -0,0 +1,8 @@
{
"dev": {
"backend": "http://localhost:12000"
},
"prod" : {
"backend": "https://api.2martens.de"
}
}
+2 -4
View File
@@ -31,10 +31,8 @@ jib {
} }
} }
container { container {
extraClasspath = listOf("/configmap") mainClass = "de.twomartens.wahlrecht.MainApplicationKt"
mainClass = "de.twomartens.wahlrecht.MainApplication"
jvmFlags = listOf("-XX:+UseContainerSupport", jvmFlags = listOf("-XX:+UseContainerSupport",
"-XX:MaxRAMPercentage=75.0", "-XX:MaxRAMPercentage=75.0")
"-Dlog4j.configurationFile=/configmap/log4j2.xml")
} }
} }
@@ -1,2 +0,0 @@
server:
port: 12000
+2 -1
View File
@@ -10,4 +10,5 @@ dependencies {
annotationProcessor(libs.mapstruct.processor) annotationProcessor(libs.mapstruct.processor)
kapt(libs.mapstruct.processor) kapt(libs.mapstruct.processor)
implementation(libs.spring.cloud.starter.config) implementation(libs.spring.cloud.starter.config)
} implementation(libs.spring.cloud.starter.bus.kafka)
}
@@ -3,11 +3,13 @@ package de.twomartens.wahlrecht
import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication import org.springframework.boot.runApplication
import org.springframework.data.mongodb.config.EnableMongoAuditing import org.springframework.data.mongodb.config.EnableMongoAuditing
import org.springframework.data.mongodb.repository.config.EnableReactiveMongoRepositories
import org.springframework.scheduling.annotation.EnableScheduling import org.springframework.scheduling.annotation.EnableScheduling
@EnableMongoAuditing @EnableMongoAuditing
@EnableScheduling @EnableScheduling
@SpringBootApplication @SpringBootApplication
@EnableReactiveMongoRepositories
open class MainApplication open class MainApplication
fun main(args: Array<String>) { fun main(args: Array<String>) {
@@ -6,6 +6,7 @@ import io.swagger.v3.oas.annotations.security.OAuthFlows
import io.swagger.v3.oas.annotations.security.SecurityScheme import io.swagger.v3.oas.annotations.security.SecurityScheme
import io.swagger.v3.oas.models.OpenAPI import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.info.Info import io.swagger.v3.oas.models.info.Info
import io.swagger.v3.oas.models.servers.Server
import org.springframework.beans.factory.annotation.Value import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Configuration
@@ -35,5 +36,7 @@ open class OpenApiConfiguration {
.version(apiVersion) .version(apiVersion)
.description(apiDescription) .description(apiDescription)
) )
.addServersItem(Server().url("http://localhost:12000"))
.addServersItem(Server().url("https://api.2martens.de"))
} }
} }
@@ -16,10 +16,13 @@ open class WebConfiguration(private val headerInterceptorRest: HeaderInterceptor
override fun addCorsMappings(registry: CorsRegistry) { override fun addCorsMappings(registry: CorsRegistry) {
val registration = registry.addMapping("/**") val registration = registry.addMapping("/**")
registration.allowedMethods( registration.allowedMethods(
HttpMethod.GET.name(), HttpMethod.POST.name(), HttpMethod.GET.name(), HttpMethod.POST.name(),
HttpMethod.PUT.name(), HttpMethod.OPTIONS.name() HttpMethod.PUT.name(), HttpMethod.HEAD.name()
) )
registration.allowCredentials(true) registration.allowCredentials(true)
registration.allowedOrigins("http://localhost:4200") registration.allowedOrigins(
"http://localhost:4200",
"https://wahlrecht.2martens.de"
)
} }
} }
@@ -32,14 +32,16 @@ class VersionHtmlController {
} }
private fun getTitle(): String { private fun getTitle(): String {
val title = VersionHtmlController::class.java.getPackage().implementationTitle val title = VersionHtmlController::class.java.`package`.implementationTitle
?: return "application"
return title.ifBlank { return title.ifBlank {
"application" "application"
} }
} }
private fun getVersion(): String { private fun getVersion(): String {
val version = VersionHtmlController::class.java.getPackage().implementationVersion val version = VersionHtmlController::class.java.`package`.implementationVersion
?: return "DEVELOPER"
return version.ifBlank { return version.ifBlank {
"DEVELOPER" "DEVELOPER"
} }
@@ -18,6 +18,7 @@ import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController import org.springframework.web.bind.annotation.RestController
import reactor.core.publisher.Mono
@RestController @RestController
@RequestMapping(value = ["/wahlrecht/v1"]) @RequestMapping(value = ["/wahlrecht/v1"])
@@ -47,12 +48,12 @@ class CalculationController(private val service: CalculationService) {
@SecurityRequirement(name = "oauth2") @SecurityRequirement(name = "oauth2")
fun calculateResult( fun calculateResult(
@RequestBody electionResult: ElectionResult @RequestBody electionResult: ElectionResult
): ResponseEntity<ElectedCandidates> { ): ResponseEntity<Mono<ElectedCandidates>> {
val result = electedCandidatesMapper.mapToExternal( val result = electedCandidatesMapper.mapToExternal(
service.determineElectedCandidates(electionResultMapper.mapToInternal(electionResult)) service.determineElectedCandidates(electionResultMapper.mapToInternal(electionResult))
) )
return ResponseEntity.ok() return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON)
.body(result) .body(Mono.just(result))
} }
} }
@@ -12,80 +12,97 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.security.SecurityRequirement import io.swagger.v3.oas.annotations.security.SecurityRequirement
import io.swagger.v3.oas.annotations.tags.Tag import io.swagger.v3.oas.annotations.tags.Tag
import org.mapstruct.factory.Mappers import org.mapstruct.factory.Mappers
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.*
import org.springframework.web.util.UriComponentsBuilder
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuples
@RestController @RestController
@RequestMapping(value = ["/wahlrecht/v1"]) @RequestMapping(value = ["/wahlrecht/v1"])
@Tag(name = "Elections", description = "all requests relating to elections") @Tag(name = "Elections", description = "all requests relating to elections")
class ElectionController(private val service: ElectionService) { class ElectionController(private val service: ElectionService) {
private val mapper = Mappers.getMapper(ElectionMapper::class.java) private val mapper = Mappers.getMapper(ElectionMapper::class.java)
@SecurityRequirement(name = "oauth2") @SecurityRequirement(name = "oauth2")
@SecurityRequirement(name = "bearerAuth") @SecurityRequirement(name = "bearerAuth")
@GetMapping(value = ["/elections"], produces = [MediaType.APPLICATION_JSON_VALUE]) @GetMapping(value = ["/elections"])
@Operation( @Operation(
summary = "Returns all stored elections", summary = "Returns all stored elections",
responses = [ApiResponse( responses = [ApiResponse(
responseCode = "200", responseCode = "200",
description = "Returns all stored elections", description = "Returns all stored elections",
content = [Content( content = [Content(
mediaType = "application/json", mediaType = "application/json",
array = ArraySchema( array = ArraySchema(
schema = Schema( schema = Schema(
implementation = Election::class implementation = Election::class
) )
) )
)] )]
)] )]
) )
fun getElections(): ResponseEntity<Collection<Election>> { fun getElections(): Flux<Election> {
val elections = service.elections.asSequence() val elections = service.getElections()
.map { mapper.mapToExternal(it.value) } .map {
.toList() mapper.mapToExternal(it)
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(elections)
} }
return elections
}
@Operation( @Operation(
summary = "Returns election matching provided name", summary = "Returns election matching provided name",
responses = [ApiResponse( responses = [ApiResponse(
responseCode = "200", responseCode = "200",
description = "Returns matching election", description = "Returns matching election",
content = [Content(mediaType = "application/json", schema = Schema(implementation = Election::class))] content = [Content(mediaType = "application/json", schema = Schema(implementation = Election::class))]
)] )]
) )
@GetMapping(value = ["/elections/by-name/{electionName}"], produces = [MediaType.APPLICATION_JSON_VALUE]) @GetMapping(value = ["/elections/{electionName}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@SecurityRequirement(name = "bearerAuth") @SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2") @SecurityRequirement(name = "oauth2")
fun getElectionByName( fun getElectionByName(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String? @PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String
): ResponseEntity<Election> { ): ResponseEntity<Mono<Election>> {
val election = mapper.mapToExternal(service.elections[electionName]!!) val election = service.findElectionByName(electionName)
return ResponseEntity.ok() .map { mapper.mapToExternal(it) }
.contentType(MediaType.APPLICATION_JSON) return ResponseEntity.ok()
.body(election) .contentType(MediaType.APPLICATION_JSON)
} .body(election)
}
@Operation( @Operation(
summary = "Stores a new election", summary = "Stores a new election",
responses = [ApiResponse( responses = [ApiResponse(
responseCode = "201", responseCode = "201",
description = "Election was created" description = "Election was created"
), ApiResponse(responseCode = "200", description = "Election was modified"), ApiResponse( ), ApiResponse(responseCode = "200", description = "Election was modified"), ApiResponse(
responseCode = "401", responseCode = "401",
description = "Unauthorized", description = "Unauthorized",
content = [Content(mediaType = "plain/text")] content = [Content(mediaType = "plain/text")]
)] )]
) )
@PutMapping("/election") @PutMapping("/election")
@SecurityRequirement(name = "bearerAuth") @SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2") @SecurityRequirement(name = "oauth2")
fun putElection(@RequestBody election: Election?): ResponseEntity<*> { fun putElection(@RequestBody election: Election, uriComponentsBuilder: UriComponentsBuilder): Mono<ResponseEntity<Election>> {
val createdNew = service.storeElection(mapper.mapToDB(election!!)) return service.storeElection(mapper.mapToDB(election))
return if (createdNew) ResponseEntity<Any>(HttpStatus.CREATED) else ResponseEntity<Any>(HttpStatus.OK) .map { tuple ->
} Tuples.of(tuple.t1, mapper.mapToExternal(tuple.t2))
}
.map { tuple ->
if (tuple.t1) {
ResponseEntity.created(uriComponentsBuilder.path("/elections/{electionName}")
.buildAndExpand(tuple.t2.name).toUri())
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
} else {
ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
}
}
}
} }
@@ -14,10 +14,12 @@ import io.swagger.v3.oas.annotations.tags.Tag
import lombok.RequiredArgsConstructor import lombok.RequiredArgsConstructor
import lombok.extern.slf4j.Slf4j import lombok.extern.slf4j.Slf4j
import org.mapstruct.factory.Mappers import org.mapstruct.factory.Mappers
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.*
import org.springframework.web.util.UriComponentsBuilder
import reactor.core.publisher.Mono
import reactor.util.function.Tuples
@Slf4j @Slf4j
@RestController @RestController
@@ -25,51 +27,72 @@ import org.springframework.web.bind.annotation.*
@RequestMapping(value = ["/wahlrecht/v1"]) @RequestMapping(value = ["/wahlrecht/v1"])
@Tag(name = "ElectionResults", description = "all requests relating to election results") @Tag(name = "ElectionResults", description = "all requests relating to election results")
class ElectionResultController(private val service: ElectionResultService) { class ElectionResultController(private val service: ElectionResultService) {
private val mapper = Mappers.getMapper(ElectionResultMapper::class.java) private val mapper = Mappers.getMapper(ElectionResultMapper::class.java)
@Operation( @Operation(
summary = "Returns election result for given election name", summary = "Returns election result for given election name",
responses = [ApiResponse( responses = [ApiResponse(
responseCode = "200", responseCode = "200",
description = "Returns stored election result for given election name", description = "Returns stored election result for given election name",
content = [Content(mediaType = "application/json", schema = Schema(implementation = ElectionResult::class))] content = [Content(mediaType = "application/json", schema = Schema(implementation = ElectionResult::class))]
), ApiResponse( ), ApiResponse(
responseCode = "404", responseCode = "404",
description = "No election result found", description = "No election result found",
content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorMessage::class))] content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorMessage::class))]
)] )]
) )
@GetMapping( @GetMapping(
value = ["/electionResult/by-election-name/{electionName}"], value = ["/electionResult/{electionName}"],
produces = [MediaType.APPLICATION_JSON_VALUE] produces = [MediaType.APPLICATION_JSON_VALUE]
) )
@SecurityRequirement(name = "bearerAuth") @SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2") @SecurityRequirement(name = "oauth2")
fun getElectionByName( fun getElectionByName(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String @PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String
): ResponseEntity<ElectionResult> { ): Mono<ResponseEntity<ElectionResult>> {
val result = mapper.mapToExternal(service.getElectionResult(electionName)) return service.getElectionResult(electionName)
return ResponseEntity.ok() .map {
.contentType(MediaType.APPLICATION_JSON) mapper.mapToExternal(it)
.body(result) }
} .map {
ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(it)
}
}
@Operation( @Operation(
summary = "Stores a new election", summary = "Stores a new election",
responses = [ApiResponse( responses = [ApiResponse(
responseCode = "201", responseCode = "201",
description = "Election was created" description = "Election was created"
), ApiResponse(responseCode = "200", description = "Election was modified"), ApiResponse( ), ApiResponse(responseCode = "200", description = "Election was modified"), ApiResponse(
responseCode = "401", responseCode = "401",
description = "Unauthorized", description = "Unauthorized",
content = [Content(mediaType = "plain/text")] content = [Content(mediaType = "plain/text")]
)] )]
) )
@PutMapping("/electionResult") @PutMapping("/electionResult")
@SecurityRequirement(name = "bearerAuth") @SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2") @SecurityRequirement(name = "oauth2")
fun putElection(@RequestBody electionResult: ElectionResult?): ResponseEntity<*> { fun putElection(@RequestBody electionResult: ElectionResult,
val createdNew = service.storeResult(mapper.mapToDB(electionResult!!)) uriComponentsBuilder: UriComponentsBuilder): Mono<ResponseEntity<ElectionResult>> {
return if (createdNew) ResponseEntity<Any>(HttpStatus.CREATED) else ResponseEntity<Any>(HttpStatus.OK) val storedElection = service.storeResult(mapper.mapToDB(electionResult))
} return storedElection
.map { tuple ->
Tuples.of(tuple.t1, mapper.mapToExternal(tuple.t2))
}
.map { tuple ->
if (tuple.t1) {
ResponseEntity.created(uriComponentsBuilder.path("/electionResult/{electionName}")
.buildAndExpand(tuple.t2.electionName).toUri())
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
} else {
ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
}
}
}
} }
@@ -1,5 +1,6 @@
package de.twomartens.wahlrecht.controller.v1 package de.twomartens.wahlrecht.controller.v1
import de.twomartens.wahlrecht.property.ServiceProperties
import io.swagger.v3.oas.annotations.Hidden import io.swagger.v3.oas.annotations.Hidden
import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMapping
@@ -7,11 +8,12 @@ import org.springframework.web.bind.annotation.RestController
@RestController @RestController
@RequestMapping(value = ["/wahlrecht/v1"]) @RequestMapping(value = ["/wahlrecht/v1"])
class HealthCheckController { class HealthCheckController(private val properties: ServiceProperties) {
@Hidden @Hidden
@GetMapping("/healthCheck") @GetMapping("/healthCheck")
fun healthCheck(message: String): String { fun healthCheck(message: String): String {
return message return properties.greeting.format(message)
} }
} }
@@ -13,65 +13,115 @@ import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.security.SecurityRequirement import io.swagger.v3.oas.annotations.security.SecurityRequirement
import io.swagger.v3.oas.annotations.tags.Tag import io.swagger.v3.oas.annotations.tags.Tag
import org.mapstruct.factory.Mappers import org.mapstruct.factory.Mappers
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity import org.springframework.http.ResponseEntity
import org.springframework.http.ResponseEntity.created
import org.springframework.http.ResponseEntity.ok
import org.springframework.stereotype.Controller import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.*
import org.springframework.web.util.UriComponentsBuilder
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuples
@Controller @Controller
@RequestMapping(value = ["/wahlrecht/v1"]) @RequestMapping(value = ["/wahlrecht/v1"])
@Tag(name = "Parties", description = "all requests relating to parties") @Tag(name = "Parties", description = "all requests relating to parties")
class PartyController(private val service: PartyService) { class PartyController(private val service: PartyService) {
private val mapper = Mappers.getMapper(PartyInElectionMapper::class.java) private val mapper = Mappers.getMapper(PartyInElectionMapper::class.java)
@Operation(
summary = "Returns all stored parties for given election name",
responses = [ApiResponse(
responseCode = "200",
description = "Returns all stored parties",
content = [Content(
mediaType = "application/json",
array = ArraySchema(schema = Schema(implementation = PartyInElection::class))
)]
), ApiResponse(
responseCode = "404",
description = "No parties found",
content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorMessage::class))]
)]
)
@GetMapping(value = ["/parties/by-election-name/{electionName}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun getPartiesByElectionName(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String
): ResponseEntity<Collection<PartyInElection>> {
val parties = service.getPartiesByElectionName(electionName).stream()
.map { election: de.twomartens.wahlrecht.model.db.PartyInElection? ->
mapper.mapToExternal(
election!!
)
}
.toList()
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_JSON)
.body(parties)
}
@Operation( @Operation(
summary = "Stores a new party in an election", summary = "Returns all stored parties for given election name",
responses = [ApiResponse( responses = [ApiResponse(
responseCode = "201", responseCode = "200",
description = "Party was created" description = "Returns all stored parties",
), ApiResponse(responseCode = "200", description = "Party was modified"), ApiResponse( content = [Content(
responseCode = "401", mediaType = "application/json",
description = "Unauthorized" array = ArraySchema(schema = Schema(implementation = PartyInElection::class))
)] )]
) ), ApiResponse(
@PutMapping("/party") responseCode = "404",
@SecurityRequirement(name = "bearerAuth") description = "No parties found",
@SecurityRequirement(name = "oauth2") content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorMessage::class))]
fun putParty(@RequestBody party: PartyInElection?): ResponseEntity<*> { )]
val createdNew = service.storeParty(mapper.mapToDB(party!!)) )
return if (createdNew) ResponseEntity<Any>(HttpStatus.CREATED) else ResponseEntity<Any>(HttpStatus.OK) @GetMapping(value = ["/parties/by-election-name/{electionName}"], produces = [MediaType.APPLICATION_JSON_VALUE])
} @SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun getPartiesByElectionName(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String
): ResponseEntity<Flux<PartyInElection>> {
val parties = service.getPartiesByElectionName(electionName)
.map { election: de.twomartens.wahlrecht.model.db.PartyInElection ->
mapper.mapToExternal(election)
}
return ok()
.contentType(MediaType.APPLICATION_JSON)
.body(parties)
}
@Operation(
summary = "Returns party stored for given election name and abbreviation",
responses = [ApiResponse(
responseCode = "200",
description = "Returns stored party",
content = [Content(
mediaType = "application/json",
schema = Schema(implementation = PartyInElection::class)
)]
), ApiResponse(
responseCode = "404",
description = "No party found",
content = [Content(mediaType = "application/json", schema = Schema(implementation = ErrorMessage::class))]
)]
)
@GetMapping(value = ["/parties/{electionName}/{abbreviation}"], produces = [MediaType.APPLICATION_JSON_VALUE])
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun getPartyByElectionNameAndAbbreviation(
@PathVariable @Parameter(description = "the election name", example = "Bezirkswahl 2019") electionName: String,
@PathVariable @Parameter(description = "the party abbreviation", example = "SPD") abbreviation: String
): ResponseEntity<Mono<PartyInElection>> {
val party = service.getPartyByElectionNameAndAbbreviation(electionName, abbreviation)
.map { stored: de.twomartens.wahlrecht.model.db.PartyInElection ->
mapper.mapToExternal(stored)
}
return ok()
.contentType(MediaType.APPLICATION_JSON)
.body(party)
}
@Operation(
summary = "Stores a new party in an election",
responses = [ApiResponse(
responseCode = "201",
description = "Party was created"
), ApiResponse(responseCode = "200", description = "Party was modified"), ApiResponse(
responseCode = "401",
description = "Unauthorized"
)]
)
@PutMapping("/party")
@SecurityRequirement(name = "bearerAuth")
@SecurityRequirement(name = "oauth2")
fun putParty(@RequestBody party: PartyInElection,
uriComponentsBuilder: UriComponentsBuilder): Mono<ResponseEntity<PartyInElection>> {
val storedParty = service.storeParty(mapper.mapToDB(party))
return storedParty
.map { tuple ->
Tuples.of(tuple.t1, mapper.mapToExternal(tuple.t2))
}
.map { tuple ->
if (tuple.t1) {
created(uriComponentsBuilder.path("/parties/{electionName}/{abbreviation}")
.buildAndExpand(tuple.t2.electionName, tuple.t2.abbreviation).toUri())
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
} else {
ok()
.contentType(MediaType.APPLICATION_JSON)
.body(tuple.t2)
}
}
}
} }
@@ -7,27 +7,30 @@ import org.springframework.data.annotation.Id
import org.springframework.data.annotation.LastModifiedDate import org.springframework.data.annotation.LastModifiedDate
import org.springframework.data.mongodb.core.index.CompoundIndex import org.springframework.data.mongodb.core.index.CompoundIndex
import org.springframework.data.mongodb.core.mapping.Document import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.core.mapping.DocumentReference
import java.time.Instant import java.time.Instant
@Document @Document
@EqualsAndHashCode @EqualsAndHashCode
@CompoundIndex(def = "{'name': 1, 'partyAbbreviation': 1, 'electionName': 1}") @CompoundIndex(def = "{'name': 1, 'partyAbbreviation': 1, 'electionName': 1}")
class Nomination { class Nomination {
@EqualsAndHashCode.Exclude @EqualsAndHashCode.Exclude
@Id @Id
var id: ObjectId? = null var id: ObjectId? = null
@EqualsAndHashCode.Exclude @EqualsAndHashCode.Exclude
@CreatedDate @CreatedDate
var created: Instant? = null var created: Instant? = null
@EqualsAndHashCode.Exclude @EqualsAndHashCode.Exclude
@LastModifiedDate @LastModifiedDate
var lastModified: Instant? = null var lastModified: Instant? = null
var name: String = "" var name: String = ""
var partyAbbreviation: String = "" var partyAbbreviation: String = ""
var electionName: String = "" var electionName: String = ""
var candidates: Collection<Candidate> = emptyList()
var supportVotesOnNomination = false @DocumentReference
var candidates: Collection<Candidate> = emptyList()
var supportVotesOnNomination = false
} }
@@ -1,6 +1,7 @@
package de.twomartens.wahlrecht.monitoring.actuator package de.twomartens.wahlrecht.monitoring.actuator
import de.twomartens.wahlrecht.interceptor.HeaderInterceptorRest import de.twomartens.wahlrecht.interceptor.HeaderInterceptorRest
import de.twomartens.wahlrecht.property.ServiceProperties
import org.springframework.boot.actuate.health.Health import org.springframework.boot.actuate.health.Health
import org.springframework.boot.actuate.health.HealthIndicator import org.springframework.boot.actuate.health.HealthIndicator
import org.springframework.boot.actuate.health.Status import org.springframework.boot.actuate.health.Status
@@ -28,8 +29,10 @@ import java.time.Clock
*/ */
@Component @Component
class RestHealthIndicator( class RestHealthIndicator(
clock: Clock, interceptor: HeaderInterceptorRest, clock: Clock, interceptor: HeaderInterceptorRest,
serverProperties: ServerProperties, private val restTemplateRestHealthIndicator: RestTemplate serverProperties: ServerProperties,
private val restTemplateRestHealthIndicator: RestTemplate,
private val serviceProperties: ServiceProperties
) : AbstractHealthIndicator(clock, Preparable { interceptor.markAsHealthCheck() }), HealthIndicator { ) : AbstractHealthIndicator(clock, Preparable { interceptor.markAsHealthCheck() }), HealthIndicator {
private val randomizer = SecureRandom() private val randomizer = SecureRandom()
private val urlPrefix: String = (HTTP_PREFIX + HOST + HOST_PORT_SEPARATOR private val urlPrefix: String = (HTTP_PREFIX + HOST + HOST_PORT_SEPARATOR
@@ -43,10 +46,10 @@ class RestHealthIndicator(
val random = randomizer.nextInt(100000, 999999).toString() val random = randomizer.nextInt(100000, 999999).toString()
val url = "$urlPrefix{random}" val url = "$urlPrefix{random}"
val response = restTemplateRestHealthIndicator.getForEntity(url, String::class.java, random) val response = restTemplateRestHealthIndicator.getForEntity(url, String::class.java, random)
val status = if (response.body == random) Status.UP else Status.DOWN val status = if (response.body == serviceProperties.greeting.format(random)) Status.UP else Status.DOWN
return Health.status(status) return Health.status(status)
.withDetail(DETAIL_ENDPOINT_KEY, url) .withDetail(DETAIL_ENDPOINT_KEY, url)
.build() .build()
} }
companion object { companion object {
@@ -2,11 +2,13 @@ package de.twomartens.wahlrecht.property
import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.media.Schema
import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.bind.ConstructorBinding
import org.springframework.cloud.context.config.annotation.RefreshScope import org.springframework.cloud.context.config.annotation.RefreshScope
import java.time.ZoneId import java.time.ZoneId
@RefreshScope @RefreshScope
@ConfigurationProperties(prefix = "de.twomartens.wahlrecht") @ConfigurationProperties(prefix = "de.twomartens.wahlrecht")
@Schema(description = "Properties, to configure this Application") @Schema(description = "Properties, to configure this Application")
data class ServiceProperties @ConstructorBinding constructor(val defaultTimeZone: ZoneId, val greeting: String) class ServiceProperties {
lateinit var defaultTimeZone: ZoneId
lateinit var greeting: String
}
@@ -1,6 +1,31 @@
package de.twomartens.wahlrecht.repository package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.Candidate import de.twomartens.wahlrecht.model.db.Candidate
import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
interface CandidateRepository : MongoRepository<Candidate, String> interface CandidateRepository : ReactiveMongoRepository<Candidate, String> {
fun findByName(name: String): Mono<Candidate>
fun findAndModify(new: Candidate): Mono<Candidate> {
val existing = findByName(new.name)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.profession = new.profession
save(old)
}
} else {
save(new)
}
}
}
fun findAllAndModify(new: Collection<Candidate>): Flux<Candidate> {
val existing = new.map {
findAndModify(it)
}
return Flux.merge(existing)
}
}
@@ -1,6 +1,27 @@
package de.twomartens.wahlrecht.repository package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.Constituency import de.twomartens.wahlrecht.model.db.Constituency
import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Mono
interface ConstituencyRepository : MongoRepository<Constituency, String> interface ConstituencyRepository : ReactiveMongoRepository<Constituency, String> {
fun findByElectionNameAndNumber(electionName: String, number: Int): Mono<Constituency>
fun findAndModify(new: Constituency): Mono<Constituency> {
val existing = findByElectionNameAndNumber(
new.electionName,
new.number)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.name = new.name
old.numberOfSeats = new.numberOfSeats
save(old)
}
} else {
save(new)
}
}
}
}
@@ -1,6 +1,27 @@
package de.twomartens.wahlrecht.repository package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.Election import de.twomartens.wahlrecht.model.db.Election
import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
interface ElectionRepository : MongoRepository<Election, String> interface ElectionRepository : ReactiveMongoRepository<Election, String> {
fun findByName(name: String): Mono<Election>
fun findAndModify(new: Election): Mono<Tuple2<Boolean, Election>> {
val electionName = new.name
val existing = findByName(electionName)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.constituencies = new.constituencies
old.totalNumberOfSeats = new.totalNumberOfSeats
old.votingThreshold = new.votingThreshold
Mono.just(false).zipWith(save(old))
}
} else {
Mono.just(true).zipWith(save(new))
}
}
}
}
@@ -1,6 +1,25 @@
package de.twomartens.wahlrecht.repository package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.ElectionResult import de.twomartens.wahlrecht.model.db.ElectionResult
import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
interface ElectionResultRepository : MongoRepository<ElectionResult, String> interface ElectionResultRepository : ReactiveMongoRepository<ElectionResult, String> {
fun findByElectionName(electionName: String): Mono<ElectionResult>
fun findAndModify(new: ElectionResult): Mono<Tuple2<Boolean, ElectionResult>> {
val existing = findByElectionName(new.electionName)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.overallResults = new.overallResults
old.constituencyResults = new.constituencyResults
Mono.just(false).zipWith(save(old))
}
} else {
Mono.just(true).zipWith(save(new))
}
}
}
}
@@ -1,6 +1,31 @@
package de.twomartens.wahlrecht.repository package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.Nomination import de.twomartens.wahlrecht.model.db.Nomination
import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Mono
import reactor.core.scheduler.Schedulers
interface NominationRepository : MongoRepository<Nomination, String> interface NominationRepository : ReactiveMongoRepository<Nomination, String> {
fun findByElectionNameAndPartyAbbreviationAndName(electionName: String,
abbreviation: String,
name: String): Mono<Nomination>
fun findAndModify(new: Nomination): Mono<Nomination> {
val existing = findByElectionNameAndPartyAbbreviationAndName(
new.electionName,
new.partyAbbreviation,
new.name
)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.publishOn(Schedulers.boundedElastic()).publishOn(Schedulers.boundedElastic()).flatMap { old ->
old.supportVotesOnNomination = new.supportVotesOnNomination
old.candidates = new.candidates
save(old)
}
} else {
save(new)
}
}
}
}
@@ -1,8 +1,30 @@
package de.twomartens.wahlrecht.repository package de.twomartens.wahlrecht.repository
import de.twomartens.wahlrecht.model.db.PartyInElection import de.twomartens.wahlrecht.model.db.PartyInElection
import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
interface PartyRepository : MongoRepository<PartyInElection, String> { interface PartyRepository : ReactiveMongoRepository<PartyInElection, String> {
fun findByElectionName(name: String): Collection<PartyInElection>
fun findByElectionName(name: String): Flux<PartyInElection>
fun findByElectionNameAndAbbreviation(electionName: String, abbreviation: String): Mono<PartyInElection>
fun findAndModify(party: PartyInElection): Mono<Tuple2<Boolean, PartyInElection>> {
val existing = findByElectionNameAndAbbreviation(party.electionName, party.abbreviation)
return existing.hasElement().flatMap { hasElement ->
if (hasElement) {
existing.flatMap { old ->
old.name = party.name
old.overallNomination = party.overallNomination
old.constituencyNominations = party.constituencyNominations
Mono.just(false).zipWith(save(old))
}
} else {
Mono.just(true).zipWith(save(party))
}
}
}
} }
@@ -17,9 +17,9 @@ class CalculationService(
log.info("Calculate election result for election {}", electionResult.electionName) log.info("Calculate election result for election {}", electionResult.electionName)
val stopWatch = StopWatch() val stopWatch = StopWatch()
stopWatch.start("determineElectedCandidates") stopWatch.start("determineElectedCandidates")
val election = electionService.getElectionInternal(electionResult.electionName) val election = electionService.getElectionInternal(electionResult.electionName).block()
val seatResult = calculateOverallSeatDistribution( val seatResult = calculateOverallSeatDistribution(
election, election!!,
electionResult.overallResults electionResult.overallResults
) )
val constituencyResults: MutableMap<Int, ElectedResult> = HashMap() val constituencyResults: MutableMap<Int, ElectedResult> = HashMap()
@@ -192,8 +192,8 @@ class CalculationService(
.toMap() .toMap()
.toMutableMap() .toMutableMap()
val nominationId = votingResult.nominationId val nominationId = votingResult.nominationId
val nomination = nominationService.getNominationInternal(nominationId) val nomination = nominationService.getNominationInternal(nominationId).block()
if (nomination.supportsVotesOnNomination()) { if (nomination!!.supportsVotesOnNomination()) {
val seatsByNomination = calculateSeatsByNominationOrder(votingResult, numberOfSeats) val seatsByNomination = calculateSeatsByNominationOrder(votingResult, numberOfSeats)
seatsByVoteOrder = numberOfSeats - seatsByNomination seatsByVoteOrder = numberOfSeats - seatsByNomination
val candidates = nomination.getCandidates() val candidates = nomination.getCandidates()
@@ -3,33 +3,17 @@ package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.model.db.Candidate import de.twomartens.wahlrecht.model.db.Candidate
import de.twomartens.wahlrecht.repository.CandidateRepository import de.twomartens.wahlrecht.repository.CandidateRepository
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Service @Service
class CandidateService(private val repository: CandidateRepository) { class CandidateService(private val repository: CandidateRepository) {
private val candidates: MutableMap<String, Candidate> by lazy {
fetchCandidates()
}
fun storeCandidate(candidate: Candidate): Candidate { fun storeCandidate(candidate: Candidate): Mono<Candidate> {
var result = candidate return repository.findAndModify(candidate)
val existing = candidates[candidate.name] }
val needsUpdate = candidate != existing
if (!needsUpdate && existing != null) {
return existing
}
if (existing != null) {
existing.profession = candidate.profession
result = existing
}
result = repository.save(result)
candidates[candidate.name] = candidate
return result
}
private fun fetchCandidates(): MutableMap<String, Candidate> { fun storeCandidates(candidates: Collection<Candidate>): Flux<Candidate> {
return repository.findAll().asSequence() return Flux.merge(candidates.map { storeCandidate(it) })
.map { Pair(it.name, it) } }
.toMap()
.toMutableMap()
}
} }
@@ -1,40 +1,14 @@
package de.twomartens.wahlrecht.service package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.model.db.Constituency import de.twomartens.wahlrecht.model.db.Constituency
import de.twomartens.wahlrecht.model.internal.ConstituencyId
import de.twomartens.wahlrecht.repository.ConstituencyRepository import de.twomartens.wahlrecht.repository.ConstituencyRepository
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
@Service @Service
class ConstituencyService(private val repository: ConstituencyRepository) { class ConstituencyService(private val repository: ConstituencyRepository) {
private val constituencies: MutableMap<ConstituencyId, Constituency> by lazy {
fetchConstituencies()
}
fun storeConstituency(constituency: Constituency): Constituency { fun storeConstituencies(constituencies: Collection<Constituency>): Flux<Constituency> {
var result = constituency return Flux.merge(constituencies.map { repository.findAndModify(it) })
val constituencyId = ConstituencyId( }
constituency.electionName,
constituency.number
)
val existing = constituencies[constituencyId]
if (constituency == existing) {
return existing
}
if (existing != null) {
existing.numberOfSeats = constituency.numberOfSeats
existing.name = constituency.name
result = existing
}
val stored = repository.save(result)
constituencies[constituencyId] = stored
return stored
}
private fun fetchConstituencies(): MutableMap<ConstituencyId, Constituency> {
return repository.findAll().asSequence()
.map { Pair(ConstituencyId(electionName = it.electionName, number = it.number), it) }
.toMap()
.toMutableMap()
}
} }
@@ -5,45 +5,20 @@ import de.twomartens.wahlrecht.repository.ElectionResultRepository
import org.springframework.http.HttpStatus import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException import org.springframework.web.server.ResponseStatusException
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
@Service @Service
class ElectionResultService(private val repository: ElectionResultRepository) { class ElectionResultService(private val repository: ElectionResultRepository) {
private val electionResults: MutableMap<String, ElectionResult> by lazy {
fetchResults()
}
fun getElectionResult(electionName: String): ElectionResult {
return electionResults[electionName]
?: throw ResponseStatusException(
HttpStatus.NOT_FOUND,
"no election result found for $electionName"
)
}
fun storeResult(electionResult: ElectionResult): Boolean { fun getElectionResult(electionName: String): Mono<ElectionResult> {
var result = electionResult return repository.findByElectionName(electionName)
.switchIfEmpty(Mono.error(
ResponseStatusException(HttpStatus.NOT_FOUND, "no election result found for $electionName")
))
}
val id = result.electionName fun storeResult(new: ElectionResult): Mono<Tuple2<Boolean, ElectionResult>> {
val existing = electionResults[id] return repository.findAndModify(new)
val needsUpdate = result != existing }
if (!needsUpdate) {
return false
}
var createdNew = true
if (existing != null) {
existing.overallResults = result.overallResults
existing.constituencyResults = result.constituencyResults
result = existing
createdNew = false
}
val stored = repository.save(result)
electionResults[id] = stored
return createdNew
}
private fun fetchResults(): MutableMap<String, ElectionResult> {
return repository.findAll().asSequence()
.map { Pair(it.electionName, it) }
.toMap()
.toMutableMap()
}
} }
@@ -1,60 +1,35 @@
package de.twomartens.wahlrecht.service package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.mapper.v1.ElectionMapper import de.twomartens.wahlrecht.mapper.v1.ElectionMapper
import de.twomartens.wahlrecht.model.db.Constituency
import de.twomartens.wahlrecht.model.db.Election import de.twomartens.wahlrecht.model.db.Election
import de.twomartens.wahlrecht.repository.ElectionRepository import de.twomartens.wahlrecht.repository.ElectionRepository
import org.mapstruct.factory.Mappers import org.mapstruct.factory.Mappers
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
@Service @Service
class ElectionService( class ElectionService(
private val electionRepository: ElectionRepository, private val electionRepository: ElectionRepository
private val constituencyService: ConstituencyService
) { ) {
private val electionMapper = Mappers.getMapper(ElectionMapper::class.java) private val electionMapper = Mappers.getMapper(ElectionMapper::class.java)
private val _elections: MutableMap<String, Election> by lazy {
fetchElections()
}
val elections: Map<String, Election> = _elections fun getElections(): Flux<Election> {
return electionRepository.findAll()
}
private fun getElection(electionName: String): Election? { fun findElectionByName(electionName: String): Mono<Election> {
return elections[electionName] return electionRepository.findByName(electionName)
} }
fun getElectionInternal(electionName: String): de.twomartens.wahlrecht.model.internal.Election { fun getElectionInternal(electionName: String): Mono<de.twomartens.wahlrecht.model.internal.Election> {
return electionMapper.mapToInternal(getElection(electionName)!!) return findElectionByName(electionName).map {
electionMapper.mapToInternal(it)
} }
}
fun storeElection(election: Election): Boolean { fun storeElection(new: Election): Mono<Tuple2<Boolean, Election>> {
var result = election return electionRepository.findAndModify(new)
var createdNew = true }
val electionName = election.name
val existing = elections[electionName]
if (election == existing) {
return false
}
val constituencies: MutableCollection<Constituency> = mutableListOf()
result.constituencies
.forEach { constituencies.add(constituencyService.storeConstituency(it)) }
if (existing != null) {
existing.day = election.day
existing.totalNumberOfSeats = election.totalNumberOfSeats
existing.votingThreshold = election.votingThreshold
result = existing
createdNew = false
}
result.constituencies = constituencies
val stored = electionRepository.save(result)
_elections[electionName] = stored
return createdNew
}
private fun fetchElections(): MutableMap<String, Election> {
return electionRepository.findAll().asSequence()
.map { Pair(it.name, it) }
.toMap()
.toMutableMap()
}
} }
@@ -1,69 +1,41 @@
package de.twomartens.wahlrecht.service package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.mapper.v1.NominationMapper import de.twomartens.wahlrecht.mapper.v1.NominationMapper
import de.twomartens.wahlrecht.model.db.Candidate
import de.twomartens.wahlrecht.model.db.Nomination import de.twomartens.wahlrecht.model.db.Nomination
import de.twomartens.wahlrecht.model.internal.NominationId import de.twomartens.wahlrecht.model.internal.NominationId
import de.twomartens.wahlrecht.repository.NominationRepository import de.twomartens.wahlrecht.repository.NominationRepository
import org.mapstruct.factory.Mappers import org.mapstruct.factory.Mappers
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
@Service @Service
class NominationService( class NominationService(
private val repository: NominationRepository, private val repository: NominationRepository
private val candidateService: CandidateService
) { ) {
private val mapper = Mappers.getMapper(NominationMapper::class.java) private val mapper = Mappers.getMapper(NominationMapper::class.java)
private val nominations: MutableMap<NominationId, Nomination> by lazy {
fetchNominations()
}
fun getNominationInternal(id: NominationId): de.twomartens.wahlrecht.model.internal.Nomination { fun getNominationInternal(id: NominationId): Mono<de.twomartens.wahlrecht.model.internal.Nomination> {
return mapper.mapToInternal(getNomination(id)!!) return getNomination(id).map {
mapper.mapToInternal(it)
} }
}
fun storeNomination(nomination: Nomination?): Nomination? { fun storeNomination(new: Nomination?): Mono<Nomination> {
if (nomination == null) return null if (new == null) return Mono.empty()
val nominationId = NominationId(
nomination.electionName,
nomination.partyAbbreviation,
nomination.name
)
val existing = nominations[nominationId]
val needsUpdate = nomination != existing
if (!needsUpdate) {
return existing
}
var result: Nomination = nomination
val candidates: MutableCollection<Candidate> = ArrayList()
result.candidates
.forEach { candidates.add(candidateService.storeCandidate(it)) }
if (existing != null) {
result = existing
}
result.candidates = candidates
result = repository.save(nomination)
nominations[nominationId] = result
return result
}
private fun getNomination(id: NominationId): Nomination? { return repository.findAndModify(new)
return nominations[id] }
}
private fun fetchNominations(): MutableMap<NominationId, Nomination> { fun storeNominations(new: Collection<Nomination>): Flux<Nomination> {
return repository.findAll().asSequence() return Flux.merge(new.map { storeNomination(it) })
.map { }
Pair(
NominationId( private fun getNomination(id: NominationId): Mono<Nomination> {
electionName = it.electionName, return repository.findByElectionNameAndPartyAbbreviationAndName(
partyAbbreviation = it.partyAbbreviation, id.electionName,
name = it.name id.partyAbbreviation,
), id.name
it )
) }
}
.toMap()
.toMutableMap()
}
} }
@@ -1,66 +1,32 @@
package de.twomartens.wahlrecht.service package de.twomartens.wahlrecht.service
import de.twomartens.wahlrecht.model.db.Nomination
import de.twomartens.wahlrecht.model.db.PartyInElection import de.twomartens.wahlrecht.model.db.PartyInElection
import de.twomartens.wahlrecht.model.internal.PartyId
import de.twomartens.wahlrecht.repository.PartyRepository import de.twomartens.wahlrecht.repository.PartyRepository
import org.springframework.http.HttpStatus import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service import org.springframework.stereotype.Service
import org.springframework.web.server.ResponseStatusException import org.springframework.web.server.ResponseStatusException
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.util.function.Tuple2
@Service @Service
class PartyService( class PartyService(
private val partyRepository: PartyRepository, private val partyRepository: PartyRepository
private val nominationService: NominationService
) { ) {
private val parties: MutableMap<PartyId, PartyInElection> by lazy { fun getPartiesByElectionName(electionName: String): Flux<PartyInElection> {
fetchParties() return partyRepository.findByElectionName(electionName)
} .switchIfEmpty(Flux.error(
ResponseStatusException(HttpStatus.NOT_FOUND, "no party found for $electionName")
))
}
fun getPartiesByElectionName(electionName: String): Collection<PartyInElection> { fun getPartyByElectionNameAndAbbreviation(electionName: String,
val parties = partyRepository.findByElectionName(electionName) abbreviation: String): Mono<PartyInElection> {
if (parties.isEmpty()) { return partyRepository.findByElectionNameAndAbbreviation(electionName, abbreviation)
throw ResponseStatusException(HttpStatus.NOT_FOUND, "no party found for $electionName") }
}
return parties
}
fun storeParty(partyInElection: PartyInElection): Boolean { fun storeParty(new: PartyInElection): Mono<Tuple2<Boolean, PartyInElection>> {
var result = partyInElection return partyRepository.findAndModify(new)
var createdNew = true }
val partyId = PartyId(
partyInElection.electionName,
partyInElection.abbreviation
)
val existing = parties[partyId]
val needsUpdate = partyInElection != existing
if (!needsUpdate) {
return false
}
val constituencyNominations: MutableMap<Int, Nomination> = mutableMapOf()
result.constituencyNominations
.forEach { constituencyNominations[it.key] = nominationService.storeNomination(it.value)!! }
if (existing != null) {
existing.name = partyInElection.name
if (constituencyNominations.isEmpty()) {
constituencyNominations.putAll(existing.constituencyNominations)
}
result = existing
createdNew = false
}
partyInElection.constituencyNominations = constituencyNominations
partyInElection.overallNomination = nominationService.storeNomination(partyInElection.overallNomination)!!
result = partyRepository.save(result)
parties[partyId] = result
return createdNew
}
private fun fetchParties(): MutableMap<PartyId, PartyInElection> {
val allParties = partyRepository.findAll()
return allParties.asSequence()
.map { Pair(PartyId(electionName = it.electionName, abbreviation = it.abbreviation), it) }
.toMap()
.toMutableMap()
}
} }
@@ -1,41 +0,0 @@
package de.twomartens.wahlrecht.service
import mu.KotlinLogging
import org.apache.logging.log4j.message.StringMapMessage
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.cloud.context.refresh.ContextRefresher
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit
/**
* automatically reloads application*.yaml. reload can also be triggered manually by doing a post
* request on http://localhost:12001/actuator/refresh
*/
@Service
class PropertyReloadService(@Qualifier("configDataContextRefresher") private val contextRefresher: ContextRefresher) {
@Scheduled(
fixedDelay = REFRESH_SECONDS.toLong(),
initialDelay = REFRESH_SECONDS.toLong(),
timeUnit = TimeUnit.SECONDS
)
fun refresh() {
val properties = contextRefresher.refresh()
if (properties.isNotEmpty()) {
log.info(
StringMapMessage()
.with(PARAM_MESSAGE, "properties changed")
.with(PARAM_PROPERTIES, properties.joinToString("\n"))
.asString()
)
}
}
companion object {
const val REFRESH_SECONDS = 60
const val PARAM_MESSAGE = "message"
const val PARAM_PROPERTIES = "labels.properties"
private val log = KotlinLogging.logger {}
}
}
@@ -1,2 +1,9 @@
server.port: 12000 server.port: 12000
management.server.port: 12001 management.server.port: 12001
spring:
config:
import:
- "classpath:config/wahlrecht.yaml"
- "optional:configserver:http://localhost:8888/config"
@@ -0,0 +1,7 @@
spring:
config:
import:
- "configserver:http://configserver:8888/config"
kafka:
bootstrap-servers:
- kafka:9092
@@ -23,9 +23,9 @@ management:
http.server.requests: true http.server.requests: true
spring: spring:
spring: cloud:
config: config:
import: "optional:configserver:http://localhost:8888/config" name: wahlrecht
main: main:
banner-mode: off banner-mode: off
profiles: profiles:
@@ -41,17 +41,6 @@ spring:
application: application:
name: wahlrecht name: wahlrecht
# properties for application
de.twomartens.wahlrecht:
defaultTimeZone: Europe/Berlin
greeting: "Hello %s"
statusprobe:
scheduleDuration: 60
maxKafkaFailureDuration: 5
maxBlobFailureCount: 5
maxFailurePercent: 50
springdoc: springdoc:
swagger-ui: swagger-ui:
display-request-duration: true display-request-duration: true
@@ -0,0 +1,2 @@
de.twomartens.wahlrecht:
greeting: "Moin %s, you are test"
@@ -0,0 +1,8 @@
de.twomartens.wahlrecht:
defaultTimeZone: Europe/Berlin
greeting: "Hello %s, on millenium"
statusprobe:
scheduleDuration: 60
maxKafkaFailureDuration: 5
maxBlobFailureCount: 5
maxFailurePercent: 50
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
./gradlew -Prelease.scope=major $@
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
./gradlew -Prelease.scope=minor $@
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
./gradlew -Prelease.scope=patch $@